BLE Sending more than 20 Bytes of Data
Last year when I was designing the BLE App, one of the hurdle we faced was the packet size. I couldn't send more than 20 bytes of data at once. So I had to created packets of 20 bytes and send them one by one, with some headers for packet information. On the receiver side I had to receive the data, organise the packets, remove the headers and stitch the data together. It's not a very new problem, so I got to work and designed the packet creation algorithm.
Format 1
- First byte will be packet no or sequence number - it can go from 0x00 to 0xff
- Second byte is a flag which says if this packet is the last packet (0xff) or not (0x00)
- The very first packet will also contain the 2 byte "length of data". This will help in gauging how many bytes to be read from the last packet
This works really well. But the maximum amount of data you can send is 4606 bytes (256*20 - 256*2 -2). Most of my data is well within that range so it didn't really hurt. Also it takes two bytes of data for setting the length of data. Which I thought was redundant.
Hence the optimised format. The optimised format is also very similar.
Format 2
- First byte is the length of this packet
- Second byte is a flag which says if this packet is the last packet (0xff) or not (0x00)
- Rest is data. So in the last packet you can grab 18 bytes or a single byte based on 'this packet length'
This format would cause problems if a packet goes missing. The receiver wouldn't know if a packet goes missing. They also wont come to know if a packet arrives in a wrong order. This would lead to data corruption. Where as in the first format-1 receiver will know because of sequence or packet number. Though I must say this has not happened to me until now.
Conclusions
Both formats have advantages and disadvantages. The first format has worked for a year now without any issues. The second format is close to the one used by Google Science Journal App to read data from BLE peripherals. 1. So I might start using the second format in my public open source projects.
Which one would you use? Do you have your own format?
- One small difference being - they use variable type bool to flag the last packet. In C bool is one byte. 0x00 is false and a non 0x00 value is true. Technically that flag byte can have any value from 0x01 to 0xff to represent true. And the receiver should be able to handle it ↩