1 /*
2  * This file is part of the MicroPython project, http://micropython.org/
3  *
4  * The MIT License (MIT)
5  *
6  * Copyright (c) 2020-2021 Damien P. George
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a copy
9  * of this software and associated documentation files (the "Software"), to deal
10  * in the Software without restriction, including without limitation the rights
11  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12  * copies of the Software, and to permit persons to whom the Software is
13  * furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24  * THE SOFTWARE.
25  */
26 
27 #include <stdio.h>
28 
29 #include "py/compile.h"
30 #include "py/runtime.h"
31 #include "py/gc.h"
32 #include "py/mperrno.h"
33 #include "py/mphal.h"
34 #include "py/stackctrl.h"
35 #include "shared/readline/readline.h"
36 #include "shared/runtime/gchelper.h"
37 #include "shared/runtime/pyexec.h"
38 #include "tusb.h"
39 #include "uart.h"
40 #include "modmachine.h"
41 #include "modrp2.h"
42 #include "genhdr/mpversion.h"
43 
44 #include "pico/stdlib.h"
45 #include "pico/binary_info.h"
46 #include "hardware/rtc.h"
47 #include "hardware/structs/rosc.h"
48 
49 extern uint8_t __StackTop, __StackBottom;
50 static char gc_heap[192 * 1024];
51 
52 // Embed version info in the binary in machine readable form
53 bi_decl(bi_program_version_string(MICROPY_GIT_TAG));
54 
55 // Add a section to the picotool output similar to program features, but for frozen modules
56 // (it will aggregate BINARY_INFO_ID_MP_FROZEN binary info)
57 bi_decl(bi_program_feature_group_with_flags(BINARY_INFO_TAG_MICROPYTHON,
58     BINARY_INFO_ID_MP_FROZEN, "frozen modules",
59     BI_NAMED_GROUP_SEPARATE_COMMAS | BI_NAMED_GROUP_SORT_ALPHA));
60 
main(int argc,char ** argv)61 int main(int argc, char **argv) {
62     #if MICROPY_HW_ENABLE_UART_REPL
63     bi_decl(bi_program_feature("UART REPL"))
64     setup_default_uart();
65     mp_uart_init();
66     #endif
67 
68     #if MICROPY_HW_ENABLE_USBDEV
69     bi_decl(bi_program_feature("USB REPL"))
70     tusb_init();
71     #endif
72 
73     #if MICROPY_PY_THREAD
74     bi_decl(bi_program_feature("thread support"))
75     mp_thread_init();
76     #endif
77 
78     // Start and initialise the RTC
79     datetime_t t = {
80         .year = 2021,
81         .month = 1,
82         .day = 1,
83         .dotw = 4, // 0 is Monday, so 4 is Friday
84         .hour = 0,
85         .min = 0,
86         .sec = 0,
87     };
88     rtc_init();
89     rtc_set_datetime(&t);
90 
91     // Initialise stack extents and GC heap.
92     mp_stack_set_top(&__StackTop);
93     mp_stack_set_limit(&__StackTop - &__StackBottom - 256);
94     gc_init(&gc_heap[0], &gc_heap[MP_ARRAY_SIZE(gc_heap)]);
95 
96     for (;;) {
97 
98         // Initialise MicroPython runtime.
99         mp_init();
100         mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_path), 0);
101         mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_));
102         mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_lib));
103         mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0);
104 
105         // Initialise sub-systems.
106         readline_init0();
107         machine_pin_init();
108         rp2_pio_init();
109 
110         // Execute _boot.py to set up the filesystem.
111         pyexec_frozen_module("_boot.py");
112 
113         // Execute user scripts.
114         int ret = pyexec_file_if_exists("boot.py");
115         if (ret & PYEXEC_FORCED_EXIT) {
116             goto soft_reset_exit;
117         }
118         if (pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) {
119             ret = pyexec_file_if_exists("main.py");
120             if (ret & PYEXEC_FORCED_EXIT) {
121                 goto soft_reset_exit;
122             }
123         }
124 
125         for (;;) {
126             if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
127                 if (pyexec_raw_repl() != 0) {
128                     break;
129                 }
130             } else {
131                 if (pyexec_friendly_repl() != 0) {
132                     break;
133                 }
134             }
135         }
136 
137     soft_reset_exit:
138         mp_printf(MP_PYTHON_PRINTER, "MPY: soft reboot\n");
139         rp2_pio_deinit();
140         machine_pin_deinit();
141         #if MICROPY_PY_THREAD
142         mp_thread_deinit();
143         #endif
144         gc_sweep_all();
145         mp_deinit();
146     }
147 
148     return 0;
149 }
150 
gc_collect(void)151 void gc_collect(void) {
152     gc_collect_start();
153     gc_helper_collect_regs_and_stack();
154     #if MICROPY_PY_THREAD
155     mp_thread_gc_others();
156     #endif
157     gc_collect_end();
158 }
159 
nlr_jump_fail(void * val)160 void nlr_jump_fail(void *val) {
161     printf("FATAL: uncaught exception %p\n", val);
162     mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(val));
163     for (;;) {
164         __breakpoint();
165     }
166 }
167 
168 #ifndef NDEBUG
__assert_func(const char * file,int line,const char * func,const char * expr)169 void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) {
170     printf("Assertion '%s' failed, at file %s:%d\n", expr, file, line);
171     panic("Assertion failed");
172 }
173 #endif
174 
175 #define POLY (0xD5)
176 
rosc_random_u8(size_t cycles)177 uint8_t rosc_random_u8(size_t cycles) {
178     static uint8_t r;
179     for (size_t i = 0; i < cycles; ++i) {
180         r = ((r << 1) | rosc_hw->randombit) ^ (r & 0x80 ? POLY : 0);
181         mp_hal_delay_us_fast(1);
182     }
183     return r;
184 }
185 
rosc_random_u32(void)186 uint32_t rosc_random_u32(void) {
187     uint32_t value = 0;
188     for (size_t i = 0; i < 4; ++i) {
189         value = value << 8 | rosc_random_u8(32);
190     }
191     return value;
192 }
193 
194 const char rp2_help_text[] =
195     "Welcome to MicroPython!\n"
196     "\n"
197     "For online help please visit https://micropython.org/help/.\n"
198     "\n"
199     "For access to the hardware use the 'machine' module.  RP2 specific commands\n"
200     "are in the 'rp2' module.\n"
201     "\n"
202     "Quick overview of some objects:\n"
203     "  machine.Pin(pin) -- get a pin, eg machine.Pin(0)\n"
204     "  machine.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n"
205     "    methods: init(..), value([v]), high(), low(), irq(handler)\n"
206     "  machine.ADC(pin) -- make an analog object from a pin\n"
207     "    methods: read_u16()\n"
208     "  machine.PWM(pin) -- make a PWM object from a pin\n"
209     "    methods: deinit(), freq([f]), duty_u16([d]), duty_ns([d])\n"
210     "  machine.I2C(id) -- create an I2C object (id=0,1)\n"
211     "    methods: readfrom(addr, buf, stop=True), writeto(addr, buf, stop=True)\n"
212     "             readfrom_mem(addr, memaddr, arg), writeto_mem(addr, memaddr, arg)\n"
213     "  machine.SPI(id, baudrate=1000000) -- create an SPI object (id=0,1)\n"
214     "    methods: read(nbytes, write=0x00), write(buf), write_readinto(wr_buf, rd_buf)\n"
215     "  machine.Timer(freq, callback) -- create a software timer object\n"
216     "    eg: machine.Timer(freq=1, callback=lambda t:print(t))\n"
217     "\n"
218     "Pins are numbered 0-29, and 26-29 have ADC capabilities\n"
219     "Pin IO modes are: Pin.IN, Pin.OUT, Pin.ALT\n"
220     "Pin pull modes are: Pin.PULL_UP, Pin.PULL_DOWN\n"
221     "\n"
222     "Useful control commands:\n"
223     "  CTRL-C -- interrupt a running program\n"
224     "  CTRL-D -- on a blank line, do a soft reset of the board\n"
225     "  CTRL-E -- on a blank line, enter paste mode\n"
226     "\n"
227     "For further help on a specific object, type help(obj)\n"
228     "For a list of available modules, type help('modules')\n"
229 ;
230