From 2b725986178b28504c7cc5365667ec4c44618da9 Mon Sep 17 00:00:00 2001
From: Rahix <rahix@rahix.de>
Date: Fri, 16 Oct 2020 21:43:20 +0200
Subject: [PATCH] feat(pycardium): Always reload pycardium before going to REPL

Remove the big endless loop from pycardium main and instead use
epic_exec("") to switch to REPL.  This way, any MicroPython state is
reset and also all hardware will be in a clean reinitialized state.

This also means that pycard10.py will now run scripts in a clean
environment that is not tainted by whatever was running before.

Fixes #212.

Signed-off-by: Rahix <rahix@rahix.de>
---
 pycardium/main.c | 65 +++++++++++++++++++++++-------------------------
 1 file changed, 31 insertions(+), 34 deletions(-)

diff --git a/pycardium/main.c b/pycardium/main.c
index 2943b1265..7aa126186 100644
--- a/pycardium/main.c
+++ b/pycardium/main.c
@@ -50,44 +50,41 @@ int main(void)
 	mp_stack_set_top(&__StackTop);
 	mp_stack_set_limit((mp_int_t)&__StackLimit);
 
-	while (1) {
-		gc_init(&__HeapBase + 1024 * 10, &__HeapLimit);
-
-		mp_init();
-
-		readline_init0();
-		interrupt_init0();
-
-		/* request by badge.team */
-		mp_obj_list_init(mp_sys_path, 0);
-		mp_obj_list_append(mp_sys_path, MP_ROM_QSTR(MP_QSTR_));
-		mp_obj_list_append(
-			mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_lib)
-		);
-		mp_obj_list_append(
-			mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_apps)
-		);
-
-		if (cnt > 0) {
-			pyexec_file_if_exists(script_name);
-		}
+	gc_init(&__HeapBase + 1024 * 10, &__HeapLimit);
+
+	mp_init();
+
+	readline_init0();
+	interrupt_init0();
+
+	/* request by badge.team */
+	mp_obj_list_init(mp_sys_path, 0);
+	mp_obj_list_append(mp_sys_path, MP_ROM_QSTR(MP_QSTR_));
+	mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_lib));
+	mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_apps));
+
+	if (cnt > 0) {
+		pyexec_file_if_exists(script_name);
 
-		epic_uart_write_str(header, sizeof(header));
-
-		for (;;) {
-			if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
-				if (pyexec_raw_repl() != 0) {
-					break;
-				}
-			} else {
-				if (pyexec_friendly_repl() != 0) {
-					break;
-				}
+		/* Drop to REPL by reloading Pycardium */
+		epic_exec("");
+	}
+
+	for (;;) {
+		if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
+			if (pyexec_raw_repl() != 0) {
+				break;
+			}
+		} else {
+			if (pyexec_friendly_repl() != 0) {
+				break;
 			}
 		}
-
-		mp_deinit();
 	}
+
+	mp_deinit();
+
+	epic_exit(0);
 }
 
 void HardFault_Handler(void)
-- 
GitLab