-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathmain-esp32.cpp
More file actions
406 lines (360 loc) · 13 KB
/
Copy pathmain-esp32.cpp
File metadata and controls
406 lines (360 loc) · 13 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#include "PowerFSM.h"
#include "PowerMon.h"
#include "configuration.h"
#include "esp_task_wdt.h"
#include "main.h"
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !MESHTASTIC_EXCLUDE_BLUETOOTH
#include "nimble/NimbleBluetooth.h"
#endif
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !MESHTASTIC_EXCLUDE_BLUETOOTH && __has_include(<esp_bt.h>)
#include <esp_bt.h>
#define CAN_RELEASE_BT_MEMORY 1
#endif
#include <MeshtasticOTA.h>
#if HAS_WIFI
#include "mesh/wifi/WiFiAPClient.h"
#endif
#include "esp_mac.h"
#include "freertosinc.h"
#include "meshUtils.h"
#include "sleep.h"
#include "soc/rtc.h"
#include "target_specific.h"
#include <Preferences.h>
#include <driver/rtc_io.h>
#include <esp_efuse.h>
#include <esp_efuse_table.h>
#include <nvs.h>
#include <nvs_flash.h>
// Weak empty variant shutdown prep function.
// May be redefined by variant files.
void variant_shutdown() __attribute__((weak));
void variant_shutdown() {}
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !MESHTASTIC_EXCLUDE_BLUETOOTH
static bool bluetoothMemoryReleased;
static bool bluetoothMemoryReleaseWarned;
#endif
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !MESHTASTIC_EXCLUDE_BLUETOOTH
static bool isNetworkConfiguredToDisableBluetooth()
{
#if HAS_WIFI
return isWifiAvailable();
#elif defined(USE_WS5500) || defined(USE_CH390D)
return config.network.wifi_enabled;
#else
return false;
#endif
}
static bool isPaxcounterActiveForBoot()
{
#if !MESHTASTIC_EXCLUDE_PAXCOUNTER
return moduleConfig.has_paxcounter && moduleConfig.paxcounter.enabled && !config.bluetooth.enabled &&
!config.network.wifi_enabled;
#else
return false;
#endif
}
static bool shouldReleaseBluetoothMemory()
{
// Paxcounter disables the Meshtastic BLE service, but libpax still needs the
// ESP32 BLE controller memory for scanning.
if (isPaxcounterActiveForBoot()) {
LOG_DEBUG("Skipping Bluetooth memory release because Paxcounter is active");
return false;
}
// On ESP32 targets WiFi and BLE share radio resources. When WiFi is configured for this boot,
// BLE will not be started, so its reserved memory can be returned to the heap until reboot.
if (isNetworkConfiguredToDisableBluetooth()) {
return true;
}
return !config.bluetooth.enabled;
}
static const char *getBluetoothReleaseReason()
{
if (isNetworkConfiguredToDisableBluetooth()) {
return "WiFi is enabled";
}
return "Bluetooth is disabled";
}
#endif
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !MESHTASTIC_EXCLUDE_BLUETOOTH
void setBluetoothEnable(bool enable)
{
if (enable && bluetoothMemoryReleased) {
if (!shouldReleaseBluetoothMemory() && !bluetoothMemoryReleaseWarned) {
bluetoothMemoryReleaseWarned = true;
LOG_WARN("Bluetooth memory has been released; reboot to re-enable Bluetooth");
}
return;
}
#if defined(USE_WS5500) || defined(USE_CH390D)
if ((config.bluetooth.enabled == true) && (config.network.wifi_enabled == false))
#elif HAS_WIFI
if (!isWifiAvailable() && config.bluetooth.enabled == true)
#else
if (config.bluetooth.enabled == true)
#endif
{
if (!nimbleBluetooth) {
nimbleBluetooth = new NimbleBluetooth();
}
if (enable && !nimbleBluetooth->isActive()) {
powerMon->setState(meshtastic_PowerMon_State_BT_On);
nimbleBluetooth->setup();
}
// For ESP32, no way to recover from bluetooth shutdown without reboot
// BLE advertising automatically stops when MCU enters light-sleep(?)
// For deep-sleep, shutdown hardware with nimbleBluetooth->deinit(). Requires reboot to reverse
}
}
#else
void setBluetoothEnable(bool enable) {}
void updateBatteryLevel(uint8_t level) {}
#endif
void esp32ReleaseBluetoothMemoryIfUnused()
{
#ifdef CAN_RELEASE_BT_MEMORY
if (bluetoothMemoryReleased || !shouldReleaseBluetoothMemory()) {
return;
}
const int32_t heapBefore = ESP.getHeapSize();
const int32_t freeBefore = ESP.getFreeHeap();
// ESP_BT_MODE_BTDM releases all BT/BLE controller and host memory for this boot.
// It is intentionally irreversible until reboot, matching the runtime config behavior.
esp_err_t err = esp_bt_mem_release(ESP_BT_MODE_BTDM);
if (err == ESP_OK) {
bluetoothMemoryReleased = true;
LOG_INFO("Released BTDM memory because %s: heap %+d, free %+d", getBluetoothReleaseReason(),
(int32_t)ESP.getHeapSize() - heapBefore, (int32_t)ESP.getFreeHeap() - freeBefore);
} else {
LOG_WARN("BTDM memory release failed: %d", err);
}
#endif
}
void getMacAddr(uint8_t *dmac)
{
#if defined(CONFIG_IDF_TARGET_ESP32C6) && defined(CONFIG_SOC_IEEE802154_SUPPORTED)
auto res = esp_base_mac_addr_get(dmac);
assert(res == ESP_OK);
#else
auto res = esp_efuse_mac_get_default(dmac);
assert(res == ESP_OK);
#endif
}
bool getDeviceId(uint8_t *deviceId)
{
#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) || \
defined(CONFIG_IDF_TARGET_ESP32C6)
// ESP32 factory burns a 128-bit unique id in efuse for S2+ and C3+ series (used for HMACs
// in the esp-rainmaker AIOT platform); a good stable hardware anchor for us too.
uint32_t unique_id[4];
esp_err_t err = esp_efuse_read_field_blob(ESP_EFUSE_OPTIONAL_UNIQUE_ID, unique_id, sizeof(unique_id) * 8);
if (err != ESP_OK) {
LOG_WARN("Failed to read unique id from efuse");
return false;
}
memcpy(deviceId, unique_id, sizeof(unique_id));
return true;
#else
// Classic ESP32 has no OPTIONAL_UNIQUE_ID efuse: fall back to the factory-burned MAC.
return getMacAddrDeviceId(deviceId);
#endif
}
#if HAS_32768HZ
#define CALIBRATE_ONE(cali_clk) calibrate_one(cali_clk, #cali_clk)
static uint32_t calibrate_one(rtc_cal_sel_t cal_clk, const char *name)
{
const uint32_t cal_count = 1000;
// const float factor = (1 << 19) * 1000.0f; unused var?
uint32_t cali_val;
for (int i = 0; i < 5; ++i) {
cali_val = rtc_clk_cal(cal_clk, cal_count);
}
return cali_val;
}
void enableSlowCLK()
{
rtc_clk_32k_enable(true);
CALIBRATE_ONE(RTC_CAL_RTC_MUX);
uint32_t cal_32k = CALIBRATE_ONE(RTC_CAL_32K_XTAL);
if (cal_32k == 0) {
LOG_DEBUG("32k XTAL OSC has not started up");
} else {
rtc_clk_slow_freq_set(RTC_SLOW_FREQ_32K_XTAL);
LOG_DEBUG("Switch RTC Source to 32.768kHz succeeded, using 32k XTAL");
CALIBRATE_ONE(RTC_CAL_RTC_MUX);
CALIBRATE_ONE(RTC_CAL_32K_XTAL);
}
CALIBRATE_ONE(RTC_CAL_RTC_MUX);
CALIBRATE_ONE(RTC_CAL_32K_XTAL);
if (rtc_clk_slow_freq_get() != RTC_SLOW_FREQ_32K_XTAL) {
LOG_WARN("Failed to switch 32K XTAL RTC source to 32.768kHz !!! ");
return;
}
}
#endif
void esp32Setup()
{
/* We explicitly don't want to do call randomSeed,
// as that triggers the esp32 core to use a less secure pseudorandom function.
uint32_t seed = esp_random();
LOG_DEBUG("Set random seed %u", seed);
randomSeed(seed);
*/
#ifdef ADC_V
pinMode(ADC_V, INPUT);
#endif
LOG_DEBUG("Total heap: %d", ESP.getHeapSize());
LOG_DEBUG("Free heap: %d", ESP.getFreeHeap());
LOG_DEBUG("Total PSRAM: %d", ESP.getPsramSize());
LOG_DEBUG("Free PSRAM: %d", ESP.getFreePsram());
nvs_stats_t nvs_stats;
auto res = nvs_get_stats(NULL, &nvs_stats);
assert(res == ESP_OK);
LOG_DEBUG("NVS: UsedEntries %d, FreeEntries %d, AllEntries %d, NameSpaces %d", nvs_stats.used_entries, nvs_stats.free_entries,
nvs_stats.total_entries, nvs_stats.namespace_count);
LOG_DEBUG("Setup Preferences in Flash Storage");
// Create object to store our persistent data
Preferences preferences;
preferences.begin("meshtastic", false);
uint32_t rebootCounter = preferences.getUInt("rebootCounter", 0);
rebootCounter++;
preferences.putUInt("rebootCounter", rebootCounter);
// store firmware version and hwrevision for access from OTA firmware
String fwrev = preferences.getString("firmwareVersion", "");
if (fwrev.compareTo(optstr(APP_VERSION)) != 0)
preferences.putString("firmwareVersion", optstr(APP_VERSION));
uint8_t hwven = preferences.getUInt("hwVendor", 0);
if (hwven != HW_VENDOR)
preferences.putUInt("hwVendor", HW_VENDOR);
preferences.end();
LOG_DEBUG("Number of Device Reboots: %d", rebootCounter);
#if !MESHTASTIC_EXCLUDE_WIFI
String version = MeshtasticOTA::getVersion();
if (version.isEmpty()) {
LOG_INFO("MeshtasticOTA firmware not available");
} else {
LOG_INFO("MeshtasticOTA firmware version %s", version.c_str());
}
MeshtasticOTA::initialize();
#endif
// enableModemSleep();
// Since we are turning on watchdogs rather late in the release schedule, we really don't want to catch any
// false positives. The wait-to-sleep timeout for shutting down radios is 30 secs, so pick 45 for now.
// #define APP_WATCHDOG_SECS 45
#define APP_WATCHDOG_SECS 90
#if ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(3, 0, 0)
const esp_task_wdt_config_t wdt_config = {
.timeout_ms = APP_WATCHDOG_SECS * 1000,
.idle_core_mask = (1U << CONFIG_FREERTOS_NUMBER_OF_CORES) - 1U,
.trigger_panic = true,
};
res = esp_task_wdt_init(&wdt_config);
if (res == ESP_ERR_INVALID_STATE) {
LOG_WARN("Task watchdog already initialized, reconfiguring existing instance");
res = esp_task_wdt_reconfigure(&wdt_config);
}
assert(res == ESP_OK);
#else
res = esp_task_wdt_init(APP_WATCHDOG_SECS, true);
if (res == ESP_ERR_INVALID_STATE) {
LOG_WARN("Task watchdog already initialized, reusing existing instance");
res = ESP_OK;
}
assert(res == ESP_OK);
#endif
res = esp_task_wdt_status(NULL);
if (res == ESP_ERR_NOT_FOUND) {
res = esp_task_wdt_add(NULL);
}
assert(res == ESP_OK);
#if HAS_32768HZ
enableSlowCLK();
#endif
}
/// loop code specific to ESP32 targets
void esp32Loop()
{
esp_task_wdt_reset(); // service our app level watchdog
// for debug printing
// radio.radioIf.canSleep();
}
void cpuDeepSleep(uint32_t msecToWake)
{
/*
Some ESP32 IOs have internal pullups or pulldowns, which are enabled by default.
If an external circuit drives this pin in deep sleep mode, current consumption may
increase due to current flowing through these pullups and pulldowns.
To isolate a pin, preventing extra current draw, call rtc_gpio_isolate() function.
For example, on ESP32-WROVER module, GPIO12 is pulled up externally.
GPIO12 also has an internal pulldown in the ESP32 chip. This means that in deep sleep,
some current will flow through these external and internal resistors, increasing deep
sleep current above the minimal possible value.
Note: we don't isolate pins that are used for the LORA, LED, i2c, or ST7735 Display for the Chatter2, spi or the wake
button(s), maybe we should not include any other GPIOs...
*/
#if SOC_RTCIO_HOLD_SUPPORTED
static const uint8_t rtcGpios[] = {
#ifndef HELTEC_VISION_MASTER_E213
// For this variant, >20mA leaks through the display if pin 2 held
// Todo: check if it's safe to remove this pin for all variants
2,
#endif
#ifndef USE_JTAG
13,
#endif
34, 35, 37};
for (int i = 0; i < sizeof(rtcGpios); i++)
rtc_gpio_isolate((gpio_num_t)rtcGpios[i]);
#endif
// FIXME, disable internal rtc pullups/pulldowns on the non isolated pins. for inputs that we aren't using
// to detect wake and in normal operation the external part drives them hard.
#if HAS_BUTTON
uint32_t _btnPin = 0xFF;
#if defined(USERPREFS_BUTTON_PIN)
_btnPin = USERPREFS_BUTTON_PIN;
#elif defined(BUTTON_PIN)
_btnPin = BUTTON_PIN;
#endif
if (config.device.button_gpio != 0) {
_btnPin = config.device.button_gpio;
}
uint64_t gpioMask = 0;
#if SOC_RTCIO_HOLD_SUPPORTED && SOC_PM_SUPPORT_EXT_WAKEUP
if (_btnPin != 0xFF) {
gpioMask |= (1ULL << _btnPin);
}
#endif
#ifdef ALT_BUTTON_WAKE
gpioMask |= (1ULL << BUTTON_PIN_ALT);
#endif
#ifdef BUTTON_NEED_PULLUP
if (_btnPin != 0xFF) {
gpio_pullup_en((gpio_num_t)_btnPin);
}
#endif
if (gpioMask != 0) {
#ifdef ESP32S3_WAKE_TYPE
esp_sleep_enable_ext1_wakeup(gpioMask, ESP32S3_WAKE_TYPE);
#else
#if SOC_PM_SUPPORT_EXT_WAKEUP
#ifdef CONFIG_IDF_TARGET_ESP32
// ESP_EXT1_WAKEUP_ALL_LOW has been deprecated since esp-idf v5.4 for any other target.
esp_sleep_enable_ext1_wakeup(gpioMask, ESP_EXT1_WAKEUP_ALL_LOW);
#else
esp_sleep_enable_ext1_wakeup(gpioMask, ESP_EXT1_WAKEUP_ANY_LOW);
#endif
#endif
#endif // #end ESP32S3_WAKE_TYPE
}
#endif
variant_shutdown();
#if SOC_PM_SUPPORT_RTC_PERIPH_PD
// We want RTC peripherals to stay on
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
#endif
// User shutdown (DELAY_FOREVER / portMAX_DELAY): no RTC timer - align with nRF52 system_off semantics.
if (msecToWake != portMAX_DELAY)
esp_sleep_enable_timer_wakeup(msecToWake * 1000ULL); // call expects usecs
esp_deep_sleep_start();
}