#include <stdio.h>


#include <unistd.h>
#include "usblcpdmac.h"


#define LOGO_STRING " Logic Controls Inc       Bematech     "
#define SPACE_STRING "                                      "
#define WAKEUP_STRING "  computer wakeup   "
#define STR_LENGTH 20

#define SLEEP_BETWEEN_TESTS 2 //seconds

LCPDDeviceDescriptorRef *deviceGot;
int deviceNumber;



int write_pd_text(LCPDDeviceDescriptorRef descr, char* text, int len)
{
	char buf[128];
	strncpy(buf, text,len);
	
	if(LCPDWrite(descr, buf, len)) 
	{
		fprintf(stderr,"--Error writing text\n");
		return -1;
	} 
	
	return 0;
}

void DisplayText(char* text, int len)
{
	printf("start to display text\n");
	
	LCPDGetDeviceDescriptors(&deviceGot, &deviceNumber);
	if (!deviceNumber)
	{
		fprintf(stderr, "No LCPD devices found");
		LCPDReleaseDescriptors(deviceGot, deviceNumber);
		return;
	}
	
	printf("Found %d devices\n", deviceNumber);
	
	for (int i = 0; i < deviceNumber; i++) 
	{
		write_pd_text(deviceGot[i], text, len);
	}
	sleep(SLEEP_BETWEEN_TESTS);
	
	LCPDReleaseDescriptors(deviceGot, deviceNumber);
	
	printf("display end !\n");
}

void WakeCallback()
{
	//LCPD devices are re-attached to the system after sleep and wake. 
	//Perform tests with the new instances.
	printf("wakeup display text\n");
	DisplayText(WAKEUP_STRING, STR_LENGTH);
}

int main(int argc, char *argv[ ])
{
	printf("\nExample Mac Program for USB Pole Display (C) 2011 Logic Controls, Inc.\n");
	
	//register wake callback
	LCPDRegisterWakeCallback(WakeCallback, CFRunLoopGetCurrent());
	
	//output text to pole display
	DisplayText(LOGO_STRING, STR_LENGTH * 2 - 1);
	
	//receive wake notification
	CFRunLoopRun();
	
	//deregister callback
	LCPDRegisterWakeCallback(NULL, NULL);
	
	printf("\n quit the test program !\n");
	return(0);
}
