XBEE code to reduce program size

Dependencies:   mbed

XBEE/XBEE.cpp

Committer:
giovanniwsn
Date:
2018-10-14
Revision:
1:b0c665b697c7
Parent:
0:7c9e8aaa85d4

File content as of revision 1:b0c665b697c7:

#include "XBEE.h"

/* Class constructor */
XBEE::XBEE(Serial* serial, int baud):xbee(serial)
{
    xbee->baud(baud);
    xbee->attach(callback(this, &XBEE::recvAttach), Serial::RxIrq);
    init();
}

/* Initialize the Device XBEE */
void XBEE::init(void)
{
    count_tx = 0;
    count_rx = 0;
    memset(&buf_tx,0,sizeof(buf_tx));
    memset(&buf_rx,0,sizeof(buf_rx));
}

/* Send message to the destination */
int XBEE::send_msg(char * str)
{
    int n = strlen(str);
    if(n > 92) return -1;
    create_TX(str);
    sendBuffer();
    wait(0.2);
    return 0;
}

/* Receives a message, writes in str */
int XBEE::recv_msg(char * buf, int tam)
{
    pkt_tx *p;
    int i;
    int ptam = 0;
    int j = 0;
    memset(buf,0,tam);
    
    for(i = 0; i < count_rx; i++) {
        if(buf_rx[i] == 0x7E) {
            p = (pkt_tx *) &buf_rx[i];
            if(p->frame_type == 0x90) {
                ptam = p->length - 0x0C;
                if(tam < ptam + j) {
                    return -1;
                }
                // posicao aonde comeca msg
                memcpy(&buf[j], ((char *)(&p->broadcast_radius)), ptam);
                j += ptam;
            }
        }
    }
    return j;
}

/* Chamada por Interrupcao, RX */
void XBEE::recvAttach (void) 
{
    while(xbee->readable()) {
        buf_rx[count_rx%sizeof(buf_rx)] = xbee->getc();
        count_rx++;
    }
}

/* Envia pacote do buffer_tx */
void XBEE::sendBuffer(void) 
{
    if(xbee->writeable()) {
        for(int i = 0; i < count_tx; i++) {
            xbee->putc(buf_tx[i]);
        }
    }
}

/* Cria pacote de mensagem */
int XBEE::create_TX(char * str)
{
    int i = 0;
    int n = strlen(str);
    uint8_t count = 0;
    pkt_tx *p = (pkt_tx *) buf_tx; // ponteiro para buffer global
    
    if(n > 92) return -1; // nao pode exceder 92 bytes
    count_tx = 0;
    memset(&buf_tx,0,sizeof(buf_tx));

    p->start_delimiter = 0x7E;
    p->length = 0x0E + n;   // pacote vazio + dados
    p->frame_type = 0x10;   // transmit request
    p->frame_id = 1;
    p->dest_addr64[6] = 0x00;   //SL_H
    p->dest_addr64[7] = 0x00;   //SL_L
    p->dest_addr16[0] = 0xFF;   //MY_H
    p->dest_addr16[1] = 0xFF;   //MY_L
    memcpy(&p->rf_data, str, n);

    // Calc. Checksum: comeca 3 pra frente, tenq passar 3 adiante no final
    for(i = 3; i < p->length + 3; i++) count += buf_tx[i];
    
    count = 0xFF - count;
    p->rf_data[n] = count;

    //p->length tem o tamanho soh do frame, 
    //pacote total eh o starter + length alto + length baixo + checksum
    count_tx = p->length + 4;
    return count_tx;
}