#include "one_wire_impl_ll.h"

onewire_ret_t ow_impl_delay_us(onewire_impl_ll_t *impl, uint32_t usec) {

    LL_RCC_ClocksTypeDef clocks;
    LL_RCC_GetSystemClocksFreq(&clocks);

    uint32_t ticks = usec * (clocks.HCLK_Frequency / 1000000);

    SysTick->CTRL = SYSTICK_CLKSOURCE_HCLK;

    SysTick->LOAD = ticks;
    SysTick->VAL = 0U; // Clear this to zero

    // Start the counter
    SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;

    // Wait until COUNTFLAG has been set.
    while(!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk));
    
    SysTick->CTRL = SYSTICK_CLKSOURCE_HCLK;

    return OW_OK;
}

onewire_ret_t ow_impl_drive_dq(onewire_impl_ll_t *impl, uint8_t value) {
    if(value) {
        LL_GPIO_SetOutputPin(impl->GPIOx, impl->PinMask);
    }
    else {
        LL_GPIO_ResetOutputPin(impl->GPIOx, impl->PinMask);
    }

    return OW_OK;
}

uint8_t ow_impl_read_dq(onewire_impl_ll_t *impl) {
    return LL_GPIO_IsInputPinSet(impl->GPIOx, impl->PinMask) ? 1 : 0;
}

