services.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /*
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <stdio.h>
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/timers.h"
  10. #include "esp_log.h"
  11. #include "esp_sleep.h"
  12. #include "driver/rtc_io.h"
  13. #include "driver/gpio.h"
  14. #include "driver/ledc.h"
  15. #include "driver/i2c.h"
  16. #include "driver/rmt.h"
  17. #include "platform_config.h"
  18. #include "gpio_exp.h"
  19. #include "battery.h"
  20. #include "led.h"
  21. #include "monitor.h"
  22. #include "globdefs.h"
  23. #include "accessors.h"
  24. #include "messaging.h"
  25. #include "buttons.h"
  26. #include "services.h"
  27. extern void battery_svc_init(void);
  28. extern void monitor_svc_init(void);
  29. extern void led_svc_init(void);
  30. int i2c_system_port = I2C_SYSTEM_PORT;
  31. int i2c_system_speed = 400000;
  32. int spi_system_host = SPI_SYSTEM_HOST;
  33. int spi_system_dc_gpio = -1;
  34. int rmt_system_base_tx_channel = RMT_CHANNEL_0;
  35. int rmt_system_base_rx_channel = RMT_CHANNEL_MAX-1;
  36. pwm_system_t pwm_system = {
  37. .timer = LEDC_TIMER_0,
  38. .base_channel = LEDC_CHANNEL_0,
  39. .max = (1 << LEDC_TIMER_13_BIT),
  40. };
  41. static EXT_RAM_ATTR struct {
  42. uint64_t wake_gpio, wake_level;
  43. uint64_t rtc_gpio, rtc_level;
  44. uint32_t delay, spurious;
  45. float battery_level;
  46. int battery_count;
  47. void (*idle_chain)(uint32_t now);
  48. void (*battery_chain)(float level, int cells);
  49. void (*suspend[10])(void);
  50. uint32_t (*sleeper[10])(void);
  51. } sleep_context;
  52. static const char *TAG = "services";
  53. /****************************************************************************************
  54. *
  55. */
  56. void set_chip_power_gpio(int gpio, char *value) {
  57. bool parsed = true;
  58. // we only parse on-chip GPIOs
  59. if (gpio >= GPIO_NUM_MAX) return;
  60. if (!strcasecmp(value, "vcc") ) {
  61. gpio_pad_select_gpio(gpio);
  62. gpio_set_direction(gpio, GPIO_MODE_OUTPUT);
  63. gpio_set_level(gpio, 1);
  64. } else if (!strcasecmp(value, "gnd")) {
  65. gpio_pad_select_gpio(gpio);
  66. gpio_set_direction(gpio, GPIO_MODE_OUTPUT);
  67. gpio_set_level(gpio, 0);
  68. } else parsed = false;
  69. if (parsed) ESP_LOGI(TAG, "set GPIO %u to %s", gpio, value);
  70. }
  71. /****************************************************************************************
  72. *
  73. */
  74. void set_exp_power_gpio(int gpio, char *value) {
  75. bool parsed = true;
  76. // we only parse on-chip GPIOs
  77. if (gpio < GPIO_NUM_MAX) return;
  78. if (!strcasecmp(value, "vcc") ) {
  79. gpio_exp_set_direction(gpio, GPIO_MODE_OUTPUT, NULL);
  80. gpio_exp_set_level(gpio, 1, true, NULL);
  81. } else if (!strcasecmp(value, "gnd")) {
  82. gpio_exp_set_direction(gpio, GPIO_MODE_OUTPUT, NULL);
  83. gpio_exp_set_level(gpio, 0, true, NULL);
  84. } else parsed = false;
  85. if (parsed) ESP_LOGI(TAG, "set expanded GPIO %u to %s", gpio, value);
  86. }
  87. /****************************************************************************************
  88. *
  89. */
  90. static void sleep_gpio_handler(void *id, button_event_e event, button_press_e mode, bool long_press) {
  91. if (event == BUTTON_PRESSED) services_sleep_activate(SLEEP_ONGPIO);
  92. }
  93. /****************************************************************************************
  94. *
  95. */
  96. static void sleep_timer(uint32_t now) {
  97. static EXT_RAM_ATTR uint32_t last, first;
  98. // first chain the calls to pseudo_idle function
  99. if (sleep_context.idle_chain) sleep_context.idle_chain(now);
  100. // we need boot time for spurious timeout calculation
  101. if (!first) first = now;
  102. // only query callbacks every 30s if we have at least one sleeper
  103. if (!*sleep_context.sleeper || now < last + 30*1000) return;
  104. last = now;
  105. // time to evaluate if we had spurious wake-up
  106. if (sleep_context.spurious && now > sleep_context.spurious + first) {
  107. bool spurious = true;
  108. // see if at least one sleeper has been awake since we started
  109. for (uint32_t (**sleeper)(void) = sleep_context.sleeper; *sleeper && spurious; sleeper++) {
  110. spurious &= (*sleeper)() >= now - first;
  111. }
  112. // no activity since we woke-up, this was a spurious one
  113. if (spurious) {
  114. ESP_LOGI(TAG, "spurious wake of %d sec, going back to sleep", (now - first) / 1000);
  115. services_sleep_activate(SLEEP_ONTIMER);
  116. }
  117. // resume normal work but we might have no "regular" inactivity delay
  118. sleep_context.spurious = 0;
  119. if (!sleep_context.delay) *sleep_context.sleeper = NULL;
  120. ESP_LOGI(TAG, "wake-up was not spurious after %d sec", (now - first) / 1000);
  121. }
  122. // we might be here because we are waiting for spurious
  123. if (sleep_context.delay) {
  124. // call all sleepers to know how long for how long they have been inactive
  125. for (uint32_t (**sleeper)(void) = sleep_context.sleeper; sleep_context.delay && *sleeper; sleeper++) {
  126. if ((*sleeper)() < sleep_context.delay) return;
  127. }
  128. // if we are here, we are ready to sleep;
  129. services_sleep_activate(SLEEP_ONTIMER);
  130. }
  131. }
  132. /****************************************************************************************
  133. *
  134. */
  135. static void sleep_battery(float level, int cells) {
  136. // chain if any
  137. if (sleep_context.battery_chain) sleep_context.battery_chain(level, cells);
  138. // then assess if we have to stop because of low batt
  139. if (level < sleep_context.battery_level) {
  140. if (sleep_context.battery_count++ == 2) services_sleep_activate(SLEEP_ONBATTERY);
  141. } else {
  142. sleep_context.battery_count = 0;
  143. }
  144. }
  145. /****************************************************************************************
  146. *
  147. */
  148. void services_sleep_init(void) {
  149. char *config = config_alloc_get(NVS_TYPE_STR, "sleep_config");
  150. char *p;
  151. // get the wake criteria
  152. if ((p = strcasestr(config, "wake"))) {
  153. char list[32] = "", item[8];
  154. sscanf(p, "%*[^=]=%31[^,]", list);
  155. p = list - 1;
  156. while (p++ && sscanf(p, "%7[^|]", item)) {
  157. int level = 0, gpio = atoi(item);
  158. if (!rtc_gpio_is_valid_gpio(gpio)) {
  159. ESP_LOGE(TAG, "invalid wake GPIO %d (not in RTC domain)", gpio);
  160. } else {
  161. sleep_context.wake_gpio |= 1LL << gpio;
  162. }
  163. if (sscanf(item, "%*[^:]:%d", &level)) sleep_context.wake_level |= level << gpio;
  164. p = strchr(p, '|');
  165. }
  166. // when moving to esp-idf more recent than 4.4.x, multiple gpio wake-up with level specific can be done
  167. if (sleep_context.wake_gpio) {
  168. ESP_LOGI(TAG, "Sleep wake-up gpio bitmap 0x%llx (active 0x%llx)", sleep_context.wake_gpio, sleep_context.wake_level);
  169. }
  170. }
  171. // do we want battery safety
  172. PARSE_PARAM_FLOAT(config, "batt", '=', sleep_context.battery_level);
  173. if (sleep_context.battery_level != 0.0) {
  174. sleep_context.battery_chain = battery_handler_svc;
  175. battery_handler_svc = sleep_battery;
  176. ESP_LOGI(TAG, "Sleep on battery level of %.2f", sleep_context.battery_level);
  177. }
  178. // get the rtc-pull criteria
  179. if ((p = strcasestr(config, "rtc"))) {
  180. char list[32] = "", item[8];
  181. sscanf(p, "%*[^=]=%31[^,]", list);
  182. p = list - 1;
  183. while (p++ && sscanf(p, "%7[^|]", item)) {
  184. int level = 0, gpio = atoi(item);
  185. if (!rtc_gpio_is_valid_gpio(gpio)) {
  186. ESP_LOGE(TAG, "invalid rtc GPIO %d", gpio);
  187. } else {
  188. sleep_context.rtc_gpio |= 1LL << gpio;
  189. }
  190. if (sscanf(item, "%*[^:]:%d", &level)) sleep_context.rtc_level |= level << gpio;
  191. p = strchr(p, '|');
  192. }
  193. // when moving to esp-idf more recent than 4.4.x, multiple gpio wake-up with level specific can be done
  194. if (sleep_context.rtc_gpio) {
  195. ESP_LOGI(TAG, "RTC forced gpio bitmap 0x%llx (active 0x%llx)", sleep_context.rtc_gpio, sleep_context.rtc_level);
  196. }
  197. }
  198. // get the GPIOs that activate sleep (we could check that we have a valid wake)
  199. if ((p = strcasestr(config, "sleep"))) {
  200. int gpio, level = 0;
  201. char sleep[8] = "";
  202. sscanf(p, "%*[^=]=%7[^,]", sleep);
  203. gpio = atoi(sleep);
  204. if ((p = strchr(sleep, ':')) != NULL) level = atoi(p + 1);
  205. ESP_LOGI(TAG, "Sleep activation gpio %d (active %d)", gpio, level);
  206. button_create(NULL, gpio, level ? BUTTON_HIGH : BUTTON_LOW, true, 0, sleep_gpio_handler, 0, -1);
  207. }
  208. // do we want delay sleep
  209. PARSE_PARAM(config, "delay", '=', sleep_context.delay);
  210. sleep_context.delay *= 60*1000;
  211. // now check why we woke-up
  212. esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
  213. if (cause == ESP_SLEEP_WAKEUP_EXT0 || cause == ESP_SLEEP_WAKEUP_EXT1) {
  214. ESP_LOGI(TAG, "waking-up from deep sleep with cause %d", cause);
  215. // find the type of wake-up
  216. uint64_t wake_gpio;
  217. if (cause == ESP_SLEEP_WAKEUP_EXT0) wake_gpio = sleep_context.wake_gpio;
  218. else wake_gpio = esp_sleep_get_ext1_wakeup_status();
  219. // we might be woken up by infrared in which case we want a short sleep
  220. if (infrared_gpio() >= 0 && ((1LL << infrared_gpio()) & wake_gpio)) {
  221. sleep_context.spurious = 1;
  222. PARSE_PARAM(config, "spurious", '=', sleep_context.spurious);
  223. sleep_context.spurious *= 60*1000;
  224. ESP_LOGI(TAG, "spurious wake-up detection during %d sec", sleep_context.spurious / 1000);
  225. }
  226. }
  227. // if we have inactivity timer (user-set or because of IR wake) then active counters
  228. if (sleep_context.delay || sleep_context.spurious) {
  229. sleep_context.idle_chain = pseudo_idle_svc;
  230. pseudo_idle_svc = sleep_timer;
  231. if (sleep_context.delay) ESP_LOGI(TAG, "inactivity timer of %d minute(s)", sleep_context.delay / (60*1000));
  232. }
  233. }
  234. /****************************************************************************************
  235. *
  236. */
  237. void services_sleep_activate(sleep_cause_e cause) {
  238. // call all sleep hooks that might want to do something
  239. for (void (**suspend)(void) = sleep_context.suspend; *suspend; suspend++) (*suspend)();
  240. // isolate all possible GPIOs, except the wake-up and RTC-maintaines ones
  241. esp_sleep_config_gpio_isolate();
  242. // keep RTC domain up if we need to maintain pull-up/down of some GPIO from RTC
  243. if (sleep_context.rtc_gpio) esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
  244. for (int i = 0; i < GPIO_NUM_MAX; i++) {
  245. // must be a RTC GPIO
  246. if (!rtc_gpio_is_valid_gpio(i)) continue;
  247. // do we need to maintain a pull-up or down of that GPIO
  248. if ((1LL << i) & sleep_context.rtc_gpio) {
  249. if ((sleep_context.rtc_level >> i) & 0x01) rtc_gpio_pullup_en(i);
  250. else rtc_gpio_pulldown_en(i);
  251. // or is this not wake-up GPIO, just isolate it
  252. } else if (!((1LL << i) & sleep_context.wake_gpio)) {
  253. rtc_gpio_isolate(i);
  254. }
  255. }
  256. // is there just one GPIO
  257. if (sleep_context.wake_gpio & (sleep_context.wake_gpio - 1)) {
  258. ESP_LOGI(TAG, "going to sleep cause %d, wake-up on multiple GPIO, any '1' wakes up 0x%llx", cause, sleep_context.wake_gpio);
  259. #if defined(CONFIG_IDF_TARGET_ESP32S3) && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 0)
  260. if (!sleep_context.wake_level) esp_sleep_enable_ext1_wakeup(sleep_context.wake_gpio, ESP_EXT1_WAKEUP_ANY_LOW);
  261. else
  262. #endif
  263. esp_sleep_enable_ext1_wakeup(sleep_context.wake_gpio, ESP_EXT1_WAKEUP_ANY_HIGH);
  264. } else if (sleep_context.wake_gpio) {
  265. int gpio = __builtin_ctzll(sleep_context.wake_gpio);
  266. int level = (sleep_context.wake_level >> gpio) & 0x01;
  267. ESP_LOGI(TAG, "going to sleep cause %d, wake-up on GPIO %d level %d", cause, gpio, level);
  268. esp_sleep_enable_ext0_wakeup(gpio, level);
  269. } else {
  270. ESP_LOGW(TAG, "going to sleep cause %d, no wake-up option", cause);
  271. }
  272. // we need to use a timer in case the same button is used for sleep and wake-up and it's "pressed" vs "released" selected
  273. if (cause == SLEEP_ONKEY) xTimerStart(xTimerCreate("sleepTimer", pdMS_TO_TICKS(1000), pdFALSE, NULL, (void (*)(void*)) esp_deep_sleep_start), 0);
  274. else esp_deep_sleep_start();
  275. }
  276. /****************************************************************************************
  277. *
  278. */
  279. static void register_method(void **store, size_t size, void *method) {
  280. for (int i = 0; i < size; i++, *store++) if (!*store) {
  281. *store = method;
  282. return;
  283. }
  284. }
  285. /****************************************************************************************
  286. *
  287. */
  288. void services_sleep_setsuspend(void (*hook)(void)) {
  289. register_method((void**) sleep_context.suspend, sizeof(sleep_context.suspend)/sizeof(*sleep_context.suspend), (void*) hook);
  290. }
  291. /****************************************************************************************
  292. *
  293. */
  294. void services_sleep_setsleeper(uint32_t (*sleeper)(void)) {
  295. register_method((void**) sleep_context.sleeper, sizeof(sleep_context.sleeper)/sizeof(*sleep_context.sleeper), (void*) sleeper);
  296. }
  297. /****************************************************************************************
  298. *
  299. */
  300. void services_init(void) {
  301. messaging_service_init();
  302. gpio_install_isr_service(0);
  303. #ifdef CONFIG_I2C_LOCKED
  304. if (i2c_system_port == 0) {
  305. i2c_system_port = 1;
  306. ESP_LOGE(TAG, "Port 0 is reserved for internal DAC use");
  307. }
  308. #endif
  309. // set potential power GPIO on chip first in case expanders are power using these
  310. parse_set_GPIO(set_chip_power_gpio);
  311. // shared I2C bus
  312. const i2c_config_t * i2c_config = config_i2c_get(&i2c_system_port);
  313. ESP_LOGI(TAG,"Configuring I2C sda:%d scl:%d port:%u speed:%u", i2c_config->sda_io_num, i2c_config->scl_io_num, i2c_system_port, i2c_config->master.clk_speed);
  314. if (i2c_config->sda_io_num != -1 && i2c_config->scl_io_num != -1) {
  315. i2c_param_config(i2c_system_port, i2c_config);
  316. i2c_driver_install(i2c_system_port, i2c_config->mode, 0, 0, 0 );
  317. } else {
  318. i2c_system_port = -1;
  319. ESP_LOGW(TAG, "no I2C configured");
  320. }
  321. const spi_bus_config_t * spi_config = config_spi_get((spi_host_device_t*) &spi_system_host);
  322. ESP_LOGI(TAG,"Configuring SPI mosi:%d miso:%d clk:%d host:%u dc:%d", spi_config->mosi_io_num, spi_config->miso_io_num, spi_config->sclk_io_num, spi_system_host, spi_system_dc_gpio);
  323. if (spi_config->mosi_io_num != -1 && spi_config->sclk_io_num != -1) {
  324. spi_bus_initialize( spi_system_host, spi_config, SPI_DMA_CH_AUTO );
  325. if (spi_system_dc_gpio != -1) {
  326. gpio_reset_pin(spi_system_dc_gpio);
  327. gpio_set_direction( spi_system_dc_gpio, GPIO_MODE_OUTPUT );
  328. gpio_set_level( spi_system_dc_gpio, 0 );
  329. } else {
  330. ESP_LOGW(TAG, "No DC GPIO set, SPI display will not work");
  331. }
  332. } else {
  333. spi_system_host = -1;
  334. ESP_LOGW(TAG, "no SPI configured");
  335. }
  336. // create GPIO expanders
  337. const gpio_exp_config_t* gpio_exp_config;
  338. for (int count = 0; (gpio_exp_config = config_gpio_exp_get(count)); count++) gpio_exp_create(gpio_exp_config);
  339. // now set potential power GPIO on expander
  340. parse_set_GPIO(set_exp_power_gpio);
  341. // system-wide PWM timer configuration
  342. ledc_timer_config_t pwm_timer = {
  343. .duty_resolution = LEDC_TIMER_13_BIT,
  344. .freq_hz = 5000,
  345. #ifdef CONFIG_IDF_TARGET_ESP32S3
  346. .speed_mode = LEDC_LOW_SPEED_MODE,
  347. #else
  348. .speed_mode = LEDC_HIGH_SPEED_MODE,
  349. #endif
  350. .timer_num = pwm_system.timer,
  351. };
  352. ledc_timer_config(&pwm_timer);
  353. led_svc_init();
  354. battery_svc_init();
  355. monitor_svc_init();
  356. }