/*
 * Copyright (c) 2021 Nordic Semiconductor ASA
 *
 * SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
 */
#include <event_manager.h>
#include <device.h>

#define MODULE main
#include <caf/events/module_state_event.h>

#include <logging/log.h>
LOG_MODULE_REGISTER(MODULE);

static volatile uint32_t g_wakeup_latch;
static volatile uint32_t g_wakeup_latch_after_clear;

static int detect_wakeup_latch(const struct device *dev)
{
	ARG_UNUSED(dev);

	g_wakeup_latch = NRF_P0->LATCH;
	// Reconfigure the button pins to reset condition before trying to clear the latch
	NRF_P0->PIN_CNF[11] = 0x00000002;
	NRF_P0->PIN_CNF[12] = 0x00000002;
	NRF_P0->PIN_CNF[24] = 0x00000002;
	NRF_P0->PIN_CNF[25] = 0x00000002;
	NRF_P0->LATCH = NRF_P0->LATCH; // clear the latch
	
	// 3 dummy reads (needed according to errata)
	(void)NRF_P0->LATCH;
	(void)NRF_P0->LATCH;
	(void)NRF_P0->LATCH;

	g_wakeup_latch_after_clear = NRF_P0->LATCH;

	return 0;
}

SYS_INIT(detect_wakeup_latch, PRE_KERNEL_1, 0);

void main(void)
{
	LOG_INF("NRF_P0->LATCH, at wakeup = 0x%08x, after clear = 0x%08x", g_wakeup_latch, g_wakeup_latch_after_clear);

	if (event_manager_init()) {
		LOG_ERR("Event manager not initialized");
	} else {
		module_set_state(MODULE_STATE_READY);
	}
}
