while (1)
{
switch (State)
{
case RX:
if (isMaster == true)
{
if (BufferSize > 0)
{
if (strncmp((const char *)Buffer, (const char *)PongMsg, 4) == 0)
{
printf("Received: PONG\r\n");
// Send the next PING frame
Buffer[0] = 'P';
Buffer[1] = 'I';
Buffer[2] = 'N';
Buffer[3] = 'G';
// We fill the buffer with numbers for the payload
for (i = 4; i < BufferSize; i++)
{
Buffer[i] = i - 4;
}
delay_ms(10);
printf("Sent: PING\r\n");
#ifdef REINIT_FLAG
Radio_TX_Resetting();
#endif
Radio.Send(Buffer, BufferSize);
}
else if (strncmp((const char *)Buffer, (const char *)PingMsg, 4) == 0)
{ // A master already exists then become a slave
isMaster = false;
#ifdef REINIT_FLAG
Radio_RX_Resetting();
#endif
Radio.Rx(LORA_RX_TIMEOUT_VALUE);
}
else // valid reception but neither a PING or a PONG message
{ // Set device as master ans start again
isMaster = true;
#ifdef REINIT_FLAG
Radio_RX_Resetting();
#endif
Radio.Rx(LORA_RX_TIMEOUT_VALUE);
}
}
}
else
{
if (BufferSize > 0)
{
if (strncmp((const char *)Buffer, (const char *)PingMsg, 4) == 0)
{
printf("Received: PING\r\n");
// Send the reply to the PONG string
Buffer[0] = 'P';
Buffer[1] = 'O';
Buffer[2] = 'N';
Buffer[3] = 'G';
// We fill the buffer with numbers for the payload
for (i = 4; i < BufferSize; i++)
{
Buffer[i] = i - 4;
}
delay_ms(10);
#ifdef REINIT_FLAG
Radio_TX_Resetting();
#endif
Radio.Send(Buffer, BufferSize);
printf("Sent: PONG\r\n");
}
else // valid reception but not a PING as expected
{ // Set device as master and start again
isMaster = true;
#ifdef REINIT_FLAG
Radio_RX_Resetting();
#endif
Radio.Rx(LORA_RX_TIMEOUT_VALUE);
}
}
}
State = LOWPOWER;
break;
case TX:
#ifdef REINIT_FLAG
Radio_RX_Resetting();
#endif
Radio.Rx(LORA_RX_TIMEOUT_VALUE);
State = LOWPOWER;
break;
case RX_TIMEOUT:
case RX_ERROR:
if (isMaster == true)
{
// Send the next PING frame
Buffer[0] = 'P';
Buffer[1] = 'I';
Buffer[2] = 'N';
Buffer[3] = 'G';
for (i = 4; i < BufferSize; i++)
{
Buffer[i] = i - 4;
}
random = (rand() + 1) % 90;
delay_ms(random);
#ifdef REINIT_FLAG
Radio_TX_Resetting();
#endif
Radio.Send(Buffer, BufferSize);
printf("Sent: PING\r\n");
}
else
{
#ifdef REINIT_FLAG
Radio_RX_Resetting();
#endif
Radio.Rx(LORA_RX_TIMEOUT_VALUE);
}
State = LOWPOWER;
break;
case TX_TIMEOUT:
#ifdef REINIT_FLAG
Radio_RX_Resetting();
#endif
Radio.Rx(LORA_RX_TIMEOUT_VALUE);
State = LOWPOWER;
break;
case LOWPOWER:
default:
// Set low power
break;
}
// Process Radio IRQ
Radio.IrqProcess();
}