/* This file demonstrates how to detect when a card is presented to the reader
 * and how to get its content.
 *
 * It requires the reader to be configured for the "Autoread" operation mode.
 * (https://docs.baltech.de/developers/configure-rfid-interface.html)
 *
 * see ./AppNote_Autoread-01.balcfg
 */
 
 
#include <stdio.h>
#include <baltech_sdk.h>


static void exit_on_error(brp_errcode errcode, char *errormessage,
						  brp_protocol dev)
{
	if (errcode != BRP_OK)
	{
		char * errname = brp_map_errcode(errcode);
		if (errname == NULL)
			fprintf(stderr, "%s [brp_errcode:%08X]\n", errormessage, errcode);
		else
			fprintf(stderr, "%s [%s]\n", errormessage, errname);
		brp_destroy(dev);
		exit(EXIT_FAILURE);
	}
}


int main(int argc, char *argv[])
{
	brp_errcode errcode;
	brp_protocol dev = brp_create();
	brp_set_io(dev, brp_create_usb_hid(0));
	errcode = brp_open(dev);
	exit_on_error(errcode, "failed to connect to USB/HID device", dev);
	
	while (1) {
		printf(".");
		
		brp_buf msg_data;
		size_t msg_data_len;
		errcode = brp_AR_GetMessage((brp_AR_GetMessage_t){
			dev, .MsgData=&msg_data, .MsgData_len=&msg_data_len});
		if (errcode == BRP_AR_ErrNoMessage) continue;
		exit_on_error(errcode, "Failed to retrieve Autoread message", dev);
		
		printf("\nDetected card with content: %.*s\n", (int)msg_data_len, msg_data);
		printf("Press 'x' and <enter> to exit (otherwise press enter):");
		if (getchar() == 'x') break;
	}
	
	brp_destroy(dev);
	return EXIT_SUCCESS;
}
