From 1b7d67266df7dd0853698726e98d63b4aeebe205 Mon Sep 17 00:00:00 2001
From: Damien George <damien.p.george@gmail.com>
Date: Wed, 15 Feb 2017 17:45:36 +1100
Subject: [PATCH] esp8266: Enable micropython.schedule() with locking in pin
 callback.

---
 esp8266/esp8266_common.ld | 1 +
 esp8266/esp_mphal.c       | 7 ++-----
 esp8266/machine_pin.c     | 2 ++
 esp8266/mpconfigport.h    | 1 +
 4 files changed, 6 insertions(+), 5 deletions(-)

diff --git a/esp8266/esp8266_common.ld b/esp8266/esp8266_common.ld
index f721c28b0..1da835681 100644
--- a/esp8266/esp8266_common.ld
+++ b/esp8266/esp8266_common.ld
@@ -100,6 +100,7 @@ SECTIONS
         *py/qstr.o*(.literal* .text*)
         *py/repl.o*(.literal* .text*)
         *py/runtime.o*(.literal* .text*)
+        *py/scheduler.o*(.literal* .text*)
         *py/scope.o*(.literal* .text*)
         *py/sequence.o*(.literal* .text*)
         *py/showbc.o*(.literal* .text*)
diff --git a/esp8266/esp_mphal.c b/esp8266/esp_mphal.c
index f5e284fde..7ecc7776a 100644
--- a/esp8266/esp_mphal.c
+++ b/esp8266/esp_mphal.c
@@ -33,6 +33,7 @@
 #include "ets_alt_task.h"
 #include "py/obj.h"
 #include "py/mpstate.h"
+#include "py/runtime.h"
 #include "extmod/misc.h"
 #include "lib/utils/pyexec.h"
 
@@ -130,11 +131,7 @@ void mp_hal_delay_ms(uint32_t delay) {
 
 void ets_event_poll(void) {
     ets_loop_iter();
-    if (MP_STATE_VM(mp_pending_exception) != NULL) {
-        mp_obj_t obj = MP_STATE_VM(mp_pending_exception);
-        MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
-        nlr_raise(obj);
-    }
+    mp_handle_pending();
 }
 
 void __assert_func(const char *file, int line, const char *func, const char *expr) {
diff --git a/esp8266/machine_pin.c b/esp8266/machine_pin.c
index a1e94e898..9ea5197bc 100644
--- a/esp8266/machine_pin.c
+++ b/esp8266/machine_pin.c
@@ -100,6 +100,7 @@ void pin_init0(void) {
 }
 
 void pin_intr_handler(uint32_t status) {
+    mp_sched_lock();
     gc_lock();
     status &= 0xffff;
     for (int p = 0; status; ++p, status >>= 1) {
@@ -111,6 +112,7 @@ void pin_intr_handler(uint32_t status) {
         }
     }
     gc_unlock();
+    mp_sched_unlock();
 }
 
 pyb_pin_obj_t *mp_obj_get_pin_obj(mp_obj_t pin_in) {
diff --git a/esp8266/mpconfigport.h b/esp8266/mpconfigport.h
index cf4cbecd4..07bd48f67 100644
--- a/esp8266/mpconfigport.h
+++ b/esp8266/mpconfigport.h
@@ -28,6 +28,7 @@
 #define MICROPY_MODULE_WEAK_LINKS   (1)
 #define MICROPY_CAN_OVERRIDE_BUILTINS (1)
 #define MICROPY_USE_INTERNAL_ERRNO  (1)
+#define MICROPY_ENABLE_SCHEDULER    (1)
 #define MICROPY_PY_ALL_SPECIAL_METHODS (1)
 #define MICROPY_PY_BUILTINS_COMPLEX (0)
 #define MICROPY_PY_BUILTINS_STR_UNICODE (1)
-- 
GitLab