FEP interrupt, response, ring buffer
Dependents: 087_myFEP_TX 087_myFEP_RX
Diff: FEP.cpp
- Revision:
- 0:b01dc5fd59bc
- Child:
- 2:aa9a344a42a8
diff -r 000000000000 -r b01dc5fd59bc FEP.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FEP.cpp Sat Oct 09 11:42:03 2021 +0000 @@ -0,0 +1,84 @@ +#include "FEP.h" + +myFEP::myFEP(PinName tx, PinName rx, uint8_t addr_, int baud=115200) : + RawSerial(tx, rx) +{ + addr = addr_; + bufindex = 0; + retindex = 0; +} + +void myFEP::StartReceive() +{ + attach(callback(this, &myFEP::ReceiveBytes)); + +} + +void myFEP::ReceiveBytes() +{ + if (bufindex > 256) bufindex %= 256; + buffer[bufindex] = getc(); // データ取得 + + if ( (bufindex > 0) && (!strcmp((char*)(buffer + bufindex - 1) , "\r\n")) ) { // <CR><LF>確認 + CheckData(); // 集計 + } +} + +void CheckData() +{ + uint8_t temp=0, length=0; // temp:配列の位置 length:配列の長さ + for (uint16_t i=0; i<256; i++) { + temp = (256 + bufindex - i) % 256; + if ( !str((char*)(buffer + temp) , "RBN") ) { // ヘッダ確認 + length = ctoi(buffer[temp+6])*100 + ctoi(buffer[temp+7])*10 + ctoi(buffer[temp+8]); // メッセージの長さを計算 + for (int j = 9; j < length+9; j++) { + retdata[j-9] = buffer[temp+j]; // + } + } + } +} + +void GetData(uint8_t *data) +{ + strcpy((char*)data, (char*)retdata); +} + + +uint8_t SendData(uint8_t *data) +{ + return SendData(data, sizeof(data)); +} + +uint8_t SendData(uint8_t *data, uint8_t length) +{ + if(length > 128) return 1; + uint8_t sendindex; // dataの添え字用の変数 + printf("@TBN%03d%03d", addr, length); // コマンド送信 + for (sendindex=0; sendindex<length; sendindex++) { + putc(data[sendindex]); // データ部分送信 + } + printf("\r\n"); // <cr><lf> + return GetResponse(); // 応答確認 +} + +uint8_t GetResponse() +{ + char res[4]; // 応答格納用変数 + uint8_t resindex=0; // + while (1) { + res[resindex] = getc(); + if (resindex >= 3) { + if (!strcmp(temp, "P0\r\n")) return 0; + else if (!strcmp(temp, "N0\r\n")) return 2; + else if (!strcmp(temp, "N1\r\n")) return 3; + else if (!strcmp(temp, "N3\r\n")) return 4; + } + if (++resindex > 3) return -1; + } +} + +uint8_t FEP::ctoi(char c) +{ + if('0' <= c && c <= '9') return (c-'0'); + else return -1; +} \ No newline at end of file