#include "stm32g4xx.h"
#include "drill_button.h"
#include "drill_button_target.h"
static db_state button;
static bool owned;
volatile db_snapshot drill_debug_button;
static bool pressed(void){return (GPIOA->IDR&(1u<<11))==0;}
bool drill_button_init(uint32_t now){
 if(!(RCC->AHB2ENR&RCC_AHB2ENR_GPIOAEN))return false;
 /* PA11 USER_BUTTON has external R7 10k pull-up to CTRL_3V3 in A32.
    Input-only configuration; no peripheral alternate function or output. */
 GPIOA->MODER&=~(3u<<22);GPIOA->PUPDR&=~(3u<<22);__DSB();
 db_init(&button,now,pressed());owned=true;drill_debug_button.available=1u;return true;
}
void drill_button_poll(uint32_t now){
 if(!owned)return;
 if(!(RCC->AHB2ENR&RCC_AHB2ENR_GPIOAEN) ||
    (GPIOA->MODER&(3u<<22)) || (GPIOA->PUPDR&(3u<<22))){
 ++drill_debug_button.epoch;__DMB();drill_debug_button.available=0u;__DMB();++drill_debug_button.epoch;owned=false;return;}
 bool down=pressed();dc_command c=db_sample(&button,now,down);
 ++drill_debug_button.epoch;__DMB();
 ++drill_debug_button.samples;drill_debug_button.last_us=now;drill_debug_button.pressed=down;
 if(c!=DC_NONE){++drill_debug_button.events;drill_debug_button.last_command=(uint32_t)c;}
 __DMB();++drill_debug_button.epoch;
}
