|
| 1 | +#include "CborDecoder.h" |
| 2 | + |
| 3 | +CBORMessageDecoderClass& CBORMessageDecoder = CBORMessageDecoderClass::getInstance(); |
| 4 | + |
| 5 | +Decoder::Status CBORMessageDecoderClass::decode(Message* msg, const uint8_t* const buf, size_t &len) { // TODO do we need to propagate the maximum length? |
| 6 | + // prepare cbor structure |
| 7 | + CborValue iter; |
| 8 | + CborTag tag; |
| 9 | + CborParser parser; |
| 10 | + |
| 11 | + if (cbor_parser_init(buf, len, 0, &parser, &iter) != CborNoError) { |
| 12 | + return Decoder::Status::Error; |
| 13 | + } |
| 14 | + |
| 15 | + if (iter.type != CborTagType) { |
| 16 | + return Decoder::Status::Error; |
| 17 | + } |
| 18 | + |
| 19 | + if (cbor_value_get_tag(&iter, &tag) != CborNoError) { |
| 20 | + return Decoder::Status::Error; |
| 21 | + } |
| 22 | + |
| 23 | + if (cbor_value_advance(&iter) != CborNoError) { |
| 24 | + return Decoder::Status::Error; |
| 25 | + } |
| 26 | + |
| 27 | + auto decoder_it = decoders.find(tag); |
| 28 | + |
| 29 | + // check if message.id exists on the decoders list or return error |
| 30 | + if(decoder_it == decoders.end()) { |
| 31 | + return Decoder::Status::Error; |
| 32 | + } |
| 33 | + |
| 34 | + // encode the message |
| 35 | + if(decoder_it->second->_decode(&iter, msg) == Decoder::Status::Error) { |
| 36 | + return Decoder::Status::Error; |
| 37 | + } |
| 38 | + |
| 39 | + return Decoder::Status::Complete; |
| 40 | +} |
| 41 | + |
| 42 | +CBORMessageDecoderInterface::CBORMessageDecoderInterface(const CBORTag tag, const MessageId id) |
| 43 | +: tag(tag), id(id) { |
| 44 | + // call singleton/global variable and insert this encoder |
| 45 | + CBORMessageDecoderClass::getInstance().append(tag, this); |
| 46 | +} |
| 47 | + |
| 48 | +Decoder::Status CBORMessageDecoderInterface::_decode(CborValue* iter, Message *msg) { |
| 49 | + CborValue array_iter; |
| 50 | + msg->id = this->id; |
| 51 | + |
| 52 | + if (cbor_value_get_type(iter) != CborArrayType) { |
| 53 | + return Decoder::Status::Error; |
| 54 | + } |
| 55 | + |
| 56 | + if (cbor_value_enter_container(iter, &array_iter) != CborNoError) { |
| 57 | + return Decoder::Status::Error; |
| 58 | + } |
| 59 | + |
| 60 | + return decode(&array_iter, msg); |
| 61 | +} |
0 commit comments