ESP32 Native version of Blinky, featureful controller code for WS2811/WS2812/NeoPixels
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

58 行
1.4KB

  1. static const char *TAG = "utils";
  2. #include <esp_log.h>
  3. #include <sys/time.h>
  4. #include <cstring>
  5. #include "utils.hpp"
  6. int64_t time_us() {
  7. /*struct timeval tv_now;
  8. gettimeofday(&tv_now, NULL);
  9. return (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec;*/
  10. struct timespec ts;
  11. clock_gettime(CLOCK_MONOTONIC, &ts);
  12. return (int64_t)ts.tv_sec * 1000000L + (int64_t)ts.tv_nsec / 1000L;
  13. }
  14. std::string read_file(const char *path) {
  15. std::string data;
  16. FILE *f = fopen(path, "r");
  17. if (!f) {
  18. ESP_LOGE(TAG, "Failed to read %s", path);
  19. return data;
  20. }
  21. constexpr size_t szbuf = 4096;
  22. char *buf = (char*)malloc(szbuf);
  23. size_t nread;
  24. while ((nread = fread(buf, 1, szbuf - 1, f)) > 0) {
  25. buf[nread] = '\0';
  26. data += buf;
  27. }
  28. fclose(f);
  29. free(buf);
  30. return data;
  31. }
  32. void write_file(const char *path, const std::string &data) {
  33. return write_file(path, data.c_str(), data.length());
  34. }
  35. void write_file(const char *path, const char *data, int len) {
  36. FILE *f = fopen(path, "w");
  37. if (!f) {
  38. ESP_LOGE(TAG, "Failed to open %s", path);
  39. return;
  40. }
  41. const char *ptr = data;
  42. size_t remain = (len < 0 ? strlen(data) : len);
  43. size_t nwritten = fwrite(ptr, 1, remain, f);
  44. if (nwritten != remain) {
  45. ESP_LOGE(TAG, "Failed to write to %s: %d/%d", path, nwritten, remain);
  46. }
  47. fclose(f);
  48. }