@@ -20,6 +20,7 @@ typedef struct _pyb_file_obj_t {
20
20
vfs_lfs_struct_t * littlefs ;
21
21
struct lfs_file_config cfg ; // Attributes of the file, e.g.: timestamp
22
22
bool timestamp_update ; // For requesting timestamp update when closing the file
23
+ bool opened ; // Indicate whether the file is opened
23
24
} pyb_file_obj_t ;
24
25
25
26
STATIC void file_obj_print (const mp_print_t * print , mp_obj_t self_in , mp_print_kind_t kind ) {
@@ -100,7 +101,8 @@ STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg,
100
101
return 0 ;
101
102
102
103
} else if (request == MP_STREAM_CLOSE ) {
103
- if (self -> littlefs == NULL ) {
104
+ // This check is needed here because calling close() twice makes LFS crash in lfs_file_close()
105
+ if (self -> opened == false) {
104
106
return 0 ;
105
107
}
106
108
@@ -112,7 +114,7 @@ STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg,
112
114
* errcode = littleFsErrorToErrno (res );
113
115
return MP_STREAM_ERROR ;
114
116
}
115
- self -> littlefs = NULL ; // indicate a closed file
117
+ self -> opened = false ; // indicate a closed file
116
118
return 0 ;
117
119
} else {
118
120
* errcode = MP_EINVAL ;
@@ -167,6 +169,7 @@ STATIC mp_obj_t file_open(fs_user_mount_t *vfs, const mp_obj_type_t *type, mp_ar
167
169
pyb_file_obj_t * o = m_new_obj_with_finaliser (pyb_file_obj_t );
168
170
o -> base .type = type ;
169
171
o -> timestamp_update = false;
172
+ o -> opened = false;
170
173
171
174
xSemaphoreTake (vfs -> fs .littlefs .mutex , portMAX_DELAY );
172
175
const char * fname = concat_with_cwd (& vfs -> fs .littlefs , mp_obj_str_get_str (args [0 ].u_obj ));
@@ -180,6 +183,7 @@ STATIC mp_obj_t file_open(fs_user_mount_t *vfs, const mp_obj_type_t *type, mp_ar
180
183
}
181
184
182
185
o -> littlefs = & vfs -> fs .littlefs ;
186
+ o -> opened = true; // File is opened successfully
183
187
184
188
return MP_OBJ_FROM_PTR (o );
185
189
}
0 commit comments