returns true if complete message is captured. multiple calls needed as it should be non-blocking.
| 168 | // returns true if complete message is captured. |
| 169 | // multiple calls needed as it should be non-blocking. |
| 170 | bool RS485::receive(uint8_t &senderID, uint8_t msg[], uint8_t &msglen) |
| 171 | { |
| 172 | static uint8_t state = 0; |
| 173 | static uint8_t sender = 255; // unknown / anonymous. |
| 174 | static uint8_t length = 0; |
| 175 | static bool forMe = false; |
| 176 | uint8_t CHKSUM = 0; |
| 177 | |
| 178 | if (_stream->available() == 0) return false; |
| 179 | |
| 180 | uint8_t v = _stream->read(); |
| 181 | // if (debug) Serial.print(v, HEX); |
| 182 | |
| 183 | switch(state) |
| 184 | { |
| 185 | // waiting for new packet |
| 186 | case 0: |
| 187 | if (v == SOH) |
| 188 | { |
| 189 | _bidx = 0; // start new packet |
| 190 | state = 1; |
| 191 | } |
| 192 | break; |
| 193 | |
| 194 | // extract receiver |
| 195 | case 1: |
| 196 | forMe = ((v == _deviceID) || (v == 255)); // PM or broadcast? |
| 197 | if (not forMe) state = 99; |
| 198 | else state = 2; |
| 199 | break; |
| 200 | |
| 201 | // extract sender |
| 202 | case 2: |
| 203 | sender = v; |
| 204 | state = 3; |
| 205 | break; |
| 206 | |
| 207 | // extract length |
| 208 | case 3: |
| 209 | msglen = v; |
| 210 | state = 3; |
| 211 | break; |
| 212 | |
| 213 | // expect STX |
| 214 | case 4: |
| 215 | if (v == STX) state = 5; |
| 216 | else state = 99; |
| 217 | break; |
| 218 | |
| 219 | // extract message |
| 220 | case 5: |
| 221 | if (length == 0) |
| 222 | { |
| 223 | state = 6; |
| 224 | break; |
| 225 | } |
| 226 | // error handling if v not ascii ? |
| 227 | _buffer[_bidx++] = v; |