/*
 Author: Obrtac Tomas  
 Mail: obrtac.tomas@gmail.com
 2017
 */

#include "RN_commands.h"


// Simple funciton for sending commands throw UART
void RN_SendCommand(char command[]){
    char uart[64];
    sprintf(uart,"%s\r\n",command); // You have to add CR+LF
    UART_PutStr2(uart); 
}

// Waiting until some characetrs come
void RN_ReadResponse(void){
    //while (!UART_CharAvailable2())
    while (UART_CharAvailable2()){
            UART_GetChar2();  
        }
}

void RN_InitializationCommands(void){
    RN_SendCommand("clr"); // Send empty command for makeing sure that nothing left on the bus
    RN_ReadResponse();
    Delay_ms10(10);
    RN_SendCommand("mac set devaddr 12344321"); // Set Devaddr
    RN_ReadResponse(); // Wait for response
    Delay_ms10(30);
    RN_SendCommand("mac set appskey 12345678901234567890123456788888"); // Set Appskey
    RN_ReadResponse(); // Wait for response
    Delay_ms10(20);
    RN_SendCommand("mac set nwkskey 12345678901234567890123456789000"); // Set Nwkskey
    Delay_ms10(20);
    RN_SendCommand("mac save"); // Write parameters to EEPROM
    RN_ReadResponse(); // Wait for response
    Delay_ms10(100);
    RN_SendCommand("mac join abp"); // Join to the network
}

// Commands for waking up 
void RN_WakeUpEvent(void)
{
    UART_PutChar2(0x00); 
    UART_PutChar2(0x55);
    return;
}

// Simple delay function
void Delay_ms10(int x)
{
    int i;
    for (i = 0; i < x; i++) __delay_ms(10); 
    return;
}