ESPHome 2025.6.0
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Modules Pages
ndef_record.cpp
Go to the documentation of this file.
1#include "ndef_record.h"
2
3namespace esphome {
4namespace nfc {
5
6static const char *const TAG = "nfc.ndef_record";
7
8NdefRecord::NdefRecord(std::vector<uint8_t> payload_data) {
9 this->payload_ = std::string(payload_data.begin(), payload_data.end());
10}
11
12std::vector<uint8_t> NdefRecord::encode(bool first, bool last) {
13 std::vector<uint8_t> data;
14
15 // Get encoded payload, this is overridden by more specific record classes
16 std::vector<uint8_t> payload_data = get_encoded_payload();
17
18 size_t payload_length = payload_data.size();
19
20 data.push_back(this->create_flag_byte(first, last, payload_length));
21
22 data.push_back(this->type_.length());
23
24 if (payload_length <= 255) {
25 data.push_back(payload_length);
26 } else {
27 data.push_back(0);
28 data.push_back(0);
29 data.push_back((payload_length >> 8) & 0xFF);
30 data.push_back(payload_length & 0xFF);
31 }
32
33 if (!this->id_.empty()) {
34 data.push_back(this->id_.length());
35 }
36
37 data.insert(data.end(), this->type_.begin(), this->type_.end());
38
39 if (!this->id_.empty()) {
40 data.insert(data.end(), this->id_.begin(), this->id_.end());
41 }
42
43 data.insert(data.end(), payload_data.begin(), payload_data.end());
44 return data;
45}
46
47uint8_t NdefRecord::create_flag_byte(bool first, bool last, size_t payload_size) {
48 uint8_t value = this->tnf_ & 0b00000111;
49 if (first) {
50 value = value | 0x80; // Set MB bit
51 }
52 if (last) {
53 value = value | 0x40; // Set ME bit
54 }
55 if (payload_size <= 255) {
56 value = value | 0x10; // Set SR bit
57 }
58 if (!this->id_.empty()) {
59 value = value | 0x08; // Set IL bit
60 }
61 return value;
62};
63
64} // namespace nfc
65} // namespace esphome
std::vector< uint8_t > encode(bool first, bool last)
virtual std::vector< uint8_t > get_encoded_payload()
Definition ndef_record.h:44
uint8_t create_flag_byte(bool first, bool last, size_t payload_size)
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint32_t payload_size()