1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
#include "esp_sleep.h"
#include "../include/stepper.h"
#include "../include/wifi.h"
#include "../include/sntp.h"
#include "../include/sun.h"
#define us_in_h 3600000000
#define us_in_m 60000000
#define us_in_s 1000000
void app_main() {
// WIFI CONFIGURATION
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
//ESP_LOGI(WIFI_TAG, "ESP_WIFI_MODE_STA");
wifi_init_sta();
// DATE AND TIME CONFIGURATION
time_t now;
struct tm time_info;
time(&now);
localtime_r(&now, &time_info);
//ESP_LOGI(SNTP_TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP.");
obtain_time();
time(&now);
char time_strftime_buf[64];
setenv("TZ", "EST5EDT,M3.2.0/2,M11.1.0", 1);
tzset();
localtime_r(&now, &time_info);
strftime(time_strftime_buf, sizeof(time_strftime_buf), "%c", &time_info);
//ESP_LOGI(SNTP_TAG, "The current date/time in Toronto is: %s", time_strftime_buf);
// CALCULATE SUN TIME
struct tm sun_time;
double sun_time_double = sun_calculation(time_info, LONGITUDE, LATITUDE);
//printf("sun_time is %f\n", sun_time_double);
sun_time.tm_hour = floor(sun_time_double);
sun_time.tm_min = floor((sun_time_double - sun_time.tm_hour) * 60);
sun_time.tm_sec = floor((((sun_time_double - sun_time.tm_hour) * 60) - sun_time.tm_min) * 60);
//TESTING STEPPER MOTOR TIMING
// while(true) {
// stepper_init();
// stepper_open();
// stepper_close();
// stepper_uninit();
// }
if(sun_time.tm_hour != time_info.tm_hour) {
//printf("going to deep sleep\n");
esp_deep_sleep(us_in_h);
} else {
// SLEEP CONFIGURATION
esp_sleep_enable_timer_wakeup(us_in_s);
// MAIN LOOP
while(true) {
time(&now);
localtime_r(&now, &time_info);
if(time_info.tm_min < sun_time.tm_min) {
//printf("light sleep\n");
esp_light_sleep_start();
}
if(time_info.tm_hour < 12) {
stepper_init();
stepper_open();
stepper_uninit();
esp_deep_sleep(us_in_m);
} else {
stepper_init();
stepper_close();
stepper_uninit();
esp_deep_sleep(us_in_m);
}
}
}
}
|