ESPHome  2024.4.2
nfc_helpers.cpp
Go to the documentation of this file.
1 #include "nfc_helpers.h"
2 
3 namespace esphome {
4 namespace nfc {
5 
6 static const char *const TAG = "nfc.helpers";
7 
8 bool has_ha_tag_ndef(NfcTag &tag) { return !get_ha_tag_ndef(tag).empty(); }
9 
10 std::string get_ha_tag_ndef(NfcTag &tag) {
11  if (!tag.has_ndef_message()) {
12  return std::string();
13  }
14  auto message = tag.get_ndef_message();
15  auto records = message->get_records();
16  for (const auto &record : records) {
17  std::string payload = record->get_payload();
18  size_t pos = payload.find(HA_TAG_ID_PREFIX);
19  if (pos != std::string::npos) {
20  return payload.substr(pos + sizeof(HA_TAG_ID_PREFIX) - 1);
21  }
22  }
23  return std::string();
24 }
25 
26 std::string get_random_ha_tag_ndef() {
27  static const char ALPHANUM[] = "0123456789abcdef";
28  std::string uri = HA_TAG_ID_PREFIX;
29  for (int i = 0; i < 8; i++) {
30  uri += ALPHANUM[random_uint32() % (sizeof(ALPHANUM) - 1)];
31  }
32  uri += "-";
33  for (int j = 0; j < 3; j++) {
34  for (int i = 0; i < 4; i++) {
35  uri += ALPHANUM[random_uint32() % (sizeof(ALPHANUM) - 1)];
36  }
37  uri += "-";
38  }
39  for (int i = 0; i < 12; i++) {
40  uri += ALPHANUM[random_uint32() % (sizeof(ALPHANUM) - 1)];
41  }
42  ESP_LOGD("pn7160", "Payload to be written: %s", uri.c_str());
43  return uri;
44 }
45 
46 } // namespace nfc
47 } // namespace esphome
const std::shared_ptr< NdefMessage > & get_ndef_message()
Definition: nfc_tag.h:47
bool has_ha_tag_ndef(NfcTag &tag)
Definition: nfc_helpers.cpp:8
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition: helpers.cpp:193
bool has_ndef_message()
Definition: nfc_tag.h:46
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
std::string get_random_ha_tag_ndef()
Definition: nfc_helpers.cpp:26
std::string get_ha_tag_ndef(NfcTag &tag)
Definition: nfc_helpers.cpp:10