Source

pebble / totp.c

/** \file
 * Google Two Factor authentication watch face.
 */
#include "pebble_os.h"
#include "pebble_app.h"
#include "pebble_fonts.h"
#include "sha1.h"

PBL_APP_INFO(
	"Two Factor",
	"hudson",
	1, // Version
	INVALID_RESOURCE,
	APP_INFO_WATCH_FACE
);


static char time_buffer[32];
static char otp_buffer[32];
static Window window;
static TextLayer time_layer;
static TextLayer otp_layer;

#define GMT_OFFSET 5

static uint32_t unix_epoch_time(
	const PblTm * const curr_time
)
{
  long now = 0;
  now += (curr_time->tm_year-70)*31536000;
  now += ((curr_time->tm_year-69)/4)*86400;
  now -= ((curr_time->tm_year-1)/100)*86400;
  now += ((curr_time->tm_year+299)/400)*86400;
  now += curr_time->tm_yday*86400;
  now += curr_time->tm_hour*3600;
  now += curr_time->tm_min*60;
  now += curr_time->tm_sec;
  return now;
}

static void
handle_tick(
	AppContextRef ctx,
	PebbleTickEvent * const event
)
{
	(void) ctx;

	string_format_time(
		otp_buffer,
		sizeof(otp_buffer),
		"%H:%M:%S",
		event->tick_time
	);

	unsigned offset = 8;
	otp_buffer[offset++] = '\n';
	otp_buffer[offset++] = '\n';

	// Convert the time into a unix epoch time.
	// this should be done in a library
	const PblTm * const ptm = event->tick_time;

	const uint32_t now = unix_epoch_time(ptm) + 3600 * GMT_OFFSET;
	uint32_t auth = oauth_calc(now);
	otp_buffer[offset + 5] = '0' + auth % 10; auth /= 10;
	otp_buffer[offset + 4] = '0' + auth % 10; auth /= 10;
	otp_buffer[offset + 3] = '0' + auth % 10; auth /= 10;
	otp_buffer[offset + 2] = '0' + auth % 10; auth /= 10;
	otp_buffer[offset + 1] = '0' + auth % 10; auth /= 10;
	otp_buffer[offset + 0] = '0' + auth % 10; auth /= 10;
	offset += 6;
	otp_buffer[offset++] = '\n';
	otp_buffer[offset++] = '\n';
	otp_buffer[offset++] = '\0';

	uint32_t rem = 30 - (now % 30);

	text_layer_set_text(&otp_layer, otp_buffer);
}


static void
handle_init(
	AppContextRef ctx
)
{
	(void) ctx;

	window_init(&window, "RFC 6238");
	window_stack_push(&window, true);

	//text_layer_init(&time_layer, window.layer.frame);
	time_buffer[0] = '\0';
	//text_layer_set_text(&time_layer, time_buffer);
	//layer_add_child(&window.layer, &time_layer.layer);

	text_layer_init(&otp_layer, window.layer.frame);
	text_layer_set_font(&otp_layer, fonts_get_system_font(FONT_KEY_GOTHAM_30_BLACK));
	otp_buffer[0] = '\0';
	text_layer_set_text(&otp_layer, otp_buffer);
	layer_add_child(&window.layer, &otp_layer.layer);
}


void
pbl_main(
	void * const params
)
{
	PebbleAppHandlers handlers = {
		.init_handler	= &handle_init,
		.tick_info	= {
			.tick_handler = &handle_tick,
			.tick_units = SECOND_UNIT,
		},
	};

	app_event_loop(params, &handlers);
}