/* Copyright (c) 2025, Canaan Bright Sight Co., Ltd
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "./api/Common.h"


unsigned long millis(void)
{
    return utils_cpu_ticks_ms();
}

unsigned long micros(void)
{
    return utils_cpu_ticks_us();
}

void delay(unsigned long ms)
{
    unsigned long start = millis();
    unsigned long target = start + ms;

    while (millis() < target) {
        unsigned long remaining = target - millis();
        if (remaining > 0) {
            // 使用较短的睡眠时间，减少被中断的影响
            usleep(remaining > 10 ? 10000 : remaining * 1000);
        }
    }
}

void delayMicroseconds(unsigned int us)
{
    if (us >= 1000) {
        // 大于等于1ms时，使用usleep
        // 但要处理可能被信号中断的情况
        unsigned long start = micros();
        unsigned long target = start + us;

        while (micros() < target) {
            unsigned long remaining = target - micros();
            if (remaining >= 100) {
                usleep(remaining);
            } else {
                // 剩余时间小于100us，使用忙等待
                while (micros() < target) {
                    // 忙等待，可以添加编译器屏障防止优化
                    __asm__ __volatile__("" ::: "memory");
                }
            }
        }
    } else {
        // 小于1ms时，使用忙等待
        unsigned long start = micros();
        unsigned long target = start + us;

        while (micros() < target) {
            // 忙等待，可以添加编译器屏障防止优化
            __asm__ __volatile__("" ::: "memory");
        }
    }
}
