-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcustomCborEncoder.ino
77 lines (59 loc) · 2.08 KB
/
customCborEncoder.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
This file is part of the Arduino_CloudUtils library.
Copyright (c) 2024 Arduino SA
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <Arduino_CBOR.h>
enum : MessageId {
CBORTestMessageId = 0x0123,
};
enum : CBORTag {
CBORTestMessageTag = 0x0321,
};
struct CBORTestMessage {
Message m;
char parameter[20];
};
class CustomMessageEncoder: public CBORMessageEncoderInterface {
public:
CustomMessageEncoder()
: CBORMessageEncoderInterface(CBORTestMessageTag, CBORTestMessageId) {}
protected:
MessageEncoder::Status encode(CborEncoder* encoder, Message *msg) override {
CBORTestMessage * testMessage = (CBORTestMessage *) msg;
CborEncoder array_encoder;
if(cbor_encoder_create_array(encoder, &array_encoder, 1) != CborNoError) {
return MessageEncoder::Status::Error;
}
if(cbor_encode_text_stringz(&array_encoder, testMessage->parameter) != CborNoError) {
return MessageEncoder::Status::Error;
}
if(cbor_encoder_close_container(encoder, &array_encoder) != CborNoError) {
return MessageEncoder::Status::Error;
}
return MessageEncoder::Status::Complete;
}
} customMessageEncoder;
void setup() {
Serial.begin(9600);
while(!Serial);
CBORMessageEncoder encoder;
uint8_t buffer[100]; // shared buffer for encoding
uint8_t expected[] = {0xD9, 0x03, 0x21, 0x81, 0x66, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66};
const size_t buf_len = sizeof(buffer);
CBORTestMessage cmd {
CBORTestMessageId,
"abcdef",
};
size_t res_len=buf_len;
MessageEncoder::Status res = encoder.encode((Message*)&cmd, buffer, res_len);
if(res == MessageEncoder::Status::Complete &&
memcmp(buffer, expected, res_len) == 0) {
Serial.println("Encode operation completed with success");
} else {
Serial.println("Encode operation failed");
}
}
void loop() {}