88#include <string.h>
99
1010#include <pbdrv/bluetooth.h>
11+ #include <pbsys/program_load.h>
1112
1213#include "py/obj.h"
14+ #include "py/objstr.h"
1315#include "py/runtime.h"
1416
1517#include <pybricks/common.h>
1618#include <pybricks/util_pb/pb_error.h>
19+ #include <pybricks/util_mp/pb_kwarg_helper.h>
20+ #include <pybricks/util_mp/pb_obj_helper.h>
1721
1822STATIC mp_obj_t pb_type_System_name (void ) {
1923 const char * hub_name = pbdrv_bluetooth_get_hub_name ();
@@ -101,6 +105,34 @@ STATIC mp_obj_t pb_type_System_shutdown(void) {
101105}
102106STATIC MP_DEFINE_CONST_FUN_OBJ_0 (pb_type_System_shutdown_obj , pb_type_System_shutdown );
103107
108+ STATIC mp_obj_t pb_type_System_storage (size_t n_args , const mp_obj_t * pos_args , mp_map_t * kw_args ) {
109+ PB_PARSE_ARGS_FUNCTION (n_args , pos_args , kw_args ,
110+ PB_ARG_REQUIRED (offset ),
111+ PB_ARG_DEFAULT_NONE (read ),
112+ PB_ARG_DEFAULT_NONE (write ));
113+
114+ // Get offset and confirm integer type.
115+ mp_int_t offset = mp_obj_get_int (offset_in );
116+
117+ // Handle read.
118+ if (write_in == mp_const_none ) {
119+ byte * data ;
120+ mp_uint_t size = mp_obj_get_int (read_in );
121+ pb_assert (pbsys_program_load_get_user_data (offset , & data , size ));
122+ return mp_obj_new_bytes (data , size );
123+ }
124+
125+ // Handle write.
126+ if (read_in == mp_const_none && !mp_obj_is_str (write_in ) && mp_obj_is_str_or_bytes (write_in )) {
127+ mp_obj_str_t * obj = ((mp_obj_str_t * )MP_OBJ_TO_PTR (write_in ));
128+ pbsys_program_load_set_user_data (offset , obj -> data , obj -> len );
129+ return mp_const_none ;
130+ }
131+
132+ mp_raise_ValueError (MP_ERROR_TEXT ("Must set either read (int) or write (bytes)." ));
133+ }
134+ STATIC MP_DEFINE_CONST_FUN_OBJ_KW (pb_type_System_storage_obj , 0 , pb_type_System_storage );
135+
104136#endif // PBIO_CONFIG_ENABLE_SYS
105137
106138// dir(pybricks.common.System)
@@ -113,6 +145,7 @@ STATIC const mp_rom_map_elem_t common_System_locals_dict_table[] = {
113145 #if PBIO_CONFIG_ENABLE_SYS
114146 { MP_ROM_QSTR (MP_QSTR_set_stop_button ), MP_ROM_PTR (& pb_type_System_set_stop_button_obj ) },
115147 { MP_ROM_QSTR (MP_QSTR_shutdown ), MP_ROM_PTR (& pb_type_System_shutdown_obj ) },
148+ { MP_ROM_QSTR (MP_QSTR_storage ), MP_ROM_PTR (& pb_type_System_storage_obj ) },
116149 #endif
117150};
118151STATIC MP_DEFINE_CONST_DICT (common_System_locals_dict , common_System_locals_dict_table );
0 commit comments