BellUtils.h 2.3 KB

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