Reading NFC record under 4 chars causes weird issues.

Hi There,

I'm trying to read the NDEF records stored on my NRF52 DK but I'm having some issues when the the NDEF record payload is less than 4 chars. I just get random symbols or large buffer values instead (See terminal output):

Code:

static char *read_nfc_data()
{
  int err;
  size_t nfc_length = ndef_msg_buf[1];
  uint8_t desc_buf[NFC_NDEF_PARSER_REQIRED_MEMO_SIZE_CALC(10)];
  size_t desc_buf_len = sizeof(desc_buf);

  // Load NDEF message from flash buffer
  err = nfc_ndef_msg_parse(desc_buf, &desc_buf_len, &ndef_msg_buf[2], &nfc_length);
  if (err)
  {
    printk("Error during parsing an NDEF message, err: %d.\n", err);
  }

  // Parse message into NDEF records
  struct nfc_ndef_msg_desc *ndef_message_desc;
  ndef_message_desc = (struct nfc_ndef_msg_desc *)desc_buf;

  // Iterate over records
  for (int i = 0; i < ndef_message_desc->record_count; i++)
  {
    size_t record_size = nfc_length;

    // Extract payload description from NDEF record
    struct nfc_ndef_record_desc record_desc = *ndef_message_desc->record[i];
    struct nfc_ndef_bin_payload_desc * payload_desc = record_desc.payload_descriptor;

    // Remove header from payload to reveal text
    int payload_length = payload_desc->payload_length - 3;
    char *payload_message = malloc(payload_length + 1);
    char *original_message = payload_desc->payload + 3;

    // Copy string from buffer to variable with terminator
    memcpy(&payload_message, &original_message, payload_length);
    payload_message[payload_length] = '\0';
    printk("String: %s (%d)\n", payload_message);
  }

  // Return empty string if failure
  return "";
}


Terminal Output:
E: CONFIG_MINIMAL_LIBC_MALLOC_ARENA_SIZE is 0
String: Aaaa
E: CONFIG_MINIMAL_LIBC_MALLOC_ARENA_SIZE is 0
String: Hello! 
E: CONFIG_MINIMAL_LIBC_MALLOC_ARENA_SIZE is 0
String: ��
         m�� 

^^ The three NDEF values were:
 - Aaaa
 - Hello!
 - A

Parents Reply Children
  • Hi,

    It shouldn't be necessary to remove the header by subtracting 3 as payload_desc->payload_length variable contains the actual payload length without the header. You also don't need to add 3 for original_message pointer as it already points at the start of the payload. 

    The SDK parsing functions should parse it correctly regardless if "record length" field is 4-byte or 1-byte record. 

    regards

    Jared 

Related