Battery measurement, basic version
This commit is contained in:
65
firmware/libs/usb_mgmt/src/usb_mgmt.c
Normal file
65
firmware/libs/usb_mgmt/src/usb_mgmt.c
Normal file
@@ -0,0 +1,65 @@
|
||||
#include <hal/nrf_power.h>
|
||||
#include <nrfx_power.h>
|
||||
#include <errno.h>
|
||||
#include <zephyr/logging/log.h>
|
||||
|
||||
#include "usb_mgmt.h"
|
||||
|
||||
LOG_MODULE_REGISTER(usb_mgmt, CONFIG_USB_MGMT_LOG_LEVEL);
|
||||
|
||||
K_EVENT_DEFINE(usb_mgmt_events);
|
||||
K_SEM_DEFINE(usb_mgmt_ready_sem, 0, 1);
|
||||
|
||||
static bool usb_mgmt_last_vbus_state;
|
||||
static bool usb_mgmt_ready;
|
||||
|
||||
static void usb_mgmt_power_handler(nrfx_power_usb_evt_t event)
|
||||
{
|
||||
bool is_present = (event == NRFX_POWER_USB_EVT_DETECTED);
|
||||
|
||||
LOG_INF("VBUS %s (event=%u)", is_present ? "connected" : "disconnected", event);
|
||||
|
||||
if (is_present != usb_mgmt_last_vbus_state) {
|
||||
usb_mgmt_last_vbus_state = is_present;
|
||||
k_event_post(&usb_mgmt_events,
|
||||
is_present ? USB_MGMT_VBUS_CONNECTED : USB_MGMT_VBUS_DISCONNECTED);
|
||||
}
|
||||
}
|
||||
|
||||
static int usb_mgmt_init(void)
|
||||
{
|
||||
usb_mgmt_last_vbus_state = nrf_power_usbregstatus_vbusdet_get(NRF_POWER);
|
||||
LOG_DBG("Boot VBUS state: %s", usb_mgmt_last_vbus_state ? "present" : "absent");
|
||||
k_event_post(&usb_mgmt_events,
|
||||
usb_mgmt_last_vbus_state ? USB_MGMT_VBUS_CONNECTED : USB_MGMT_VBUS_DISCONNECTED);
|
||||
|
||||
nrfx_power_config_t config = { 0 };
|
||||
nrfx_power_usbevt_config_t usb_config = {
|
||||
.handler = usb_mgmt_power_handler,
|
||||
};
|
||||
|
||||
nrfx_power_init(&config);
|
||||
nrfx_power_usbevt_init(&usb_config);
|
||||
nrfx_power_usbevt_enable();
|
||||
|
||||
usb_mgmt_ready = true;
|
||||
k_sem_give(&usb_mgmt_ready_sem);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
SYS_INIT(usb_mgmt_init, APPLICATION, CONFIG_APPLICATION_INIT_PRIORITY);
|
||||
|
||||
bool usb_mgmt_is_vbus_present(void)
|
||||
{
|
||||
return usb_mgmt_last_vbus_state;
|
||||
}
|
||||
|
||||
bool usb_mgmt_wait_ready(k_timeout_t timeout)
|
||||
{
|
||||
if (usb_mgmt_ready) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return k_sem_take(&usb_mgmt_ready_sem, timeout) == 0;
|
||||
}
|
||||
Reference in New Issue
Block a user