|
| 1 | +#include "EasyTransfer.h" |
| 2 | + |
| 3 | +//Captures address and size of struct |
| 4 | +void EasyTransfer::begin(uint8_t * ptr, uint8_t length, Stream *theStream){ |
| 5 | +address = ptr; |
| 6 | +size = length; |
| 7 | +_stream = theStream; |
| 8 | + |
| 9 | +//dynamic creation of rx parsing buffer in RAM |
| 10 | +rx_buffer = (uint8_t*) malloc(size); |
| 11 | +} |
| 12 | + |
| 13 | +//Sends out struct in binary, with header, length info and checksum |
| 14 | +void EasyTransfer::sendData(){ |
| 15 | + uint8_t CS = size; |
| 16 | + _stream->write(0x06); |
| 17 | + _stream->write(0x15); |
| 18 | + _stream->write(size); |
| 19 | + for(int i = 0; i<size; i++){ |
| 20 | + CS^=*(address+i); |
| 21 | + _stream->write(*(address+i)); |
| 22 | + } |
| 23 | + _stream->write(CS); |
| 24 | +} |
| 25 | + |
| 26 | +boolean EasyTransfer::receiveData(){ |
| 27 | + |
| 28 | + //start off by looking for the header bytes. If they were already found in a previous call, skip it. |
| 29 | + if(rx_len == 0){ |
| 30 | + //this size check may be redundant due to the size check below, but for now I'll leave it the way it is. |
| 31 | + if(_stream->available() >= 3){ |
| 32 | +//this will block until a 0x06 is found or buffer size becomes less then 3. |
| 33 | + while(_stream->read() != 0x06) { |
| 34 | +//This will trash any preamble junk in the serial buffer |
| 35 | +//but we need to make sure there is enough in the buffer to process while we trash the rest |
| 36 | +//if the buffer becomes too empty, we will escape and try again on the next call |
| 37 | +if(_stream->available() < 3) |
| 38 | +return false; |
| 39 | +} |
| 40 | + if (_stream->read() == 0x15){ |
| 41 | + rx_len = _stream->read(); |
| 42 | +//make sure the binary structs on both Arduinos are the same size. |
| 43 | + if(rx_len != size){ |
| 44 | + rx_len = 0; |
| 45 | + return false; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + //we get here if we already found the header bytes, the struct size matched what we know, and now we are byte aligned. |
| 52 | + if(rx_len != 0){ |
| 53 | + while(_stream->available() && rx_array_inx <= rx_len){ |
| 54 | + rx_buffer[rx_array_inx++] = _stream->read(); |
| 55 | + } |
| 56 | + |
| 57 | + if(rx_len == (rx_array_inx-1)){ |
| 58 | + //seem to have got whole message |
| 59 | + //last uint8_t is CS |
| 60 | + calc_CS = rx_len; |
| 61 | + for (int i = 0; i<rx_len; i++){ |
| 62 | + calc_CS^=rx_buffer[i]; |
| 63 | + } |
| 64 | + |
| 65 | + if(calc_CS == rx_buffer[rx_array_inx-1]){//CS good |
| 66 | + memcpy(address,rx_buffer,size); |
| 67 | +rx_len = 0; |
| 68 | +rx_array_inx = 0; |
| 69 | +return true; |
| 70 | +} |
| 71 | + |
| 72 | + else{ |
| 73 | + //failed checksum, need to clear this out anyway |
| 74 | +rx_len = 0; |
| 75 | +rx_array_inx = 0; |
| 76 | +return false; |
| 77 | + } |
| 78 | + |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + return false; |
| 83 | +} |
0 commit comments