wifi_management_task.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * SPDX-FileCopyrightText: 2023 Helmut Pozimski <helmut@pozimski.eu>
  3. *
  4. * SPDX-License-Identifier: GPL-2.0-only
  5. */
  6. #include <esp_log.h>
  7. #include <freertos/FreeRTOS.h>
  8. #include <freertos/event_groups.h>
  9. #include <apps/esp_sntp.h>
  10. #include "wifi.h"
  11. #include "ds3231.h"
  12. #include "time_conversion.h"
  13. #define TAG "wifi_management_task"
  14. #define SECONDS_PER_DAY 86400
  15. static uint32_t calculate_current_second(struct tm* local_time) {
  16. return local_time->tm_hour * 60 * 60 + local_time->tm_min * 60 + local_time->tm_sec;
  17. }
  18. static uint32_t determine_sleep_seconds(struct tm* local_time) {
  19. uint32_t current_second = calculate_current_second(local_time);
  20. uint32_t reference_second;
  21. if (local_time->tm_hour >= 22) {
  22. reference_second = (SECONDS_PER_DAY - current_second) + 6 * 60 * 60;
  23. } else {
  24. reference_second = (22 * 60 * 60) - current_second;
  25. }
  26. return reference_second;
  27. }
  28. void wifi_management_task(void *pvParameters) {
  29. struct tm current_time;
  30. uint8_t* wifi_enabled_flag = (uint8_t*) pvParameters;
  31. while(1) {
  32. ESP_LOGI(TAG, "wifi_managent_task is executed");
  33. struct tm* local_time;
  34. ds3231_read_date_time(&current_time);
  35. local_time = convert_to_local(&current_time);
  36. if (local_time->tm_hour >= 22 && *wifi_enabled_flag) {
  37. ESP_LOGI(TAG, "Stopping wifi");
  38. wifi_stop();
  39. *wifi_enabled_flag = 0;
  40. } else if (local_time->tm_hour >= 6 && !*wifi_enabled_flag) {
  41. ESP_LOGI(TAG, "Starting wifi");
  42. wifi_start();
  43. *wifi_enabled_flag = 1;
  44. sntp_restart();
  45. }
  46. uint32_t sleep_seconds = determine_sleep_seconds(local_time);
  47. ESP_LOGI(TAG, "Sleeping for %ld seconds", sleep_seconds);
  48. vTaskDelay(sleep_seconds * 1000 / portTICK_PERIOD_MS);
  49. }
  50. vTaskDelete( NULL );
  51. }