NagaokaRoboticsClub_mbedTeam / Mbed 2 deprecated NHK2020

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers FEP.cpp Source File

FEP.cpp

00001 #include "FEP.h"
00002 
00003 FEP::FEP(PinName tx, PinName rx, uint8_t addr, int baud) :
00004     RawSerial(tx, rx, baud)
00005 {
00006     _address = addr;
00007 }
00008 
00009 void FEP::startReceive(uint16_t dataSize)
00010 {
00011     bufferSize = dataSize + 15;
00012     bufferPoint = 0;
00013     receivedBytes = 0;
00014     buffer = new uint8_t[bufferSize];
00015     data  = new uint8_t[dataSize];
00016     attach(callback(this, &FEP::receiveByte));
00017 }
00018 
00019 void FEP::getData(uint8_t data_[])
00020 {
00021     for(int i = 0; i < bufferSize - 15; i++) {
00022         data_[i] = data[i];
00023     }
00024 }
00025 
00026 void FEP::sendData(uint8_t data_[], uint8_t length)
00027 {
00028     uint8_t checksum = 0x00;
00029 
00030     printf("@TBN%03d%03d", _address, length + 1);
00031     for (int j = 0; j < length; j++) {
00032         checksum += data_[j];
00033         putc(data_[j]);
00034     }
00035     putc(checksum);
00036     putc('\r');
00037     putc('\n');
00038 }
00039 
00040 void FEP::receiveByte()
00041 {
00042     buffer[bufferPoint % bufferSize] = getc();
00043 
00044     if(bufferPoint != 0xff) {
00045         ++bufferPoint;
00046     } else {
00047         bufferPoint = (255%bufferSize)+1;
00048     }
00049 
00050     ++receivedBytes;
00051 
00052     if(receivedBytes >= bufferSize) checkData();
00053 }
00054 
00055 void FEP::checkData()
00056 {
00057     for(int i = 0; i < bufferSize; i++) {
00058         if(buffer[i % bufferSize] == FEP_HEADER0 && buffer[(i + 1) % bufferSize] == FEP_HEADER1 && buffer[(i + 2) % bufferSize] == FEP_HEADER2) {
00059             uint8_t checksum = 0x00;
00060             for(int j = 9; j < bufferSize - 6; j++) {
00061                 checksum += buffer[(i + j)% bufferSize];
00062             }
00063             if(checksum == buffer[(i + bufferSize - 6)% bufferSize]) {
00064                 for(int j = 9; j < bufferSize - 6; j++) {
00065                     data[j - 9] = buffer[(i + j) % bufferSize];
00066                 }
00067                 receivedBytes = 0;
00068                 return;
00069             }
00070         }
00071     }
00072 }