/*
    PIP - Platform Independent Primitives
    Ivan Pelipenko peri4ko@yandex.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "pitime.h"

#include "piincludes_p.h"
#ifdef QNX
#  include <time.h>
#endif
#ifndef MICRO_PIP
#  include "pisystemtests.h"
#elif defined(ARDUINO)
#  include <Arduino.h>
#endif
#ifdef MICRO_PIP
#  include <sys/time.h>
#endif


//! \details
//! \~english
//! This function consider \c "usleep" offset
//! on QNX/Linux/Mac, which is calculated with
//! \a pip_sys_test program. If this is correct
//! offset value in system config, this function
//! wait \b exactly "usecs" microseconds.
//! \~russian
//! Этот метод учитывает смещение \c "usleep"
//! на QNX/Linux/Mac, которое расчитывается с помощью
//! утилиты \a pip_sys_test. Если это значение в системном
//! конфиге действительно, то этот метод будет ожидать
//! \b точно "usecs" микросекунд.
void piUSleep(int usecs) {
	if (usecs <= 0) return;
#ifdef WINDOWS
	// printf("Sleep %d\n", usecs / 1000);
	if (usecs > 0) Sleep(usecs / 1000);
		// printf("Sleep end");
#else
#  ifdef FREERTOS
	vTaskDelay(usecs / 1000 / portTICK_PERIOD_MS);
#  else
	usecs -= PISystemTests::usleep_offset_us;
	if (usecs > 0) usleep(usecs);
#  endif
#endif
}
