/************************************************************
* Copyright (C) 2007 Masahiko SAWAI All Rights Reserved. 
************************************************************/
/**
* Show all Wii Remote battery level.
**/

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

#include <wiiremote.h>

int main(int argc, char *argv[])
{
	int number, i;
	WRMT_WiiRemote *wiiremotes[WRMT_MAX_DEVICES];
	
	if (WRMT_Init() != 0)
	{
		fprintf(stderr, "WRMT_Init() Faild.\n");
		exit(-1);
	}
	atexit(WRMT_Quit);

	/* Get Number of WiiRemotes */
	number = WRMT_GetNumWiiRemote();
	if (number <= 0)
	{
		fprintf(stderr, "No Wii Remote Found.\n");
		exit(-1);
	}
	fprintf(stderr, "Number of Wii Remote : %d\n", number);

	/* Open and init all WiiRemotes */
	for (i = 0;i < number;i++)
	{
		WRMT_IOReturn rc;

		wiiremotes[i] = WRMT_GetWiiRemoteAt(i);
		rc = WRMT_WiiRemote_Open(wiiremotes[i]);
		if (rc == WRMT_IO_ERROR)
		{
			fprintf(stderr, "WRMT_WiiRemote_Open(%d) Fail.\n", i);
			fprintf(stderr, "\t%s\n", WRMT_GetError());
			exit(-1);
		}
		fprintf(stderr, "[%d] WRMT_WiiRemote_Open() Success.\n", i);
	}

	/* Wait and update all controler */
	for (i = 0;i < 200;i++)
	{
		WRMT_Update();
		WRMT_Sleep(10);
	}

	/* Show battery level */
	for (i = 0;i < number;i++)
	{
		int battery_level = WRMT_WiiRemote_GetState(wiiremotes[i], WRMT_DATA_BATTERY_LEVEL);
		fprintf(stderr, "[%d] battery_level == %d(0x%02x) %.1f %%\n", i,
			battery_level, battery_level, battery_level / 2.0);
	}

	/* Close All Wii Remote */
	for (i = WRMT_GetNumWiiRemote()-1;i >= 0;i--)
	{
		fprintf(stderr, "WRMT_WiiRemote_Close(%d).\n", i);
		WRMT_WiiRemote_Close(wiiremotes[i]);
	}
	fprintf(stderr, "WRMT_Quit().\n");

	return 0;
}
