keycard-pro/app/pwr.c

81 lines
1.4 KiB
C
Raw Permalink Normal View History

2023-08-30 14:27:16 +00:00
#include "FreeRTOS.h"
#include "task.h"
#include "app_tasks.h"
2023-10-22 04:14:37 +00:00
#include "core/core.h"
2023-09-05 09:14:20 +00:00
#include "core/settings.h"
2023-08-22 12:37:29 +00:00
#include "hal.h"
2023-09-05 09:14:20 +00:00
#include "pwr.h"
2023-09-15 02:21:06 +00:00
#include "usb/usb.h"
2023-09-05 09:14:20 +00:00
2024-03-13 09:53:43 +00:00
#define VBAT_MIN 3100
2024-02-16 14:03:20 +00:00
#define VBAT_MAX 4100
#define VBAT_USB 4600
2023-09-05 09:14:20 +00:00
static void pwr_graceful_shutdown() {
while(hal_flash_busy()) {
;
}
2023-08-22 12:37:29 +00:00
2023-09-05 09:14:20 +00:00
settings_commit();
2023-08-22 12:51:15 +00:00
}
2023-08-22 12:37:29 +00:00
void pwr_reboot() {
2023-09-05 09:14:20 +00:00
pwr_graceful_shutdown();
2023-08-22 12:51:15 +00:00
hal_reboot();
2023-08-22 12:37:29 +00:00
}
void pwr_shutdown() {
2023-09-05 09:14:20 +00:00
pwr_graceful_shutdown();
2023-08-22 12:37:29 +00:00
hal_gpio_set(GPIO_PWR_KILL, GPIO_SET);
}
2023-09-15 02:21:06 +00:00
void pwr_usb_plugged(bool from_isr) {
2023-10-22 04:14:37 +00:00
if (g_settings.enable_usb && g_core.ready) {
2023-09-15 02:21:06 +00:00
hal_usb_start();
}
if (from_isr) {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
vTaskNotifyGiveIndexedFromISR(APP_TASK(usb), USB_NOTIFICATION_IDX, &xHigherPriorityTaskWoken);
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
} else {
xTaskNotifyGiveIndexed(APP_TASK(usb), USB_NOTIFICATION_IDX);
}
2023-08-22 12:37:29 +00:00
}
void pwr_usb_unplugged() {
2023-08-29 06:49:51 +00:00
hal_usb_stop();
2023-08-22 12:37:29 +00:00
}
void pwr_smartcard_inserted() {
2024-02-19 10:00:35 +00:00
#ifndef TEST_APP
2023-08-22 12:37:29 +00:00
pwr_reboot();
2024-02-19 10:00:35 +00:00
#endif
2023-08-22 12:37:29 +00:00
}
void pwr_smartcard_removed() {
2024-02-19 10:00:35 +00:00
#ifndef TEST_APP
2023-08-22 12:37:29 +00:00
pwr_shutdown();
2024-02-19 10:00:35 +00:00
#endif
2023-08-22 12:37:29 +00:00
}
2023-09-14 02:53:53 +00:00
void pwr_inactivity_timer_elapsed() {
2023-09-14 06:59:22 +00:00
pwr_shutdown();
2023-09-14 02:53:53 +00:00
}
2024-02-16 14:03:20 +00:00
uint8_t pwr_battery_level() {
uint32_t vbat;
hal_adc_read(ADC_VBAT, &vbat);
if (vbat > VBAT_USB) {
return PWR_BATTERY_CHARGING;
} else if (vbat > VBAT_MAX) {
vbat = VBAT_MAX;
} else if (vbat < VBAT_MIN) {
vbat = VBAT_MIN;
}
return ((vbat - VBAT_MIN) * 100) / (VBAT_MAX - VBAT_MIN);
}