Code: Select all
#include <stdio.h>
#include "mpconfig.h"
#include "nlr.h"
#include "misc.h"
#include "qstr.h"
#include "obj.h"
#include "runtime.h"
#define RAISE_EXCEP(assertion, type, msg) { if ((assertion) == 0) nlr_raise(mp_obj_new_exception_msg(&(type), (msg))); }
STATIC int someFunc(int x)
{
int rc = x;
if (rc == 0) {
printf("rc == 0\n");
} else {
printf("rc != 0 (%d)\n", rc);
}
return rc;
}
STATIC mp_obj_t dh_test(mp_obj_t x) {
int status = someFunc(mp_obj_get_int(x));
RAISE_EXCEP(status>=0, mp_type_IndexError, "read failed");
RAISE_EXCEP(status==0, mp_type_IOError, "no data");
printf("status = %d\n", status);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(dh_test_obj, dh_test);
STATIC const mp_map_elem_t dh_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_dh) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_test), (mp_obj_t)&dh_test_obj },
};
STATIC const mp_obj_dict_t dh_module_globals = {
.base = {&mp_type_dict},
.map = {
.all_keys_are_qstrs = 1,
.table_is_fixed_array = 1,
.used = MP_ARRAY_SIZE(dh_module_globals_table),
.alloc = MP_ARRAY_SIZE(dh_module_globals_table),
.table = (mp_map_elem_t*)dh_module_globals_table,
},
};
const mp_obj_module_t dh_module = {
.base = { &mp_type_module },
.name = MP_QSTR_dh,
.globals = (mp_obj_dict_t*)&dh_module_globals,
};
Code: Select all
import dh
i = 1
while True:
print("i =", i)
rc = i
i -= 1
try:
dh.test(rc)
except IOError:
print('IOError: no data error in read')
continue
except:
# some error occurred, we may need to restart the connection
print('error in read')
break
Code: Select all
{ MP_OBJ_NEW_QSTR(MP_QSTR_dh), (mp_obj_t)&dh_module }, \
Added:
Code: Select all
Q(dh)
Q(test)
Added dh.c into stmhal/Makefile.
I get the following results:
Code: Select all
>>> import dhtest
i = 1
rc != 0 (1)
IOError: no data error in read
i = 0
rc == 0
status = 0
i = -1
rc != 0 (-1)
error in read
You didn't include your definitions of ReadError and NoDataError, so I used IndexError and IOError in their place.
Can you provide your definitions of mp_type_ReadError and mp_type_NoDataError?