pybsleep.c 25.4 KB
Newer Older
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
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Daniel Campora
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <stdint.h>
#include <string.h>

#include "py/mpstate.h"
#include MICROPY_HAL_H
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "py/runtime.h"
#include "inc/hw_types.h"
#include "inc/hw_ints.h"
#include "inc/hw_nvic.h"
#include "inc/hw_common_reg.h"
#include "inc/hw_memmap.h"
#include "cc3200_asm.h"
#include "rom_map.h"
#include "interrupt.h"
#include "systick.h"
#include "prcm.h"
#include "spi.h"
#include "pin.h"
45
#include "pybsleep.h"
46
47
#include "pybpin.h"
#include "simplelink.h"
48
#include "modnetwork.h"
49
50
51
52
53
54
55
#include "modwlan.h"
#include "osi.h"
#include "debug.h"
#include "mpexception.h"
#include "mpcallback.h"
#include "mperror.h"
#include "sleeprestore.h"
56
#include "serverstask.h"
57
58
59
60
61
62
63
64

/******************************************************************************
 DECLARE PRIVATE CONSTANTS
 ******************************************************************************/
#define SPIFLASH_INSTR_READ_STATUS              (0x05)
#define SPIFLASH_INSTR_DEEP_POWER_DOWN          (0xB9)
#define SPIFLASH_STATUS_BUSY                    (0x01)

65
66
67
68
69
70
#define LPDS_UP_TIME                            (425)         // 13 msec
#define LPDS_DOWN_TIME                          (98)          // 3 msec
#define USER_OFFSET                             (131)         // 4 smec
#define WAKEUP_TIME_LPDS                        (LPDS_UP_TIME + LPDS_DOWN_TIME + USER_OFFSET)   // 20 msec
#define WAKEUP_TIME_HIB                         (32768)       // 1 s

71
72
73
#define FORCED_TIMER_INTERRUPT_MS               (1)
#define FAILED_SLEEP_DELAY_MS                   (FORCED_TIMER_INTERRUPT_MS * 3)

74
75
76
77
/******************************************************************************
 DECLARE PRIVATE TYPES
 ******************************************************************************/
// storage memory for Cortex M4 registers
78
79
80
81
82
83
84
85
typedef struct {
    uint32_t     msp;
    uint32_t     psp;
    uint32_t     psr;
    uint32_t     primask;
    uint32_t     faultmask;
    uint32_t     basepri;
    uint32_t     control;
86
} arm_cm4_core_regs_t;
87

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// storage memory for the NVIC registers
typedef struct {
    uint32_t vector_table;      // Vector Table Offset
    uint32_t aux_ctrl;          // Auxiliary control register
    uint32_t int_ctrl_state;    // Interrupt Control and State
    uint32_t app_int;           // Application Interrupt Reset control
    uint32_t sys_ctrl;          // System control
    uint32_t config_ctrl;       // Configuration control
    uint32_t sys_pri_1;         // System Handler Priority 1
    uint32_t sys_pri_2;         // System Handler Priority 2
    uint32_t sys_pri_3;         // System Handler Priority 3
    uint32_t sys_hcrs;          // System Handler control and state register
    uint32_t systick_ctrl;      // SysTick Control Status
    uint32_t systick_reload;    // SysTick Reload
    uint32_t systick_calib;     // SysTick Calibration
    uint32_t int_en[6];         // Interrupt set enable
    uint32_t int_priority[49];  // Interrupt priority
} nvic_reg_store_t;
106

107
108
109
110
111
typedef struct {
    mp_obj_base_t base;
    mp_obj_t      obj;
    WakeUpCB_t    wakeup;
} pybsleep_obj_t;
112

113
typedef struct {
114
115
116
    mp_obj_t    wlan_lpds_wake_cb;
    mp_obj_t    timer_lpds_wake_cb;
    mp_obj_t    gpio_lpds_wake_cb;
117
    uint        timer_wake_pwrmode;
118
} pybsleep_data_t;
119
120
121
122
123
124

/******************************************************************************
 DECLARE PRIVATE DATA
 ******************************************************************************/
STATIC const mp_obj_type_t pybsleep_type;
STATIC nvic_reg_store_t    *nvic_reg_store;
125
STATIC pybsleep_data_t   pybsleep_data = {NULL, NULL, NULL, 0};
126
volatile arm_cm4_core_regs_t vault_arm_registers;
127
STATIC pybsleep_reset_cause_t pybsleep_reset_cause = PYB_SLP_PWRON_RESET;
128
STATIC pybsleep_wake_reason_t pybsleep_wake_reason = PYB_SLP_WAKED_PWRON;
129
130
131
132
133
134
135
136
137
138
139

/******************************************************************************
 DECLARE PRIVATE FUNCTIONS
 ******************************************************************************/
STATIC pybsleep_obj_t *pybsleep_find (mp_obj_t obj);
STATIC void pybsleep_flash_powerdown (void);
STATIC NORETURN void pybsleep_suspend_enter (void);
void pybsleep_suspend_exit (void);
STATIC void pybsleep_obj_wakeup (void);
STATIC void PRCMInterruptHandler (void);
STATIC void pybsleep_iopark (void);
140
141
STATIC bool setup_timer_lpds_wake (void);
STATIC bool setup_timer_hibernate_wake (void);
142
143
144
145

/******************************************************************************
 DEFINE PUBLIC FUNCTIONS
 ******************************************************************************/
146
147
__attribute__ ((section (".boot")))
void pybsleep_pre_init (void) {
148
149
    // allocate memory for nvic registers vault
    ASSERT ((nvic_reg_store = mem_Malloc(sizeof(nvic_reg_store_t))) != NULL);
150
151
152
153
154
}

void pybsleep_init0 (void) {
    // initialize the sleep objects list
    mp_obj_list_init(&MP_STATE_PORT(pybsleep_obj_list), 0);
155

156
    // register and enable the PRCM interrupt
157
    osi_InterruptRegister(INT_PRCM, (P_OSI_INTR_ENTRY)PRCMInterruptHandler, INT_PRIORITY_LVL_1);
158

159
160
161
    // disable all LPDS and hibernate wake up sources (WLAN is disabed/enabled before entering LDPS mode)
    MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_GPIO);
    MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_TIMER);
162
163
    MAP_PRCMHibernateWakeupSourceDisable(PRCM_HIB_SLOW_CLK_CTR | PRCM_HIB_GPIO2  | PRCM_HIB_GPIO4  | PRCM_HIB_GPIO13 |
                                         PRCM_HIB_GPIO17       | PRCM_HIB_GPIO11 | PRCM_HIB_GPIO24 | PRCM_HIB_GPIO26);
164

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    // store the reset casue (if it's soft reset, leave it as it is)
    if (pybsleep_reset_cause != PYB_SLP_SOFT_RESET) {
        switch (MAP_PRCMSysResetCauseGet()) {
        case PRCM_POWER_ON:
            pybsleep_reset_cause = PYB_SLP_PWRON_RESET;
            break;
        case PRCM_CORE_RESET:
        case PRCM_MCU_RESET:
        case PRCM_SOC_RESET:
            pybsleep_reset_cause = PYB_SLP_HARD_RESET;
            break;
        case PRCM_WDT_RESET:
            pybsleep_reset_cause = PYB_SLP_WDT_RESET;
            break;
        case PRCM_HIB_EXIT:
            if (PRCMWasResetBecauseOfWDT()) {
                pybsleep_reset_cause = PYB_SLP_WDT_RESET;
            }
            else {
                pybsleep_reset_cause = PYB_SLP_HIB_RESET;
185
186
187
188
189
190
191
192
193
194
195
                // set the correct wake reason
                switch (MAP_PRCMHibernateWakeupCauseGet()) {
                case PRCM_HIB_WAKEUP_CAUSE_SLOW_CLOCK:
                    pybsleep_wake_reason = PYB_SLP_WAKED_BY_RTC;
                    break;
                case PRCM_HIB_WAKEUP_CAUSE_GPIO:
                    pybsleep_wake_reason = PYB_SLP_WAKED_BY_GPIO;
                    break;
                default:
                    break;
                }
196
197
198
199
200
201
202
203
204
205
            }
            break;
        default:
            break;
        }
    }
}

void pybsleep_signal_soft_reset (void) {
    pybsleep_reset_cause = PYB_SLP_SOFT_RESET;
206
207
}

208
209
210
211
212
213
214
215
216
void pybsleep_add (const mp_obj_t obj, WakeUpCB_t wakeup) {
    pybsleep_obj_t * sleep_obj = m_new_obj(pybsleep_obj_t);
    sleep_obj->base.type = &pybsleep_type;
    sleep_obj->obj = obj;
    sleep_obj->wakeup = wakeup;
    // only add objects once
    if (!pybsleep_find(sleep_obj)) {
        mp_obj_list_append(&MP_STATE_PORT(pybsleep_obj_list), sleep_obj);
    }
217
218
}

219
220
221
222
223
void pybsleep_remove (const mp_obj_t obj) {
    pybsleep_obj_t *sleep_obj;
    if ((sleep_obj = pybsleep_find(obj))) {
        mp_obj_list_remove(&MP_STATE_PORT(pybsleep_obj_list), sleep_obj);
    }
224
225
}

226
void pybsleep_set_wlan_lpds_callback (mp_obj_t cb_obj) {
227
    pybsleep_data.wlan_lpds_wake_cb = cb_obj;
228
}
229

230
void pybsleep_set_gpio_lpds_callback (mp_obj_t cb_obj) {
231
    pybsleep_data.gpio_lpds_wake_cb = cb_obj;
232
}
233

234
void pybsleep_set_timer_lpds_callback (mp_obj_t cb_obj) {
235
    pybsleep_data.timer_lpds_wake_cb = cb_obj;
236
}
237

238
void pybsleep_configure_timer_wakeup (uint pwrmode) {
239
    pybsleep_data.timer_wake_pwrmode = pwrmode;
240
241
}

242
243
244
245
pybsleep_reset_cause_t pybsleep_get_reset_cause (void) {
    return pybsleep_reset_cause;
}

246
247
248
249
250
251
252
253
254
/******************************************************************************
 DEFINE PRIVATE FUNCTIONS
 ******************************************************************************/
STATIC pybsleep_obj_t *pybsleep_find (mp_obj_t obj) {
    for (mp_uint_t i = 0; i < MP_STATE_PORT(pybsleep_obj_list).len; i++) {
        // search for the object and then remove it
        pybsleep_obj_t *sleep_obj = ((pybsleep_obj_t *)(MP_STATE_PORT(pybsleep_obj_list).items[i]));
        if (sleep_obj->obj == obj) {
            return sleep_obj;
255
        }
256
257
    }
    return NULL;
258
259
}

260
STATIC void pybsleep_flash_powerdown (void) {
261
262
263
    uint32_t status;

    // Enable clock for SSPI module
264
    MAP_PRCMPeripheralClkEnable(PRCM_SSPI, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK);
265
266
    // Reset SSPI at PRCM level and wait for reset to complete
    MAP_PRCMPeripheralReset(PRCM_SSPI);
267
    while(!MAP_PRCMPeripheralStatusGet(PRCM_SSPI));
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286

    // Reset SSPI at module level
    MAP_SPIReset(SSPI_BASE);
    // Configure SSPI module
    MAP_SPIConfigSetExpClk (SSPI_BASE, PRCMPeripheralClockGet(PRCM_SSPI),
                            20000000, SPI_MODE_MASTER,SPI_SUB_MODE_0,
                            (SPI_SW_CTRL_CS   |
                             SPI_4PIN_MODE    |
                             SPI_TURBO_OFF    |
                             SPI_CS_ACTIVELOW |
                             SPI_WL_8));

    // Enable SSPI module
    MAP_SPIEnable(SSPI_BASE);
    // Enable chip select for the spi flash.
    MAP_SPICSEnable(SSPI_BASE);
    // Wait for the spi flash
    do {
        // Send the status register read instruction and read back a dummy byte.
287
        MAP_SPIDataPut(SSPI_BASE, SPIFLASH_INSTR_READ_STATUS);
288
289
290
291
292
        MAP_SPIDataGet(SSPI_BASE, &status);

        // Write a dummy byte then read back the actual status.
        MAP_SPIDataPut(SSPI_BASE, 0xFF);
        MAP_SPIDataGet(SSPI_BASE, &status);
293
    } while ((status & 0xFF) == SPIFLASH_STATUS_BUSY);
294
295
296
297
298
299

    // Disable chip select for the spi flash.
    MAP_SPICSDisable(SSPI_BASE);
    // Start another CS enable sequence for Power down command.
    MAP_SPICSEnable(SSPI_BASE);
    // Send Deep Power Down command to spi flash
300
    MAP_SPIDataPut(SSPI_BASE, SPIFLASH_INSTR_DEEP_POWER_DOWN);
301
302
303
304
    // Disable chip select for the spi flash.
    MAP_SPICSDisable(SSPI_BASE);
}

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
STATIC NORETURN void pybsleep_suspend_enter (void) {
    // enable full RAM retention
    MAP_PRCMSRAMRetentionEnable(PRCM_SRAM_COL_1 | PRCM_SRAM_COL_2 | PRCM_SRAM_COL_3 | PRCM_SRAM_COL_4, PRCM_SRAM_LPDS_RET);

    // save the NVIC control registers
    nvic_reg_store->vector_table = HWREG(NVIC_VTABLE);
    nvic_reg_store->aux_ctrl = HWREG(NVIC_ACTLR);
    nvic_reg_store->int_ctrl_state = HWREG(NVIC_INT_CTRL);
    nvic_reg_store->app_int = HWREG(NVIC_APINT);
    nvic_reg_store->sys_ctrl = HWREG(NVIC_SYS_CTRL);
    nvic_reg_store->config_ctrl = HWREG(NVIC_CFG_CTRL);
    nvic_reg_store->sys_pri_1 = HWREG(NVIC_SYS_PRI1);
    nvic_reg_store->sys_pri_2 = HWREG(NVIC_SYS_PRI2);
    nvic_reg_store->sys_pri_3 = HWREG(NVIC_SYS_PRI3);
    nvic_reg_store->sys_hcrs = HWREG(NVIC_SYS_HND_CTRL);

    // save the systick registers
    nvic_reg_store->systick_ctrl = HWREG(NVIC_ST_CTRL);
    nvic_reg_store->systick_reload = HWREG(NVIC_ST_RELOAD);
    nvic_reg_store->systick_calib = HWREG(NVIC_ST_CAL);

    // save the interrupt enable registers
    uint32_t *base_reg_addr = (uint32_t *)NVIC_EN0;
    for(int32_t i = 0; i < (sizeof(nvic_reg_store->int_en) / 4); i++) {
        nvic_reg_store->int_en[i] = base_reg_addr[i];
    }
331

332
333
334
335
336
    // save the interrupt priority registers
    base_reg_addr = (uint32_t *)NVIC_PRI0;
    for(int32_t i = 0; i < (sizeof(nvic_reg_store->int_priority) / 4); i++) {
        nvic_reg_store->int_priority[i] = base_reg_addr[i];
    }
337

338
339
340
    // switch off the heartbeat led (this makes sure it will blink as soon as we wake up)
    mperror_heartbeat_switch_off();

341
    // park the gpio pins
342
343
    pybsleep_iopark();

344
    // store the cpu registers
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
    sleep_store();

    // save the restore info and enter LPDS
    MAP_PRCMLPDSRestoreInfoSet(vault_arm_registers.psp, (uint32_t)sleep_restore);
    MAP_PRCMLPDSEnter();

    // let the cpu fade away...
    for ( ; ; );
}

void pybsleep_suspend_exit (void) {
    // take the I2C semaphore
    uint32_t reg = HWREG(COMMON_REG_BASE + COMMON_REG_O_I2C_Properties_Register);
    reg = (reg & ~0x3) | 0x1;
    HWREG(COMMON_REG_BASE + COMMON_REG_O_I2C_Properties_Register) = reg;

    // take the GPIO semaphore
    reg = HWREG(COMMON_REG_BASE + COMMON_REG_O_GPIO_properties_register);
    reg = (reg & ~0x3FF) | 0x155;
    HWREG(COMMON_REG_BASE + COMMON_REG_O_GPIO_properties_register) = reg;

    // restore de NVIC control registers
    HWREG(NVIC_VTABLE) = nvic_reg_store->vector_table;
    HWREG(NVIC_ACTLR) = nvic_reg_store->aux_ctrl;
    HWREG(NVIC_INT_CTRL) = nvic_reg_store->int_ctrl_state;
    HWREG(NVIC_APINT) = nvic_reg_store->app_int;
    HWREG(NVIC_SYS_CTRL) = nvic_reg_store->sys_ctrl;
    HWREG(NVIC_CFG_CTRL) = nvic_reg_store->config_ctrl;
    HWREG(NVIC_SYS_PRI1) = nvic_reg_store->sys_pri_1;
    HWREG(NVIC_SYS_PRI2) = nvic_reg_store->sys_pri_2;
    HWREG(NVIC_SYS_PRI3) = nvic_reg_store->sys_pri_3;
    HWREG(NVIC_SYS_HND_CTRL) = nvic_reg_store->sys_hcrs;

    // restore the systick register
    HWREG(NVIC_ST_CTRL) = nvic_reg_store->systick_ctrl;
    HWREG(NVIC_ST_RELOAD) = nvic_reg_store->systick_reload;
    HWREG(NVIC_ST_CAL) = nvic_reg_store->systick_calib;

    // restore the interrupt priority registers
    uint32_t *base_reg_addr = (uint32_t *)NVIC_PRI0;
    for (uint32_t i = 0; i < (sizeof(nvic_reg_store->int_priority) / 4); i++) {
        base_reg_addr[i] = nvic_reg_store->int_priority[i];
    }
388

389
390
391
392
393
    // restore the interrupt enable registers
    base_reg_addr = (uint32_t *)NVIC_EN0;
    for(uint32_t i = 0; i < (sizeof(nvic_reg_store->int_en) / 4); i++) {
        base_reg_addr[i] = nvic_reg_store->int_en[i];
    }
394

395
    HAL_INTRODUCE_SYNC_BARRIER();
396

397
398
    // ungate the clock to the shared spi bus
    MAP_PRCMPeripheralClkEnable(PRCM_SSPI, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK);
399

400
    // reinitialize simplelink's interface
401
    sl_IfOpen (NULL, 0);
402

403
404
    // restore the configuration of all active peripherals
    pybsleep_obj_wakeup();
405

406
407
408
    // reconfigure all the previously enabled interrupts
    mpcallback_wake_all();

409
410
    // trigger a sw interrupt
    MAP_IntPendSet(INT_PRCM);
411

412
413
    // force an exception to go back to the point where suspend mode was entered
    nlr_raise(mp_obj_new_exception(&mp_type_SystemExit));
414
415
}

416
417
418
STATIC void PRCMInterruptHandler (void) {
    // reading the interrupt status automatically clears the interrupt
    if (PRCM_INT_SLOW_CLK_CTR == MAP_PRCMIntStatus()) {
419
        // this interrupt is triggered during active mode
420
        mpcallback_handler(pybsleep_data.timer_lpds_wake_cb);
421
422
    }
    else {
423
        // interrupt has been triggered while waking up from LPDS
424
        switch (MAP_PRCMLPDSWakeupCauseGet()) {
425
        case PRCM_LPDS_HOST_IRQ:
426
            mpcallback_handler(pybsleep_data.wlan_lpds_wake_cb);
427
            pybsleep_wake_reason = PYB_SLP_WAKED_BY_WLAN;
428
            break;
429
        case PRCM_LPDS_GPIO:
430
            mpcallback_handler(pybsleep_data.gpio_lpds_wake_cb);
431
            pybsleep_wake_reason = PYB_SLP_WAKED_BY_GPIO;
432
            break;
433
        case PRCM_LPDS_TIMER:
434
            // disable the timer as wake-up source
435
            pybsleep_data.timer_wake_pwrmode &= ~PYB_PWR_MODE_LPDS;
436
            MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_TIMER);
437
            mpcallback_handler(pybsleep_data.timer_lpds_wake_cb);
438
            pybsleep_wake_reason = PYB_SLP_WAKED_BY_RTC;
439
440
441
            break;
        default:
            break;
442
        }
443
    }
444
445
}

446
447
448
449
450
STATIC void pybsleep_obj_wakeup (void) {
    for (mp_uint_t i = 0; i < MP_STATE_PORT(pybsleep_obj_list).len; i++) {
        pybsleep_obj_t *sleep_obj = ((pybsleep_obj_t *)MP_STATE_PORT(pybsleep_obj_list).items[i]);
        sleep_obj->wakeup(sleep_obj->obj);
    }
451
452
}

453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
STATIC void pybsleep_iopark (void) {
    mp_map_t *named_map = mp_obj_dict_get_map((mp_obj_t)&pin_cpu_pins_locals_dict);
    for (uint i = 0; i < named_map->used; i++) {
        pin_obj_t * pin = (pin_obj_t *)named_map->table[i].value;
        // skip the sflash pins since these are shared with the network processor
        switch (pin->pin_num) {
        case PIN_11:
        case PIN_12:
        case PIN_13:
        case PIN_14:
#ifdef DEBUG
        // also skip the JTAG pins
        case PIN_16:
        case PIN_17:
        case PIN_19:
        case PIN_20:
#endif
            break;
        default:
472
473
            // enable a weak pull-down if the pin is unused
            if (!pin->isused) {
474
475
                MAP_PinConfigSet(pin->pin_num, pin->strength, PIN_TYPE_STD_PD);
            }
476
            // make it an input
477
478
            MAP_PinDirModeSet(pin->pin_num, PIN_DIR_MODE_IN);
            break;
479
        }
480
    }
481

482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
    // park the sflash pins
    HWREG(0x4402E0E8) &= ~(0x3 << 8);
    HWREG(0x4402E0E8) |= (0x2 << 8);
    HWREG(0x4402E0EC) &= ~(0x3 << 8);
    HWREG(0x4402E0EC) |= (0x2 << 8);
    HWREG(0x4402E0F0) &= ~(0x3 << 8);
    HWREG(0x4402E0F0) |= (0x2 << 8);
    HWREG(0x4402E0F4) &= ~(0x3 << 8);
    HWREG(0x4402E0F4) |= (0x1 << 8);

    // park the antenna selection pins
    HWREG(0x4402E108) = 0x00000E61;
    HWREG(0x4402E10C) = 0x00000E61;
}

497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
STATIC bool setup_timer_lpds_wake (void) {
    uint64_t t_match, t_curr, t_remaining;

    // get the time remaining for the RTC timer to expire
    t_match = MAP_PRCMSlowClkCtrMatchGet();
    t_curr  = MAP_PRCMSlowClkCtrGet();

    if (t_match > t_curr) {
        // get the time remaining in terms of slow clocks
        t_remaining = (t_match - t_curr);
        if (t_remaining > WAKEUP_TIME_LPDS) {
            // subtract the time it takes for wakeup from lpds
            t_remaining -= WAKEUP_TIME_LPDS;
            t_remaining = (t_remaining > 0xFFFFFFFF) ? 0xFFFFFFFF: t_remaining;
            // setup the LPDS wake time
            MAP_PRCMLPDSIntervalSet((uint32_t)t_remaining);
            // enable the wake source
            MAP_PRCMLPDSWakeupSourceEnable(PRCM_LPDS_TIMER);
            return true;
        }
    }
    else {
        // setup a timer interrupt immediately
        MAP_PRCMRTCMatchSet(0, FORCED_TIMER_INTERRUPT_MS);
    }

    // disable the timer as wake source
    MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_TIMER);

    // LPDS wake by timer was not possible, force
    // an interrupt in active mode instead
    MAP_PRCMIntEnable(PRCM_INT_SLOW_CLK_CTR);

    return false;
}

STATIC bool setup_timer_hibernate_wake (void) {
    uint64_t t_match, t_curr, t_remaining;

    // get the time remaining for the RTC timer to expire
    t_match = MAP_PRCMSlowClkCtrMatchGet();
    t_curr  = MAP_PRCMSlowClkCtrGet();

    if (t_match > t_curr) {
        // get the time remaining in terms of slow clocks
        t_remaining = (t_match - t_curr);
        if (t_remaining > WAKEUP_TIME_HIB) {
            // subtract the time it takes for wakeup from hibernate
            t_remaining -= WAKEUP_TIME_HIB;
            // setup the LPDS wake time
            MAP_PRCMHibernateIntervalSet((uint32_t)t_remaining);
            // enable the wake source
            MAP_PRCMHibernateWakeupSourceEnable(PRCM_HIB_SLOW_CLK_CTR);
            return true;
        }
    }
    else {
        // setup a timer interrupt immediately
        MAP_PRCMRTCMatchSet(0, FORCED_TIMER_INTERRUPT_MS);
    }

    // disable the timer as wake source
    MAP_PRCMLPDSWakeupSourceDisable(PRCM_HIB_SLOW_CLK_CTR);

    // hibernate wake by timer was not possible, force
    // an interrupt in active mode instead
    MAP_PRCMIntEnable(PRCM_INT_SLOW_CLK_CTR);

    return false;
}

568
569
570
571
572
573
574
575
576
577
578
/******************************************************************************/
// Micro Python bindings; Sleep class

/// \function idle()
/// Gates the processor clock until an interrupt is triggered
STATIC mp_obj_t pyb_sleep_idle (mp_obj_t self_in) {
    __WFI();
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_sleep_idle_obj, pyb_sleep_idle);

579
/// \function suspend(wlan)
580
/// Enters suspended mode. Wake up sources should have been enable prior to
581
/// calling this method.
582
583
STATIC mp_obj_t pyb_sleep_suspend (mp_obj_t self_in) {
    nlr_buf_t nlr;
584

585
    // check if we should enable timer wake-up
586
    if (pybsleep_data.timer_wake_pwrmode & PYB_PWR_MODE_LPDS) {
587
588
        if (!setup_timer_lpds_wake()) {
            // lpds entering is not possible, wait for the forced interrupt and return
589
            pybsleep_data.timer_wake_pwrmode &= ~PYB_PWR_MODE_LPDS;
590
591
592
593
594
            HAL_Delay (FAILED_SLEEP_DELAY_MS);
            return mp_const_none;
        }
    }

595
596
    // do we need network wake-up?
    if (pybsleep_data.wlan_lpds_wake_cb) {
597
        MAP_PRCMLPDSWakeupSourceEnable (PRCM_LPDS_HOST_IRQ);
598
        server_sleep_sockets();
599
600
601
602
    }
    else {
        MAP_PRCMLPDSWakeupSourceDisable (PRCM_LPDS_HOST_IRQ);
    }
603

604
    // entering and exiting suspended mode must be an atomic operation
605
    // therefore interrupts need to be disabled
606
607
608
609
610
    uint primsk = disable_irq();
    if (nlr_push(&nlr) == 0) {
        pybsleep_suspend_enter();
        nlr_pop();
    }
611

612
613
    // an exception is always raised when exiting suspend mode
    enable_irq(primsk);
614

615
    return mp_const_none;
616
}
617
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_sleep_suspend_obj, pyb_sleep_suspend);
618

619
620
/// \function hibernate()
/// Enters hibernate mode. Wake up sources should have been enable prior to
621
/// calling this method.
622
STATIC mp_obj_t pyb_sleep_hibernate (mp_obj_t self_in) {
623
    // check if we should enable timer wake-up
624
    if (pybsleep_data.timer_wake_pwrmode & PYB_PWR_MODE_HIBERNATE) {
625
626
        if (!setup_timer_hibernate_wake()) {
            // hibernating is not possible, wait for the forced interrupt and return
627
            pybsleep_data.timer_wake_pwrmode &= ~PYB_PWR_MODE_HIBERNATE;
628
629
630
631
            HAL_Delay (FAILED_SLEEP_DELAY_MS);
            return mp_const_none;
        }
    }
632
    wlan_stop(SL_STOP_TIMEOUT);
633
    pybsleep_flash_powerdown();
634
635
    // must be done just before entering hibernate mode
    pybsleep_iopark();
636
637
    MAP_PRCMHibernateEnter();
    return mp_const_none;
638
}
639
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_sleep_hibernate_obj, pyb_sleep_hibernate);
640

641
642
643
644
645
646
647
648
649
650
/// \function reset_cause()
/// Returns the last reset casue
STATIC mp_obj_t pyb_sleep_reset_cause (mp_obj_t self_in) {
    return MP_OBJ_NEW_SMALL_INT(pybsleep_reset_cause);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_sleep_reset_cause_obj, pyb_sleep_reset_cause);

/// \function wake_reason()
/// Returns the wake up reson from ldps or hibernate
STATIC mp_obj_t pyb_sleep_wake_reason (mp_obj_t self_in) {
651
    return MP_OBJ_NEW_SMALL_INT(pybsleep_wake_reason);
652
653
654
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_sleep_wake_reason_obj, pyb_sleep_wake_reason);

655
656
657
658
659
STATIC const mp_map_elem_t pybsleep_locals_dict_table[] = {
    // instance methods
    { MP_OBJ_NEW_QSTR(MP_QSTR_idle),                    (mp_obj_t)&pyb_sleep_idle_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_suspend),                 (mp_obj_t)&pyb_sleep_suspend_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_hibernate),               (mp_obj_t)&pyb_sleep_hibernate_obj },
660
661
    { MP_OBJ_NEW_QSTR(MP_QSTR_reset_cause),             (mp_obj_t)&pyb_sleep_reset_cause_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_wake_reason),             (mp_obj_t)&pyb_sleep_wake_reason_obj },
662

663
    // class constants
664
    { MP_OBJ_NEW_QSTR(MP_QSTR_ACTIVE),                  MP_OBJ_NEW_SMALL_INT(PYB_PWR_MODE_ACTIVE) },
665
666
    { MP_OBJ_NEW_QSTR(MP_QSTR_SUSPENDED),               MP_OBJ_NEW_SMALL_INT(PYB_PWR_MODE_LPDS) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_HIBERNATING),             MP_OBJ_NEW_SMALL_INT(PYB_PWR_MODE_HIBERNATE) },
667
    { MP_OBJ_NEW_QSTR(MP_QSTR_POWER_ON),                MP_OBJ_NEW_SMALL_INT(PYB_SLP_PWRON_RESET) },
668
669
670
671
672
    { MP_OBJ_NEW_QSTR(MP_QSTR_HARD_RESET),              MP_OBJ_NEW_SMALL_INT(PYB_SLP_HARD_RESET) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_WDT_RESET),               MP_OBJ_NEW_SMALL_INT(PYB_SLP_WDT_RESET) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_HIB_RESET),               MP_OBJ_NEW_SMALL_INT(PYB_SLP_HIB_RESET) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_SOFT_RESET),              MP_OBJ_NEW_SMALL_INT(PYB_SLP_SOFT_RESET) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_WLAN_WAKE),               MP_OBJ_NEW_SMALL_INT(PYB_SLP_WAKED_BY_WLAN) },
673
    { MP_OBJ_NEW_QSTR(MP_QSTR_PIN_WAKE),                MP_OBJ_NEW_SMALL_INT(PYB_SLP_WAKED_BY_GPIO) },
674
    { MP_OBJ_NEW_QSTR(MP_QSTR_RTC_WAKE),                MP_OBJ_NEW_SMALL_INT(PYB_SLP_WAKED_BY_RTC) },
675
};
676

677
STATIC MP_DEFINE_CONST_DICT(pybsleep_locals_dict, pybsleep_locals_dict_table);
678

679
680
STATIC const mp_obj_type_t pybsleep_type = {
    { &mp_type_type },
681
    .name = MP_QSTR_Sleep,
682
683
    .locals_dict = (mp_obj_t)&pybsleep_locals_dict,
};
684

685
const mp_obj_base_t pyb_sleep_obj = {&pybsleep_type};