Receiver code

Dependencies:   mbed

Xbee.cpp

Committer:
vinbel93
Date:
2016-02-18
Revision:
0:f8873e0badb2

File content as of revision 0:f8873e0badb2:

#include "mbed.h"
#include "Xbee.h"

// Fonction d'assignation du PAN ID
void setPanId(Serial* xbee, long long panId)
{
    // Construction de la trame
    const int frameLength = 16;
    char frame[frameLength];
    frame[0] = 0x7E; // Start delimiter
    frame[1] = 0x00; // Length (MSB)
    frame[2] = 0x0C; // Length (LSB)
    frame[3] = 0x08; // AT Command
    frame[4] = 0x00; // Frame ID
    frame[5] = 'I';
    frame[6] = 'D';
    frame[7] = (panId >> 56) & 0xFF;
    frame[8] = (panId >> 48) & 0xFF;
    frame[9] = (panId >> 40) & 0xFF;
    frame[10] = (panId >> 32) & 0xFF;
    frame[11] = (panId >> 24) & 0xFF;
    frame[12] = (panId >> 16) & 0xFF;
    frame[13] = (panId >> 8) & 0xFF;
    frame[14] = (panId >> 0) & 0xFF;
    frame[15] = checksum(frame, 3, 15);

    // Envoi sur le UART
    if (xbee->writeable())
    {
        for (int i = 0; i < frameLength; i++)
        {
            xbee->putc(frame[i]);
        }
    }
}

// Envoi d'un message au coordinateur (Transmit Request)
void transmitRequest(Serial* xbee, char* data, int size)
{
    // Construction de la trame
    const int frameLength = 18 + size;
    char frame[frameLength];
    frame[0] = 0x7E; // Start delimiter
    frame[1] = 0x00; // Length (MSB)
    frame[2] = 0x0E + size; // Length (LSB)
    frame[3] = 0x10; // AT Command
    frame[4] = 0x01; // Frame ID
    frame[5] = (MAC_ADDRESS_COORDINATOR >> 56) & 0xFF;
    frame[6] = (MAC_ADDRESS_COORDINATOR >> 48) & 0xFF;
    frame[7] = (MAC_ADDRESS_COORDINATOR >> 40) & 0xFF;
    frame[8] = (MAC_ADDRESS_COORDINATOR >> 32) & 0xFF;
    frame[9] = (MAC_ADDRESS_COORDINATOR >> 24) & 0xFF;
    frame[10] = (MAC_ADDRESS_COORDINATOR >> 16) & 0xFF;
    frame[11] = (MAC_ADDRESS_COORDINATOR >> 8) & 0xFF;
    frame[12] = (MAC_ADDRESS_COORDINATOR >> 0) & 0xFF;
    frame[13] = 0xFF; // Broadcast
    frame[14] = 0xFE; // Broadcast
    frame[15] = 0x00; // Broadcast radius
    frame[16] = 0x00; // Options

    // Ajout des données utiles
    for (int i = 0; i < size; i++)
    {
        frame[17 + i] = data[i];
    }
    frame[17 + size] = checksum(frame, 3, 17 + size);
    
    // Envoi sur le UART
    if (xbee->writeable())
    {
        for (int i = 0; i < frameLength; i++)
        {
            xbee->putc(frame[i]);
        }
    }
}

// Fonction de calcul de checksum
char checksum(char* frame, int begin, int end)
{
    char sum = 0;

    // Addition des bits
    for (int i = begin; i < end; i++)
    {
        sum += frame[i];
    }
    
    return 0xFF - sum;
}