FEP interrupt, response, ring buffer

Dependents:   087_myFEP_TX 087_myFEP_RX

FEP.cpp

Committer:
piroro4560
Date:
2021-10-15
Revision:
4:8d754f144b96
Parent:
3:12dcc46fb9dc

File content as of revision 4:8d754f144b96:

/**
 *  @file   FEP.cpp
 *  @author 安澤瑠
 *  @date   21/10/15
 */
#include "FEP.h"

myFEP::myFEP(PinName tx, PinName rx, uint8_t addr_, int baud) :
    RawSerial(tx, rx, baud)
{
    addr     = addr_;
    timeout  = TIMEOUT_COUNT;
    bufindex = 0;
    retindex = 0;
    length   = 0;
}

void myFEP::StartReceive()
{
    attach(callback(this, &myFEP::ReceiveBytes));
    timeoutTimer.attach(callback(this, &myFEP::TimeoutLoop), 0.1);
}

void myFEP::TimeoutLoop()
{
    if (timeout >= TIMEOUT_COUNT) {
        status = false;
    } else {
        status = true;
        timeout++;
    }
}

void myFEP::ReceiveBytes()
{
    buffer[bufindex] = getc(); // Receive 1byte
    timeout = 0;

    if ( (!strncmp((char*)(buffer + ((256 + bufindex - 1)%256) ), "\r\n", 2)) ) { // <CR><LF> bufindex = <LF>(='\n')
        CheckData(); // check and extract message
    }
    bufindex++;
}

void myFEP::CheckData()
{
    uint8_t temp=0;
    for (uint16_t i=0; i<256; i++) {
        temp = (256 + bufindex - i) % 256;
        if ( !strncmp((char*)(buffer + temp) , "RBN", 3) ) { // check header  temp='R'
            length = buffer[(temp+9)%256];
            for (int j = 10; j < length+10; j++) {
                retdata[j-10] = buffer[(temp+j)%256]; // get message
            }
            return;
        }
    }
}

uint8_t myFEP::GetData(uint8_t *data)
{
    for (int i=0; i<length; i++) data[i] = retdata[i];
    return length;
}

int8_t myFEP::SendData(uint8_t *data, uint8_t length_)
{
    if(length_ > 126) return 1;
    uint8_t sendindex; // index of 'data'
    printf("@TBN%03d%03d", addr, length_+1); // send comand
    putc(length_);
    for (sendindex=0; sendindex<length_; sendindex++) {
        putc(data[sendindex]); // send message
    }
    printf("\r\n"); // <cr><lf>
    return GetResponse(); // check response
}

int8_t myFEP::GetResponse()
{
    char res[256]; // array of storing response
    for (uint8_t resindex=0; resindex<256; resindex++) {
        res[resindex] = getc();
        if (!strncmp(res+resindex-1, "\r\n", 2)) {
            if (!strncmp(res+resindex-3, "P0", 2))  return 0;
            else if (!strncmp(res+resindex-3, "N0", 2)) return 2;
            else if (!strncmp(res+resindex-3, "N1", 2)) return 3;
            else if (!strncmp(res+resindex-3, "N3", 2)) return 4;
        }
    }
    return -1;
}