BellUtils.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #ifndef EUPHONIUM_BELL_UTILS
  2. #define EUPHONIUM_BELL_UTILS
  3. #include <string.h>
  4. #ifdef _WIN32
  5. #include <WinSock2.h>
  6. #else
  7. #include <sys/time.h>
  8. #endif
  9. #include <random>
  10. #include <vector>
  11. #ifdef ESP_PLATFORM
  12. #include "esp_system.h"
  13. #endif
  14. namespace bell {
  15. std::string generateRandomUUID();
  16. void freeAndNull(void*& ptr);
  17. std::string getMacAddress();
  18. struct tv {
  19. tv() {}
  20. tv(timeval tv) : sec(tv.tv_sec), usec(tv.tv_usec){};
  21. tv(int32_t _sec, int32_t _usec) : sec(_sec), usec(_usec){};
  22. static tv now() {
  23. tv timestampNow;
  24. #if _WIN32
  25. static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
  26. SYSTEMTIME system_time;
  27. FILETIME file_time;
  28. uint64_t time;
  29. GetSystemTime(&system_time);
  30. SystemTimeToFileTime(&system_time, &file_time);
  31. time = ((uint64_t)file_time.dwLowDateTime);
  32. time += ((uint64_t)file_time.dwHighDateTime) << 32;
  33. timestampNow.sec = (long)((time - EPOCH) / 10000000L);
  34. timestampNow.usec = (long)(system_time.wMilliseconds * 1000);
  35. #else
  36. timeval t;
  37. gettimeofday(&t, NULL);
  38. timestampNow.sec = t.tv_sec;
  39. timestampNow.usec = t.tv_usec;
  40. #endif
  41. return timestampNow;
  42. }
  43. int32_t sec;
  44. int32_t usec;
  45. int64_t ms() { return (sec * (int64_t)1000) + (usec / 1000); }
  46. tv operator+(const tv& other) const {
  47. tv result(*this);
  48. result.sec += other.sec;
  49. result.usec += other.usec;
  50. if (result.usec > 1000000) {
  51. result.sec += result.usec / 1000000;
  52. result.usec %= 1000000;
  53. }
  54. return result;
  55. }
  56. tv operator/(const int& other) const {
  57. tv result(*this);
  58. int64_t millis = result.ms();
  59. millis = millis / other;
  60. result.sec = std::floor(millis / 1000.0);
  61. result.usec = (int32_t)((int64_t)(millis * 1000) % 1000000);
  62. return result;
  63. }
  64. tv operator-(const tv& other) const {
  65. tv result(*this);
  66. result.sec -= other.sec;
  67. result.usec -= other.usec;
  68. while (result.usec < 0) {
  69. result.sec -= 1;
  70. result.usec += 1000000;
  71. }
  72. return result;
  73. }
  74. };
  75. } // namespace bell
  76. #ifdef ESP_PLATFORM
  77. #include <freertos/FreeRTOS.h>
  78. #define BELL_SLEEP_MS(ms) vTaskDelay(ms / portTICK_PERIOD_MS)
  79. #define BELL_YIELD() taskYIELD()
  80. #elif defined(_WIN32)
  81. #define BELL_SLEEP_MS(ms) Sleep(ms)
  82. #define BELL_YIELD() ;
  83. #else
  84. #include <unistd.h>
  85. #define BELL_SLEEP_MS(ms) usleep(ms * 1000)
  86. #define BELL_YIELD() ;
  87. #endif
  88. #endif