Please note, that SIZE field definition uses comms::option::NumValueSerOffset option, which effectively adds 2 when size value is serialised, and subtracts it when remaining length is deserialised. It must be done, because SIZE value specifies number of remaining bytes, including the CHECKSUM value at the end.
The outermost layer defines a full protocol stack. It should be typedef-ed to avoid any confusion:
usingMyProtocolStack=MySyncPrefix;
The processing loop may look like this:
// Protocol stackMyProtocolStack protStack;// Message handler objectMyHandler handler;// Input data storage, the data received over I/O link is appended herestd::vector<std::uint8_t> inData;voidprocessData(){while (!inData.empty()) { MyProtocolStack::ReadIterator readIter =&inData[0]; MyProtocolStack::MsgPtr msg;auto es =protStack.read(msg, readIter,inData.size());if (es == comms::ErrorStatus::NotEnoughData) { // More data is required;return; }if (es == comms::ErrorStatus::Success) {assert(msgPtr); // Must hold the valid message objectmsgPtr->dispatch(handler); // Process message, dispatch to handling function // Erase consumed bytes from the bufferauto consumedBytes = std::distance(ProtocolStack::ReadIterator(&inData[0]), readIter);inData.erase(inData.begin(),inData.begin() + consumedBytes);continue; } // Some error occurred, pop only one first byte and try to process againinData.erase(inData.begin()); }}
The processing loop above is not the most efficient one, but it demonstrates what needs to be done and how our generic library can be used to identify and process the received message.
Writing Message
The write logic is even simpler.
voidsendMessage(constMyMessage& msg){ // Output buffer std::vector<std::uint8_t> outData; // Reserve enough space in output bufferoutData.reserve(protStack.length(msg)); auto writeIter = std::back_inserter(outData);auto es =protStack.write(msg, writeIter,outData.max_size());if (es == comms::ErrorStatus::UpdateRequired) {auto updateIter =&outData[0]; es =protStack.update(updateIter,outData.size()); }if (es != comms::ErrorStatus::Success) { ... // report errorreturn; } ... // Send written data over I/O link}