code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
#ifndef _BT_HOST_ADAPTER_H_ #define _BT_HOST_ADAPTER_H_ typedef struct { char *dev_name; uint16_t conn_num_max; }amp_bt_host_adapter_init_t; typedef struct { int32_t type; char *adv_data; char *scan_rsp_data; int32_t interval_min; int32_t interval_max; int32_t channel_map; }amp_bt_host_adapter_adv_start_t; typedef struct { int32_t type; uint16_t interval; uint16_t window; }amp_bt_host_adapter_scan_start_t; typedef struct { char *char_uuid; char *permission; char *descr_uuid; char *descr_type; }amp_bt_host_adapter_gatt_chars_t; typedef struct { char *s_uuid; uint32_t attr_cnt; amp_bt_host_adapter_gatt_chars_t *chars; }amp_bt_host_adapter_gatts_srvc_t; typedef struct { size_t len; uint8_t *data; } amp_bt_gatts_adapter_usr_data_t; //GAP int bt_host_adapter_init(amp_bt_host_adapter_init_t *init); int bt_host_adapter_start_adv(amp_bt_host_adapter_adv_start_t *adv_param); int bt_host_adapter_stop_adv(void); int bt_host_adapter_start_scan(amp_bt_host_adapter_scan_start_t *scan_param); int bt_host_adapter_stop_scan(void); void native_bt_host_conn_handle(int32_t conn_handle, int32_t connect); void native_bt_host_scan_handle(char *addr, int32_t addr_type, int32_t adv_type, char *adv_data, int32_t rssi); //GATTS void native_bt_host_gatts_handle_write(uint8_t data[], size_t len); int bt_gatts_adapter_add_service(amp_bt_host_adapter_gatts_srvc_t *srvc); int bt_gatts_adapter_update_chars(char *uuid, uint8_t *data, size_t len); #endif
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/addons/wireless/bt_host/bt_host_adapter.h
C
apache-2.0
1,533
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" #include "be_inl.h" #include "aiot_state_api.h" #include "bt_host_adapter.h" #include "cJSON.h" #define MOD_STR "BT_HOST" typedef struct { int scan_js_cb_ref; int conn_js_cb_ref; int gatts_js_cb_ref; }module_bt_host_info; module_bt_host_info g_module_bt_host_info; static module_bt_host_info * module_bt_host_get_info(void) { return &g_module_bt_host_info; } static void module_bt_host_clean(void) { } static duk_ret_t native_bt_host_init(duk_context *ctx) { int ret = -1; amp_bt_host_adapter_init_t *adapter_init; char *deviceName; int32_t conn_num_max; duk_get_prop_string(ctx, 0, "deviceName"); duk_get_prop_string(ctx, 0, "conn_num_max"); deviceName = duk_get_string(ctx, -2); conn_num_max = duk_get_number(ctx, -1); amp_debug(MOD_STR, "%s: deviceName = %s, conn_num_max = %d", __func__, deviceName, conn_num_max); adapter_init = (amp_bt_host_adapter_init_t *)aos_malloc(sizeof(amp_bt_host_adapter_init_t)); if (!adapter_init) { amp_error(MOD_STR, "allocate memory failed\n"); goto out; } adapter_init->dev_name = deviceName; adapter_init->conn_num_max = conn_num_max; ret = bt_host_adapter_init(adapter_init); amp_debug(MOD_STR, "%s: init ret = %d", __func__, ret); aos_free(adapter_init); out: duk_push_int(ctx, ret); return 1; } static duk_ret_t native_bt_host_start_adv(duk_context *ctx) { int ret = -1; int32_t type, interval_min, interval_max, channel_map; char *adv_data, *scan_rsp_data; amp_bt_host_adapter_adv_start_t *adapter_start_adv; module_bt_host_info * info = module_bt_host_get_info(); amp_debug(MOD_STR, "%s enter", __func__); duk_get_prop_string(ctx, 0, "type"); duk_get_prop_string(ctx, 0, "adv_data"); duk_get_prop_string(ctx, 0, "scan_rsp_data"); duk_get_prop_string(ctx, 0, "interval_min"); duk_get_prop_string(ctx, 0, "interval_max"); duk_get_prop_string(ctx, 0, "channel_map"); type = duk_get_number(ctx, -6); adv_data = duk_get_string(ctx, -5); scan_rsp_data = duk_get_string(ctx, -4); interval_min = duk_get_number(ctx, -3); interval_max = duk_get_number(ctx, -2); channel_map = duk_get_number(ctx, -1); amp_debug(MOD_STR, "%s: type = %d, ad = %s, sd = %s, interval_min = %d, interval_max = %d, channel_map = %d", __func__, type, adv_data, scan_rsp_data, interval_min, interval_max, channel_map); duk_dup(ctx, 1); info->conn_js_cb_ref = be_ref(ctx); adapter_start_adv = (amp_bt_host_adapter_adv_start_t *)aos_malloc(sizeof(amp_bt_host_adapter_adv_start_t)); if (!adapter_start_adv) { amp_error(MOD_STR, "allocate memory failed\n"); goto out; } adapter_start_adv->type = type; adapter_start_adv->adv_data = adv_data; adapter_start_adv->scan_rsp_data = scan_rsp_data; adapter_start_adv->interval_min = interval_min; adapter_start_adv->interval_max = interval_max; adapter_start_adv->channel_map = channel_map; ret = bt_host_adapter_start_adv(adapter_start_adv); aos_free(adapter_start_adv); out: duk_push_int(ctx, ret); return 1; } static duk_ret_t native_bt_host_stop_adv(duk_context *ctx) { int ret = -1; ret = bt_host_adapter_stop_adv(); out: duk_push_int(ctx, ret); return 1; } static duk_ret_t native_bt_host_start_scan(duk_context *ctx) { int ret = -1; int32_t type, interval, window; amp_bt_host_adapter_scan_start_t *adapter_start_scan; module_bt_host_info * info = module_bt_host_get_info(); amp_debug(MOD_STR, "%s enter", __func__); duk_get_prop_string(ctx, 0, "type"); duk_get_prop_string(ctx, 0, "interval"); duk_get_prop_string(ctx, 0, "window"); type = duk_get_number(ctx, -3); interval = duk_get_number(ctx, -2); window = duk_get_number(ctx, -1); duk_dup(ctx, 1); info->scan_js_cb_ref = be_ref(ctx); amp_debug(MOD_STR, "%s: type = %d, interval = %d, window = %d, channel_map = %d", __func__, type, interval, window); adapter_start_scan = (amp_bt_host_adapter_scan_start_t *)aos_malloc(sizeof(amp_bt_host_adapter_scan_start_t)); if (!adapter_start_scan) { amp_error(MOD_STR, "allocate memory failed\n"); goto out; } adapter_start_scan->type = type; adapter_start_scan->interval = interval; adapter_start_scan->window = window; ret = bt_host_adapter_start_scan(adapter_start_scan); aos_free(adapter_start_scan); out: duk_push_int(ctx, ret); return 1; } static duk_ret_t native_bt_host_stop_scan(duk_context *ctx) { int ret = -1; ret = bt_host_adapter_stop_scan(); out: duk_push_int(ctx, ret); return 1; } static duk_ret_t native_bt_host_add_service(duk_context *ctx) { int ret = -1, chars_num = 0; char *attr_uuid = NULL, *attr_permit = NULL, *service_cfg = NULL; cJSON* service_obj = NULL, *chars_list_obj = NULL, *descr_obj = NULL, *elemet = NULL; amp_bt_host_adapter_gatts_srvc_t service = {0}; amp_bt_host_adapter_gatt_chars_t *chars_list; module_bt_host_info * info = module_bt_host_get_info(); amp_debug(MOD_STR, "%s enter", __func__); service_cfg = duk_to_string(ctx, 0); #if 1 /* eg. { "s_uuid":"0x1A1A", "chars_list":[ { "char_uuid":"0x1B1B", "char_permit":"RW", "char_descr":{ "descr_type":"CCC", "descr_uuid":"0x1C1C" } }, { "char_uuid":"0x1D1D", "char_permit":"R" } ] } */ if (service_cfg) { amp_debug(MOD_STR, "[%s] service_cfg: %s", __func__, service_cfg); service_obj = cJSON_Parse(service_cfg); if (service_obj != NULL && cJSON_IsObject(service_obj)) { service.s_uuid = cJSON_GetStringValue(cJSON_GetObjectItem(service_obj, "s_uuid")); service.attr_cnt ++; // for service declaration if (service.s_uuid) { chars_list_obj = cJSON_GetObjectItem(service_obj, "chars_list"); if (chars_list_obj && cJSON_IsArray(chars_list_obj)) { chars_num = cJSON_GetArraySize(chars_list_obj); if (chars_num) { chars_list = service.chars = (amp_bt_host_adapter_gatt_chars_t *)aos_malloc( chars_num * sizeof(amp_bt_host_adapter_gatt_chars_t)); if (chars_list) { memset(chars_list, 0, chars_num * sizeof(amp_bt_host_adapter_gatt_chars_t)); cJSON_ArrayForEach(elemet, chars_list_obj) { chars_list->char_uuid = cJSON_GetStringValue(cJSON_GetObjectItem(elemet, "char_uuid")); chars_list->permission = cJSON_GetStringValue(cJSON_GetObjectItem(elemet, "char_permit")); descr_obj = cJSON_GetObjectItem(elemet, "char_descr"); if (descr_obj) { chars_list->descr_uuid = cJSON_GetStringValue(cJSON_GetObjectItem(descr_obj, "descr_uuid")); chars_list->descr_type = cJSON_GetStringValue(cJSON_GetObjectItem(descr_obj, "descr_type")); service.attr_cnt += 3; } else { service.attr_cnt += 2; } chars_list ++; } ret = bt_gatts_adapter_add_service(&service); aos_free(service.chars); } else { amp_error(MOD_STR, "[%s] memory not enough for chars_list", __func__); } } else { amp_error(MOD_STR, "[%s] the number of characteristic is invalid", __func__); } } } cJSON_Delete(service_obj); } else { amp_error(MOD_STR, "[%s] failed to parse service_cfg to json object", __func__); } } else { amp_error(MOD_STR, "[%s] service_cfg is null", __func__); } if (ret) { // success duk_dup(ctx, 1); info->gatts_js_cb_ref = be_ref(ctx); } #endif duk_push_int(ctx, ret?0:-1); return 1; } static duk_ret_t native_bt_host_update_chars(duk_context *ctx) { size_t vals_len = 0; int ret = -1, index = 0; uint8_t *vals_data = NULL; char *arg_str = NULL, *uuid = NULL; cJSON *root = NULL, *arry = NULL, *elemet = NULL; module_bt_host_info * info = module_bt_host_get_info(); amp_debug(MOD_STR, "%s enter with top %d", __func__, duk_get_top(ctx)); arg_str = duk_get_string(ctx, 0); //{"uuid":0x1000, "value":[1, 2, 3, 4]} if (arg_str) { root = cJSON_Parse(arg_str); if (root && cJSON_IsObject(root)) { uuid = cJSON_GetStringValue(cJSON_GetObjectItem(root, "uuid")); arry = cJSON_GetObjectItem(root, "value"); if (arry && cJSON_IsArray(arry)) { vals_len = cJSON_GetArraySize(arry); vals_data = (uint8_t *)malloc(vals_len * sizeof(uint8_t)); if (vals_data) { memset(vals_data, 0, vals_len * sizeof(uint8_t)); cJSON_ArrayForEach(elemet, arry) { vals_data[index++] = elemet->valueint; } ret = bt_gatts_adapter_update_chars(uuid, vals_data, vals_len); free(vals_data); } } cJSON_Delete(root); } } duk_push_int(ctx, ret); // 0: success, -1: fail return 1; } void native_bt_host_conn_handle(int32_t conn_handle, int32_t connect) { module_bt_host_info * info = module_bt_host_get_info(); if (info->conn_js_cb_ref) { duk_context *ctx = be_get_context(); be_push_ref(ctx, info->conn_js_cb_ref); duk_push_int(ctx, conn_handle); duk_push_int(ctx, connect); if (duk_pcall(ctx, 2) != DUK_EXEC_SUCCESS) { amp_console("%s", duk_safe_to_stacktrace(ctx, -1)); } duk_pop(ctx); duk_gc(ctx, 0); } } void native_bt_host_scan_handle(char *addr, int32_t addr_type, int32_t adv_type, char *adv_data, int32_t rssi) { module_bt_host_info * info = module_bt_host_get_info(); if (info->scan_js_cb_ref) { amp_error(MOD_STR, "scan cb %x\n", info->scan_js_cb_ref); duk_context *ctx = be_get_context(); be_push_ref(ctx, info->scan_js_cb_ref); duk_push_string(ctx, addr); duk_push_int(ctx, addr_type); duk_push_int(ctx, adv_type); duk_push_string(ctx, adv_data); duk_push_int(ctx, rssi); if (duk_pcall(ctx, 5) != DUK_EXEC_SUCCESS) { amp_console("%s", duk_safe_to_stacktrace(ctx, -1)); } duk_pop(ctx); duk_gc(ctx, 0); } } void native_bt_host_gatts_handle_write(uint8_t data[], size_t len) { module_bt_host_info * info = module_bt_host_get_info(); amp_debug(MOD_STR, "+++[%s][%d]+++", __func__, __LINE__); if (info->gatts_js_cb_ref) { duk_context *ctx = be_get_context(); amp_debug(MOD_STR, "+++[%s][%d]+++", __func__, __LINE__); be_push_ref(ctx, info->gatts_js_cb_ref); amp_debug(MOD_STR, "+++[%s][%d]+++", __func__, __LINE__); duk_idx_t arr_idx = duk_push_array(ctx); for (int i = 0; i < len; i++) { duk_push_int(ctx, data[i]); duk_put_prop_index(ctx, arr_idx, i); } amp_debug(MOD_STR, "+++[%s][%d]+++", __func__, __LINE__); if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) { amp_console("%s", duk_safe_to_stacktrace(ctx, -1)); } amp_debug(MOD_STR, "+++[%s][%d]+++", __func__, __LINE__); duk_pop(ctx); duk_gc(ctx, 0); } } void module_bt_host_register(void) { duk_context *ctx = be_get_context(); amp_module_free_register(module_bt_host_clean); duk_push_object(ctx); AMP_ADD_FUNCTION("init", native_bt_host_init, 1); AMP_ADD_FUNCTION("start_adv", native_bt_host_start_adv, 2); AMP_ADD_FUNCTION("stop_adv", native_bt_host_stop_adv, 0); AMP_ADD_FUNCTION("start_scan", native_bt_host_start_scan, 2); AMP_ADD_FUNCTION("stop_scan", native_bt_host_stop_scan, 0); AMP_ADD_FUNCTION("add_service", native_bt_host_add_service, 2); AMP_ADD_FUNCTION("update_char", native_bt_host_update_chars, 1); amp_debug(MOD_STR, "bt_host registered"); duk_put_prop_string(ctx, -2, "BT_HOST"); }
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/addons/wireless/bt_host/module_bt_host.c
C
apache-2.0
12,970
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_fs.h" #include "aos_system.h" #include "amp_config.h" #include "amp_defines.h" #include "amp_task.h" #include "board_mgr.h" #include "be_inl.h" #include "cJSON.h" #include "addons/libjs.h" #include "startup/app_entry.h" #define MOD_STR "BE" #define MAX_PATH_SIZE 1024 static duk_context *duk_ctx; static char node_modules_path[MAX_PATH_SIZE]; static char resolved_path[MAX_PATH_SIZE]; static char *file_data; int g_repl_config = 0; #define assert(x) do{ \ if(!(x)){ \ amp_error(MOD_STR, "fatal expression: " #x "\r\n"); \ while(1){ \ aos_msleep(10); \ }; \ } \ }while(0) static char *resolve_path(const char *parent, const char *module_id) { char base[MAX_PATH_SIZE]; int i; #ifdef JSE_HIGHLEVEL_JSAPI /* check libjs */ for(i = 0; i < libjs_num; i++){ if(strcmp(LIBJS_ENTRIES[i].name, module_id) != 0){ continue; } return (char *)module_id; } #endif /* path process */ if (module_id[0] != '.') { snprintf(base, sizeof(base), "%s/%s", node_modules_path, module_id); } else { strcpy(base, parent); char *last_slash = strrchr(base, '/'); if (last_slash) last_slash[0] = '\0'; int len = strlen(module_id); const char *p = module_id; if (len == 1 && p[0] == '.') { p += 1; } else if (p[0] == '.' && p[1] == '/') { p += 2; } else { const char *end = module_id + len; while (p <= end - 3 && p[0] == '.' && p[1] == '.' && p[2] == '/') { p += 3; char *last_slash = strrchr(base, '/'); if (last_slash) last_slash[0] = '\0'; else { amp_warn(MOD_STR, "resolve path fail\n"); break; } } } strcat(base, "/"); strcat(base, p); } struct aos_stat sb; int ret = aos_stat(base, &sb); amp_debug(MOD_STR, "base: %s, ret: %d\n", base, ret); if (!ret && S_ISREG(sb.st_mode)) { strcpy(resolved_path, base); return resolved_path; } snprintf(resolved_path, sizeof(resolved_path), "%s.js", base); ret = aos_stat(resolved_path, &sb); amp_debug(MOD_STR, "resolved_path: %s, ret: %d\n", resolved_path, ret); if (!ret && S_ISREG(sb.st_mode)) { return resolved_path; } snprintf(resolved_path, sizeof(resolved_path), "%s/index.js", base); ret = aos_stat(resolved_path, &sb); amp_debug(MOD_STR, "resolved_path: %s, ret: %d\n", resolved_path, ret); if (!ret && S_ISREG(sb.st_mode)) { return resolved_path; } snprintf(resolved_path, sizeof(resolved_path), "%s/package.json", base); ret = aos_stat(resolved_path, &sb); amp_debug(MOD_STR, "resolved_path: %s, ret: %d\n", resolved_path, ret); if (ret || !S_ISREG(sb.st_mode)) { amp_warn(MOD_STR, "file %s not exist\n", resolved_path); return NULL; } /* parse package.json */ char *pkg_data = aos_malloc(sb.st_size + 1); if (!pkg_data) { amp_warn(MOD_STR, "cannot alloc memory to read package.json for module: %s", module_id); return NULL; } int fp = aos_open(resolved_path, O_RDONLY); aos_read(fp, pkg_data, sb.st_size); aos_close(fp); pkg_data[sb.st_size] = '\0'; cJSON *json = cJSON_Parse(pkg_data); //TODO: cJSON *item_main = cJSON_GetObjectItemCaseSensitive(json, "main"); cJSON *item_main = cJSON_GetObjectItem(json, "main"); amp_debug(MOD_STR, "item_main: %p\n", item_main); //TODO: if (cJSON_IsString(item_main) && item_main->valuestring) { if (item_main->valuestring) { snprintf(resolved_path, sizeof(resolved_path), "%s/%s", base, item_main->valuestring); if (!aos_stat(resolved_path, &sb) && S_ISREG(sb.st_mode)) { cJSON_Delete(json); aos_free(pkg_data); return resolved_path; } snprintf(resolved_path, sizeof(resolved_path), "%s/%s.js", base, item_main->valuestring); if (!aos_stat(resolved_path, &sb) && S_ISREG(sb.st_mode)) { cJSON_Delete(json); aos_free(pkg_data); return resolved_path; } } cJSON_Delete(json); aos_free(pkg_data); return NULL; } static duk_ret_t cb_resolve_module(duk_context *ctx) { const char *module_id; const char *parent_id; module_id = duk_require_string(ctx, 0); parent_id = duk_require_string(ctx, 1); amp_debug(MOD_STR, "module_id: %s, parent_id: %s\n", module_id, parent_id); char *path = resolve_path(parent_id, module_id); if (!path) return duk_type_error(ctx, "cannot find module: %s", module_id); duk_push_string(ctx, path); amp_debug(MOD_STR, "resolve_cb: id:'%s', parent-id:'%s', resolve-to:'%s'\n", module_id, parent_id, duk_get_string(ctx, -1)); return 1; } static duk_ret_t cb_load_module(duk_context *ctx) { const char *filename; const char *module_id; int len; int i; module_id = duk_require_string(ctx, 0); duk_get_prop_string(ctx, 2, "filename"); filename = duk_require_string(ctx, -1); amp_debug(MOD_STR, "id:'%s', filename:'%s'\n", module_id, filename); #ifdef JSE_HIGHLEVEL_JSAPI /* find libjs entries */ for(i = 0; i < libjs_num; i++){ if(strcmp(LIBJS_ENTRIES[i].name, module_id) != 0){ continue; } amp_debug(MOD_STR, "find libjs entry: %s", module_id); duk_push_lstring(ctx, LIBJS_ENTRIES[i].content, strlen(LIBJS_ENTRIES[i].content)); return 1; } #endif int fp = aos_open(filename, O_RDONLY); assert(fp >= 0); len = aos_lseek(fp, 0, HAL_SEEK_END); amp_debug(MOD_STR, "file: %s, size: %d\n", filename, len); aos_lseek(fp, 0, HAL_SEEK_SET); char *data = (char *)aos_malloc(len); if (!data) { aos_close(fp); amp_warn(MOD_STR, "cannot alloc memory to read module: %s", module_id); return duk_type_error(ctx, "cannot alloc memory to read module: %s", module_id); } aos_read(fp, data, len); duk_push_lstring(ctx, data, len); aos_free(data); aos_close(fp); return 1; } static duk_ret_t handle_assert(duk_context *ctx) { if (duk_to_boolean(ctx, 0)) return 0; const char *msg = duk_safe_to_string(ctx, 1); // fprintf(stderr, "assertion failed: %s\n", msg); // fflush(stderr); amp_error(MOD_STR,"assertion failed: %s", msg); duk_push_string(ctx, ""); return duk_throw(ctx); } #if defined(JSE_HIGHLEVEL_JSAPI) && defined(JSE_CORE_ADDON_INITJS) static void module_initjs_register(void) { amp_debug(MOD_STR, "module_initjs_register"); // amp_debug("%s\r\n", LIBJS_ENTRIES[libjs_num - 1].content); duk_context *ctx = be_get_context(); duk_eval_string(ctx, LIBJS_ENTRIES[libjs_num - 1].content); duk_pop(ctx); } #endif /* * register addons */ static void jsengine_register_addons() { duk_context *ctx = be_get_context(); /** global Object */ #ifdef JSE_CORE_ADDON_BUILDIN module_builtin_register(); #endif #ifdef JSE_CORE_ADDON_SYSTEM module_system_register(); #endif #ifdef JSE_CORE_ADDON_SYSTIMER module_systimer_register(); #endif #ifdef JSE_ADVANCED_ADDON_UND module_und_register(); #endif duk_push_object(ctx); /** core component */ #ifdef JSE_CORE_ADDON_FS module_fs_register(); #endif #ifdef JSE_CORE_ADDON_KV module_kv_register(); #endif #ifdef JSE_CORE_ADDON_PM module_pm_register(); #endif #ifdef JSE_CORE_ADDON_BATTERY module_battery_register(); #endif #ifdef JSE_CORE_ADDON_CHARGER module_charger_register(); #endif #ifdef JSE_CORE_ADDON_AT module_at_register(); #endif #ifdef JSE_CORE_ADDON_LOG module_log_register(); #endif #ifdef JSE_ADVANCED_ADDON_BLECFGNET module_blecfgnet_register(); #endif #ifdef JSE_ADVANCED_ADDON_UI //module_vm_register(); module_ui_register(); #endif #ifdef JSE_ADVANCED_ADDON_KEYPAD module_keypad_register(); #endif #ifdef JSE_CORE_ADDON_CRYPTO module_crypto_register(); #endif /** network component */ #ifdef JSE_NET_ADDON_MQTT module_mqtt_register(); #endif #ifdef JSE_NET_ADDON_NETMGR module_netmgr_register(); #endif #ifdef JSE_NET_ADDON_WIFI module_wifi_register(); #endif #ifdef JSE_NET_ADDON_CELLULAR module_cellular_register(); #endif #ifdef JSE_NET_ADDON_UDP module_udp_register(); #endif #ifdef JSE_NET_ADDON_TCP module_tcp_register(); #endif #ifdef JSE_NET_ADDON_HTTP module_http_register(); #endif #ifdef JSE_NET_ADDON_MIIO module_miio_register(); #endif /** hardware component */ #ifdef JSE_HW_ADDON_ADC module_adc_register(); #endif #ifdef JSE_HW_ADDON_DAC module_dac_register(); #endif #ifdef JSE_HW_ADDON_CAN module_can_register(); #endif #ifdef JSE_HW_ADDON_GPIO module_gpio_register(); #endif #ifdef JSE_HW_ADDON_I2C module_i2c_register(); #endif #ifdef JSE_HW_ADDON_SPI module_spi_register(); #endif #ifdef JSE_HW_ADDON_TIMER module_timer_register(); #endif #ifdef JSE_HW_ADDON_IR module_ir_register(); #endif #ifdef JSE_HW_ADDON_LCD module_lcd_register(); #endif #ifdef JSE_HW_ADDON_PWM module_pwm_register(); #endif #ifdef JSE_HW_ADDON_ONEWIRE module_onewire_register(); #endif #ifdef JSE_HW_ADDON_RTC module_rtc_register(); #endif #ifdef JSE_HW_ADDON_UART module_uart_register(); #endif #ifdef JSE_HW_ADDON_WDG module_wdg_register(); #endif /** advanced component */ #ifdef JSE_ADVANCED_ADDON_AIOT_DEVICE module_aiot_device_register(); #endif #ifdef JSE_ADVANCED_ADDON_AIOT_GATEWAY module_aiot_gateway_register(); #endif #ifdef JSE_ADVANCED_ADDON_OTA module_app_ota_register(); #endif #ifdef JSE_ADVANCED_ADDON_AUDIOPLAYER module_audioplayer_register(); #endif #ifdef JSE_ADVANCED_ADDON_TTS module_tts_register(); #endif #ifdef JSE_ADVANCED_ADDON_LOCATION module_location_register(); #endif #ifdef JSE_ADVANCED_ADDON_PAYBOX module_paybox_register(); #endif #ifdef JSE_ADVANCED_ADDON_SMARTCARD module_smartcard_register(); #endif /** wireless component */ #ifdef JSE_WIRELESS_ADDON_BT_HOST module_bt_host_register(); #endif /* init.js */ #if defined(JSE_HIGHLEVEL_JSAPI) && defined(JSE_CORE_ADDON_INITJS) module_initjs_register(); #endif duk_put_global_string(ctx, "__native"); } void duk_debug_write_cb(long arg_level, const char *arg_file, long arg_line, const char *arg_func, const char *arg_msg){ amp_debug(MOD_STR, "%s\r\n", arg_msg); } void jsengine_init() { amp_debug(MOD_STR, "duktape jsengine_init\r\n"); if (duk_ctx) { amp_warn(MOD_STR, "bone engine has been initialized\n"); return; } duk_ctx = duk_create_heap_default(); be_ref_setup(duk_ctx); duk_push_c_function(duk_ctx, handle_assert, 2); duk_put_global_string(duk_ctx, "assert"); duk_push_object(duk_ctx); duk_push_c_function(duk_ctx, cb_resolve_module, DUK_VARARGS); duk_put_prop_string(duk_ctx, -2, "resolve"); duk_push_c_function(duk_ctx, cb_load_module, DUK_VARARGS); duk_put_prop_string(duk_ctx, -2, "load"); be_module_node_init(duk_ctx); amp_debug(MOD_STR, "duktape be_module_node_init\r\n"); snprintf(node_modules_path, sizeof(node_modules_path), "/node_modules"); // node_modules_path = JSE_FS_ROOT_DIR"/node_modules"; /* register all addons */ jsengine_register_addons(); #ifdef JSE_ADVANCED_ADDON_UI page_entry_register(); #endif /* register App() */ app_entry_register(); amp_debug(MOD_STR, "duktape jsengine_register_addons\r\n"); if (g_repl_config) { repl_init(); } } static duk_ret_t get_stack_raw(duk_context *ctx, void *udata) { (void)udata; if (!duk_is_object(ctx, -1)) { return 1; } if (!duk_has_prop_string(ctx, -1, "stack")) { return 1; } if (!duk_is_error(ctx, -1)) { /* Not an Error instance, don't read "stack". */ return 1; } duk_get_prop_string(ctx, -1, "stack"); /* caller coerces */ duk_remove(ctx, -2); return 1; } static void print_pop_error(duk_context *ctx, FILE *f) { /* Print error objects with a stack trace specially. * Note that getting the stack trace may throw an error * so this also needs to be safe call wrapped. */ (void)duk_safe_call(ctx, get_stack_raw, NULL /*udata*/, 1 /*nargs*/, 1 /*nrets*/); amp_console("%s\n", duk_safe_to_stacktrace(ctx, -1)); duk_pop(ctx); } static duk_ret_t wrapped_compile_execute(duk_context *ctx, void *udata) { const char *src_data; duk_size_t src_len; duk_uint_t comp_flags; (void)udata; /* Use duk_compile_lstring_filename() variant which avoids interning * the source code. This only really matters for low memory environments. */ /* [ ... src_data src_len filename ] */ src_data = (const char *)duk_require_pointer(ctx, -3); src_len = (duk_size_t)duk_require_uint(ctx, -2); comp_flags = DUK_COMPILE_SHEBANG; duk_compile_lstring_filename(ctx, comp_flags, src_data, src_len); /* [ ... src_data src_len function ] */ duk_push_global_object(ctx); /* 'this' binding */ duk_call_method(ctx, 0); return 0; /* duk_safe_call() cleans up */ } void jsengine_start(const char *js) { assert(duk_ctx); if (!js) { amp_warn(MOD_STR, "js is null\n"); return; } duk_push_pointer(duk_ctx, (void *)js); duk_push_uint(duk_ctx, (duk_uint_t)strlen(js)); duk_push_string(duk_ctx, "eval"); int ret = duk_safe_call(duk_ctx, wrapped_compile_execute, NULL /*udata*/, 3 /*nargs*/, 1 /*nret*/); if (ret != DUK_EXEC_SUCCESS) { print_pop_error(duk_ctx, stderr); } else { duk_pop(duk_ctx); } } void jsengine_eval_file(const char *filename) { amp_debug(MOD_STR, "jsengine_eval_file entry"); assert(filename); amp_debug(MOD_STR, "%s %s", "eval file: ", filename); /* set entry */ be_module_node_set_entry(duk_ctx, filename); /* read & run js file */ struct aos_stat sb; if (aos_stat(filename, &sb) || !S_ISREG(sb.st_mode)) { amp_warn(MOD_STR, "%s %s", "file not exist", filename); return; } amp_debug(MOD_STR, "%s %d", "file size: ", sb.st_size); file_data = (char *)aos_malloc(sb.st_size + 1); if (!file_data) { amp_warn(MOD_STR, "cannot alloc memory"); return; } file_data[sb.st_size] = 0; int fp = aos_open(filename, O_RDONLY); aos_read(fp, file_data, sb.st_size); aos_close(fp); duk_push_pointer(duk_ctx, (void *)file_data); duk_push_uint(duk_ctx, (duk_uint_t)sb.st_size); duk_push_string(duk_ctx, filename); int ret = duk_safe_call(duk_ctx, wrapped_compile_execute, NULL /*udata*/, 3 /*nargs*/, 1 /*nret*/); if (ret != DUK_EXEC_SUCCESS) { print_pop_error(duk_ctx, stderr); } else { duk_pop(duk_ctx); } } void jsengine_exit() { if (!duk_ctx) { amp_warn(MOD_STR, "jsengine has not been initialized"); return; } if (file_data) { aos_free(file_data); file_data = NULL; } duk_destroy_heap(duk_ctx); // aos_free(node_modules_path); duk_ctx = NULL; } duk_context *be_get_context() { return duk_ctx; } void jsengine_loop_once() { } extern int64_t g_ntp_time; extern int64_t g_up_time; duk_double_t amp_date_get_now() { int64_t uptime = aos_now_ms(); g_ntp_time = g_ntp_time + (uptime - g_up_time); duk_double_t time = floor(g_ntp_time); g_ntp_time = g_ntp_time - (uptime - g_up_time); return time; }
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/be.c
C
apache-2.0
15,893
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef BONE_ENGINE_INL_H #define BONE_ENGINE_INL_H #include <stdint.h> #include "duktape/duktape.h" #ifdef __cplusplus extern "C" { #endif /* * get JSEngine context */ duk_context *be_get_context(); /* * Create a global array refs in the heap stash */ void be_ref_setup(duk_context *ctx); /* * saving top of stack to refs, return refs position. (NOTE: top of stack * overflow) * */ int be_ref(duk_context *ctx); /* * get ref from refs */ void be_push_ref(duk_context *ctx, int ref); /* * clear ref in refs */ void be_unref(duk_context *ctx, int ref); /* * module manage initial */ void be_module_node_init(duk_context *ctx); /* * set entry file path, e.g. /spiffs/index.js */ void be_module_node_set_entry(duk_context *ctx, const char *entry); /* * JSEngine log prefix, identification for be-cli */ #define BonePrefix "BoneEngine > " #define AMP_ADD_GLOBAL_FUNCTION(FUNCTION_NAME_STRING, FUNCTION_NAME, PARAM_COUNT) \ duk_push_c_function(ctx, FUNCTION_NAME, PARAM_COUNT); \ duk_put_global_string(ctx, FUNCTION_NAME_STRING) #define AMP_ADD_FUNCTION(FUNCTION_NAME_STRING, FUNCTION_NAME, PARAM_COUNT) \ duk_push_c_function(ctx, FUNCTION_NAME, PARAM_COUNT); \ duk_put_prop_string(ctx, -2, FUNCTION_NAME_STRING) #define AMP_ADD_INT(INT_NAME, INT_VALUE) \ duk_push_int(ctx, INT_VALUE); \ duk_put_prop_string(ctx, -2, INT_NAME) #define AMP_ADD_STRING(STRING_NAME, STRING_VALUE) \ duk_push_string(ctx, STRING_VALUE); \ duk_put_prop_string(ctx, -2, STRING_NAME) #define AMP_ADD_BOOLEAN(BOOLEAN_NAME, BOOLEAN_VALUE) \ duk_push_boolean(ctx, BOOLEAN_VALUE); \ duk_put_prop_string(ctx, -2, BOOLEAN_NAME) /* addons */ void module_adc_register(void); void module_builtin_register(void); void module_dac_register(void); void module_gpio_register(void); void module_i2c_register(void); void module_ir_register(void); void module_lcd_register(void); void module_miio_register(void); void module_mqtt_register(void); void module_os_register(void); void module_crypto_register(void); void module_pwm_register(void); void module_rtc_register(void); void module_timer_register(void); void module_uart_register(void); void module_wdg_register(void); void module_wifi_register(void); void module_udp_register(void); void module_http_register(void); void module_fs_register(void); void module_aiot_register(void); void module_app_ota_register(void); void module_audioplayer_register(void); void module_tts_register(void); void module_location_register(void); void module_paybox_register(void); void module_smartcard_register(void); void module_kv_register(void); void module_pm_register(void); void module_battery_register(void); void module_charger_register(void); void module_wakelock_register(void); void module_cellular_register(void); void module_tcp_register(void); void module_aiot_register(void); void module_spi_register(void); void module_systimer_register(void); void module_system_register(void); void module_vm_register(void); void module_ui_register(void); void module_keypad_register(void); void module_bt_host_register(void); void module_blecfgnet_register(void); int32_t repl_init(void); #ifdef __cplusplus } #endif #endif /* BONE_ENGINE_INL_H */
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/be_inl.h
C
apache-2.0
3,263
/* * Node.js-like module loading framework for Duktape * * https://nodejs.org/api/modules.html */ #include "be_inl.h" static void duk__push_module_object(duk_context *ctx, const char *id); static duk_bool_t duk__get_cached_module(duk_context *ctx, const char *id) { duk_push_global_stash(ctx); (void)duk_get_prop_string(ctx, -1, "\xff" "requireCache"); if (duk_get_prop_string(ctx, -1, id)) { duk_remove(ctx, -2); duk_remove(ctx, -2); return 1; } else { duk_pop_3(ctx); return 0; } } /* Place a `module` object on the top of the value stack into the require cache * based on its `.id` property. As a convenience to the caller, leave the * object on top of the value stack afterwards. */ static void duk__put_cached_module(duk_context *ctx) { /* [ ... module ] */ duk_push_global_stash(ctx); (void)duk_get_prop_string(ctx, -1, "\xff" "requireCache"); duk_dup(ctx, -3); /* [ ... module stash req_cache module ] */ (void)duk_get_prop_string(ctx, -1, "id"); duk_dup(ctx, -2); duk_put_prop(ctx, -4); duk_pop_3(ctx); /* [ ... module ] */ } static void duk__del_cached_module(duk_context *ctx, const char *id) { duk_push_global_stash(ctx); (void)duk_get_prop_string(ctx, -1, "\xff" "requireCache"); duk_del_prop_string(ctx, -1, id); duk_pop_2(ctx); } static duk_int_t duk__eval_module_source(duk_context *ctx, void *udata) { const char *src; /* * Stack: [ ... module source ] */ (void)udata; /* Wrap the module code in a function expression. This is the simplest * way to implement CommonJS closure semantics and matches the behavior of * e.g. Node.js. */ duk_push_string(ctx, "(function(exports,require,module,__filename,__dirname){"); src = duk_require_string(ctx, -2); duk_push_string(ctx, (src[0] == '#' && src[1] == '!') ? "//" : ""); /* Shebang support. */ duk_dup(ctx, -3); /* source */ duk_push_string( ctx, "\n})"); /* Newline allows module last line to contain a // comment. */ duk_concat(ctx, 4); /* [ ... module source func_src ] */ (void)duk_get_prop_string(ctx, -3, "filename"); duk_compile(ctx, DUK_COMPILE_EVAL); duk_call(ctx, 0); /* [ ... module source func ] */ /* Set name for the wrapper function. */ duk_push_string(ctx, "name"); duk_push_string(ctx, "main"); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_FORCE); /* call the function wrapper */ (void)duk_get_prop_string(ctx, -3, "exports"); /* exports */ (void)duk_get_prop_string(ctx, -4, "require"); /* require */ duk_dup(ctx, -5); /* module */ (void)duk_get_prop_string(ctx, -6, "filename"); /* __filename */ duk_push_undefined(ctx); /* __dirname */ duk_call(ctx, 5); /* [ ... module source result(ignore) ] */ /* module.loaded = true */ duk_push_true(ctx); duk_put_prop_string(ctx, -4, "loaded"); /* [ ... module source retval ] */ duk_pop_2(ctx); /* [ ... module ] */ return 1; } static duk_ret_t duk__handle_require(duk_context *ctx) { /* * Value stack handling here is a bit sloppy but should be correct. * Call handling will clean up any extra garbage for us. */ const char *id; const char *parent_id; duk_idx_t module_idx; duk_idx_t stash_idx; duk_int_t ret; duk_push_global_stash(ctx); stash_idx = duk_normalize_index(ctx, -1); duk_push_current_function(ctx); (void)duk_get_prop_string(ctx, -1, "\xff" "moduleId"); parent_id = duk_require_string(ctx, -1); (void)parent_id; /* not used directly; suppress warning */ /* [ id stash require parent_id ] */ id = duk_require_string(ctx, 0); (void)duk_get_prop_string(ctx, stash_idx, "\xff" "modResolve"); duk_dup(ctx, 0); /* module ID */ duk_dup(ctx, -3); /* parent ID */ duk_call(ctx, 2); /* [ ... stash ... resolved_id ] */ id = duk_require_string(ctx, -1); if (duk__get_cached_module(ctx, id)) { goto have_module; /* use the cached module */ } duk__push_module_object(ctx, id); duk__put_cached_module(ctx); /* module remains on stack */ /* * From here on out, we have to be careful not to throw. If it can't be * avoided, the error must be caught and the module removed from the * require cache before rethrowing. This allows the application to * reattempt loading the module. */ module_idx = duk_normalize_index(ctx, -1); /* [ ... stash ... resolved_id module ] */ (void)duk_get_prop_string(ctx, stash_idx, "\xff" "modLoad"); duk_dup(ctx, -3); /* resolved ID */ (void)duk_get_prop_string(ctx, module_idx, "exports"); duk_dup(ctx, module_idx); ret = duk_pcall(ctx, 3); if (ret != DUK_EXEC_SUCCESS) { duk__del_cached_module(ctx, id); (void)duk_throw(ctx); /* rethrow */ } if (duk_is_string(ctx, -1)) { duk_int_t ret; /* [ ... module source ] */ ret = duk_safe_call(ctx, duk__eval_module_source, NULL, 2, 1); if (ret != DUK_EXEC_SUCCESS) { duk__del_cached_module(ctx, id); (void)duk_throw(ctx); /* rethrow */ } } else if (duk_is_undefined(ctx, -1)) { duk_pop(ctx); } else { duk__del_cached_module(ctx, id); (void)duk_type_error(ctx, "invalid module load callback return value"); } /* fall through */ have_module: /* [ ... module ] */ (void)duk_get_prop_string(ctx, -1, "exports"); duk_gc(ctx, 0); return 1; } static void duk__push_require_function(duk_context *ctx, const char *id) { duk_push_c_function(ctx, duk__handle_require, 1); duk_push_string(ctx, "name"); duk_push_string(ctx, "require"); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE); duk_push_string(ctx, id); duk_put_prop_string(ctx, -2, "\xff" "moduleId"); /* require.cache */ duk_push_global_stash(ctx); (void)duk_get_prop_string(ctx, -1, "\xff" "requireCache"); duk_put_prop_string(ctx, -3, "cache"); duk_pop(ctx); } static void duk__push_module_object(duk_context *ctx, const char *id) { duk_push_object(ctx); /* Node.js uses the canonicalized filename of a module for both module.id * and module.filename. We have no concept of a file system here, so just * use the module ID for both values. */ duk_push_string(ctx, id); duk_dup(ctx, -1); duk_put_prop_string(ctx, -3, "filename"); duk_put_prop_string(ctx, -2, "id"); /* module.exports = {} */ duk_push_object(ctx); duk_put_prop_string(ctx, -2, "exports"); /* module.loaded = false */ duk_push_false(ctx); duk_put_prop_string(ctx, -2, "loaded"); /* module.require */ duk__push_require_function(ctx, id); duk_put_prop_string(ctx, -2, "require"); } void be_module_node_set_entry(duk_context *ctx, const char *entry) { duk_push_global_object(ctx); duk_get_prop_string(ctx, -1, "require"); duk_push_string(ctx, entry); duk_put_prop_string(ctx, -2, "\xff" "moduleId"); duk_pop_n(ctx, 2); } void be_module_node_init(duk_context *ctx) { /* * Stack: [ ... options ] => [ ... ] */ duk_idx_t options_idx; duk_require_object_coercible(ctx, -1); /* error before setting up requireCache */ options_idx = duk_require_normalize_index(ctx, -1); /* Initialize the require cache to a fresh object. */ duk_push_global_stash(ctx); duk_push_bare_object(ctx); duk_put_prop_string(ctx, -2, "\xff" "requireCache"); duk_pop(ctx); /* Stash callbacks for later use. User code can overwrite them later * on directly by accessing the global stash. */ duk_push_global_stash(ctx); duk_get_prop_string(ctx, options_idx, "resolve"); duk_require_function(ctx, -1); duk_put_prop_string(ctx, -2, "\xff" "modResolve"); duk_get_prop_string(ctx, options_idx, "load"); duk_require_function(ctx, -1); duk_put_prop_string(ctx, -2, "\xff" "modLoad"); duk_pop(ctx); /* register `require` as a global function. */ duk_push_global_object(ctx); duk_push_string(ctx, "require"); duk__push_require_function(ctx, ""); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_SET_WRITABLE | DUK_DEFPROP_SET_CONFIGURABLE); duk_pop(ctx); duk_pop(ctx); /* pop argument */ }
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/be_module_node.c
C
apache-2.0
9,306
#include "be_inl.h" /* * Create a global array refs in the heap stash. */ void be_ref_setup(duk_context *ctx) { duk_push_heap_stash(ctx); /* Create a new array with one `0` at index `0`. */ duk_push_array(ctx); duk_push_int(ctx, 0); duk_put_prop_index(ctx, -2, 0); /* Store it as "refs" in the heap stash */ duk_put_prop_string(ctx, -2, "refs"); duk_pop(ctx); } int be_ref(duk_context *ctx) { int ref; if (duk_is_undefined(ctx, -1)) { duk_pop(ctx); return 0; } /* Get the "refs" array in the heap stash */ duk_push_heap_stash(ctx); duk_get_prop_string(ctx, -1, "refs"); duk_remove(ctx, -2); /* ref = refs[0] */ duk_get_prop_index(ctx, -1, 0); ref = duk_get_int(ctx, -1); duk_pop(ctx); /* If there was a free slot, remove it from the list */ if (ref != 0) { /* refs[0] = refs[ref] */ duk_get_prop_index(ctx, -1, ref); duk_put_prop_index(ctx, -2, 0); } /* Otherwise use the end of the list */ else { /* ref = refs.length; */ ref = duk_get_length(ctx, -1); } /* swap the array and the user value in the stack */ duk_insert(ctx, -2); /* refs[ref] = value */ duk_put_prop_index(ctx, -2, ref); /* Remove the refs array from the stack. */ duk_pop(ctx); return ref; } void be_push_ref(duk_context *ctx, int ref) { if (!ref) { duk_push_undefined(ctx); return; } /* Get the "refs" array in the heap stash */ duk_push_heap_stash(ctx); duk_get_prop_string(ctx, -1, "refs"); duk_remove(ctx, -2); duk_get_prop_index(ctx, -1, ref); duk_remove(ctx, -2); } void be_unref(duk_context *ctx, int ref) { if (!ref) return; /* Get the "refs" array in the heap stash */ duk_push_heap_stash(ctx); duk_get_prop_string(ctx, -1, "refs"); duk_remove(ctx, -2); /* Insert a new link in the freelist */ /* refs[ref] = refs[0] */ duk_get_prop_index(ctx, -1, 0); duk_put_prop_index(ctx, -2, ref); /* refs[0] = ref */ duk_push_int(ctx, ref); duk_put_prop_index(ctx, -2, 0); duk_pop(ctx); }
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/be_refs.c
C
apache-2.0
2,159
/* * Duktape public API for Duktape 2.5.0. * * See the API reference for documentation on call semantics. The exposed, * supported API is between the "BEGIN PUBLIC API" and "END PUBLIC API" * comments. Other parts of the header are Duktape internal and related to * e.g. platform/compiler/feature detection. * * Git commit 6001888049cb42656f8649db020e804bcdeca6a7 (v2.5.0). * Git branch v2.5-maintenance. * * See Duktape AUTHORS.rst and LICENSE.txt for copyright and * licensing information. */ /* LICENSE.txt */ /* * =============== * Duktape license * =============== * * (http://opensource.org/licenses/MIT) * * Copyright (c) 2013-2019 by Duktape authors (see AUTHORS.rst) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* AUTHORS.rst */ /* * =============== * Duktape authors * =============== * * Copyright * ========= * * Duktape copyrights are held by its authors. Each author has a copyright * to their contribution, and agrees to irrevocably license the contribution * under the Duktape ``LICENSE.txt``. * * Authors * ======= * * Please include an e-mail address, a link to your GitHub profile, or something * similar to allow your contribution to be identified accurately. * * The following people have contributed code, website contents, or Wiki contents, * and agreed to irrevocably license their contributions under the Duktape * ``LICENSE.txt`` (in order of appearance): * * * Sami Vaarala <sami.vaarala@iki.fi> * * Niki Dobrev * * Andreas \u00d6man <andreas@lonelycoder.com> * * L\u00e1szl\u00f3 Lang\u00f3 <llango.u-szeged@partner.samsung.com> * * Legimet <legimet.calc@gmail.com> * * Karl Skomski <karl@skomski.com> * * Bruce Pascoe <fatcerberus1@gmail.com> * * Ren\u00e9 Hollander <rene@rene8888.at> * * Julien Hamaide (https://github.com/crazyjul) * * Sebastian G\u00f6tte (https://github.com/jaseg) * * Tomasz Magulski (https://github.com/magul) * * \D. Bohdan (https://github.com/dbohdan) * * Ond\u0159ej Jirman (https://github.com/megous) * * Sa\u00fal Ibarra Corretg\u00e9 <saghul@gmail.com> * * Jeremy HU <huxingyi@msn.com> * * Ole Andr\u00e9 Vadla Ravn\u00e5s (https://github.com/oleavr) * * Harold Brenes (https://github.com/harold-b) * * Oliver Crow (https://github.com/ocrow) * * Jakub Ch\u0142api\u0144ski (https://github.com/jchlapinski) * * Brett Vickers (https://github.com/beevik) * * Dominik Okwieka (https://github.com/okitec) * * Remko Tron\u00e7on (https://el-tramo.be) * * Romero Malaquias (rbsm@ic.ufal.br) * * Michael Drake <michael.drake@codethink.co.uk> * * Steven Don (https://github.com/shdon) * * Simon Stone (https://github.com/sstone1) * * \J. McC. (https://github.com/jmhmccr) * * Jakub Nowakowski (https://github.com/jimvonmoon) * * Tommy Nguyen (https://github.com/tn0502) * * Fabrice Fontaine (https://github.com/ffontaine) * * Christopher Hiller (https://github.com/boneskull) * * Gonzalo Diethelm (https://github.com/gonzus) * * Michal Kasperek (https://github.com/michalkas) * * Andrew Janke (https://github.com/apjanke) * * Steve Fan (https://github.com/stevefan1999) * * Edward Betts (https://github.com/edwardbetts) * * Ozhan Duz (https://github.com/webfolderio) * * Akos Kiss (https://github.com/akosthekiss) * * TheBrokenRail (https://github.com/TheBrokenRail) * * Jesse Doyle (https://github.com/jessedoyle) * * Gero Kuehn (https://github.com/dc6jgk) * * James Swift (https://github.com/phraemer) * * Luis de Bethencourt (https://github.com/luisbg) * * Ian Whyman (https://github.com/v00d00) * * Rick Sayre (https://github.com/whorfin) * * Other contributions * =================== * * The following people have contributed something other than code (e.g. reported * bugs, provided ideas, etc; roughly in order of appearance): * * * Greg Burns * * Anthony Rabine * * Carlos Costa * * Aur\u00e9lien Bouilland * * Preet Desai (Pris Matic) * * judofyr (http://www.reddit.com/user/judofyr) * * Jason Woofenden * * Micha\u0142 Przyby\u015b * * Anthony Howe * * Conrad Pankoff * * Jim Schimpf * * Rajaran Gaunker (https://github.com/zimbabao) * * Andreas \u00d6man * * Doug Sanden * * Josh Engebretson (https://github.com/JoshEngebretson) * * Remo Eichenberger (https://github.com/remoe) * * Mamod Mehyar (https://github.com/mamod) * * David Demelier (https://github.com/markand) * * Tim Caswell (https://github.com/creationix) * * Mitchell Blank Jr (https://github.com/mitchblank) * * https://github.com/yushli * * Seo Sanghyeon (https://github.com/sanxiyn) * * Han ChoongWoo (https://github.com/tunz) * * Joshua Peek (https://github.com/josh) * * Bruce E. Pascoe (https://github.com/fatcerberus) * * https://github.com/Kelledin * * https://github.com/sstruchtrup * * Michael Drake (https://github.com/tlsa) * * https://github.com/chris-y * * Laurent Zubiaur (https://github.com/lzubiaur) * * Neil Kolban (https://github.com/nkolban) * * Wilhelm Wanecek (https://github.com/wanecek) * * Andrew Janke (https://github.com/apjanke) * * Unamer (https://github.com/unamer) * * Karl Dahlke (eklhad@gmail.com) * * If you are accidentally missing from this list, send me an e-mail * (``sami.vaarala@iki.fi``) and I'll fix the omission. */ #if !defined(DUKTAPE_H_INCLUDED) #define DUKTAPE_H_INCLUDED #define DUK_SINGLE_FILE /* * BEGIN PUBLIC API */ /* * Version and Git commit identification */ /* Duktape version, (major * 10000) + (minor * 100) + patch. Allows C code * to #if (DUK_VERSION >= NNN) against Duktape API version. The same value * is also available to ECMAScript code in Duktape.version. Unofficial * development snapshots have 99 for patch level (e.g. 0.10.99 would be a * development version after 0.10.0 but before the next official release). */ #define DUK_VERSION 20500L /* Git commit, describe, and branch for Duktape build. Useful for * non-official snapshot builds so that application code can easily log * which Duktape snapshot was used. Not available in the ECMAScript * environment. */ #define DUK_GIT_COMMIT "6001888049cb42656f8649db020e804bcdeca6a7" #define DUK_GIT_DESCRIBE "v2.5.0" #define DUK_GIT_BRANCH "v2.5-maintenance" /* External duk_config.h provides platform/compiler/OS dependent * typedefs and macros, and DUK_USE_xxx config options so that * the rest of Duktape doesn't need to do any feature detection. * DUK_VERSION is defined before including so that configuration * snippets can react to it. */ #include "duk_config.h" /* * Avoid C++ name mangling */ #if defined(__cplusplus) extern "C" { #endif /* * Some defines forwarded from feature detection */ #undef DUK_API_VARIADIC_MACROS #if defined(DUK_USE_VARIADIC_MACROS) #define DUK_API_VARIADIC_MACROS #endif #define DUK_API_NORETURN(decl) DUK_NORETURN(decl) /* * Public API specific typedefs * * Many types are wrapped by Duktape for portability to rare platforms * where e.g. 'int' is a 16-bit type. See practical typing discussion * in Duktape web documentation. */ struct duk_thread_state; struct duk_memory_functions; struct duk_function_list_entry; struct duk_number_list_entry; struct duk_time_components; /* duk_context is now defined in duk_config.h because it may also be * referenced there by prototypes. */ typedef struct duk_thread_state duk_thread_state; typedef struct duk_memory_functions duk_memory_functions; typedef struct duk_function_list_entry duk_function_list_entry; typedef struct duk_number_list_entry duk_number_list_entry; typedef struct duk_time_components duk_time_components; typedef duk_ret_t (*duk_c_function)(duk_context *ctx); typedef void *(*duk_alloc_function) (void *udata, duk_size_t size); typedef void *(*duk_realloc_function) (void *udata, void *ptr, duk_size_t size); typedef void (*duk_free_function) (void *udata, void *ptr); typedef void (*duk_fatal_function) (void *udata, const char *msg); typedef void (*duk_decode_char_function) (void *udata, duk_codepoint_t codepoint); typedef duk_codepoint_t (*duk_map_char_function) (void *udata, duk_codepoint_t codepoint); typedef duk_ret_t (*duk_safe_call_function) (duk_context *ctx, void *udata); typedef duk_size_t (*duk_debug_read_function) (void *udata, char *buffer, duk_size_t length); typedef duk_size_t (*duk_debug_write_function) (void *udata, const char *buffer, duk_size_t length); typedef duk_size_t (*duk_debug_peek_function) (void *udata); typedef void (*duk_debug_read_flush_function) (void *udata); typedef void (*duk_debug_write_flush_function) (void *udata); typedef duk_idx_t (*duk_debug_request_function) (duk_context *ctx, void *udata, duk_idx_t nvalues); typedef void (*duk_debug_detached_function) (duk_context *ctx, void *udata); struct duk_thread_state { /* XXX: Enough space to hold internal suspend/resume structure. * This is rather awkward and to be fixed when the internal * structure is visible for the public API header. */ char data[128]; }; struct duk_memory_functions { duk_alloc_function alloc_func; duk_realloc_function realloc_func; duk_free_function free_func; void *udata; }; struct duk_function_list_entry { const char *key; duk_c_function value; duk_idx_t nargs; }; struct duk_number_list_entry { const char *key; duk_double_t value; }; struct duk_time_components { duk_double_t year; /* year, e.g. 2016, ECMAScript year range */ duk_double_t month; /* month: 1-12 */ duk_double_t day; /* day: 1-31 */ duk_double_t hours; /* hour: 0-59 */ duk_double_t minutes; /* minute: 0-59 */ duk_double_t seconds; /* second: 0-59 (in POSIX time no leap second) */ duk_double_t milliseconds; /* may contain sub-millisecond fractions */ duk_double_t weekday; /* weekday: 0-6, 0=Sunday, 1=Monday, ..., 6=Saturday */ }; /* * Constants */ /* Duktape debug protocol version used by this build. */ #define DUK_DEBUG_PROTOCOL_VERSION 2 /* Used to represent invalid index; if caller uses this without checking, * this index will map to a non-existent stack entry. Also used in some * API calls as a marker to denote "no value". */ #define DUK_INVALID_INDEX DUK_IDX_MIN /* Indicates that a native function does not have a fixed number of args, * and the argument stack should not be capped/extended at all. */ #define DUK_VARARGS ((duk_int_t) (-1)) /* Number of value stack entries (in addition to actual call arguments) * guaranteed to be allocated on entry to a Duktape/C function. */ #define DUK_API_ENTRY_STACK 64U /* Value types, used by e.g. duk_get_type() */ #define DUK_TYPE_MIN 0U #define DUK_TYPE_NONE 0U /* no value, e.g. invalid index */ #define DUK_TYPE_UNDEFINED 1U /* ECMAScript undefined */ #define DUK_TYPE_NULL 2U /* ECMAScript null */ #define DUK_TYPE_BOOLEAN 3U /* ECMAScript boolean: 0 or 1 */ #define DUK_TYPE_NUMBER 4U /* ECMAScript number: double */ #define DUK_TYPE_STRING 5U /* ECMAScript string: CESU-8 / extended UTF-8 encoded */ #define DUK_TYPE_OBJECT 6U /* ECMAScript object: includes objects, arrays, functions, threads */ #define DUK_TYPE_BUFFER 7U /* fixed or dynamic, garbage collected byte buffer */ #define DUK_TYPE_POINTER 8U /* raw void pointer */ #define DUK_TYPE_LIGHTFUNC 9U /* lightweight function pointer */ #define DUK_TYPE_MAX 9U /* Value mask types, used by e.g. duk_get_type_mask() */ #define DUK_TYPE_MASK_NONE (1U << DUK_TYPE_NONE) #define DUK_TYPE_MASK_UNDEFINED (1U << DUK_TYPE_UNDEFINED) #define DUK_TYPE_MASK_NULL (1U << DUK_TYPE_NULL) #define DUK_TYPE_MASK_BOOLEAN (1U << DUK_TYPE_BOOLEAN) #define DUK_TYPE_MASK_NUMBER (1U << DUK_TYPE_NUMBER) #define DUK_TYPE_MASK_STRING (1U << DUK_TYPE_STRING) #define DUK_TYPE_MASK_OBJECT (1U << DUK_TYPE_OBJECT) #define DUK_TYPE_MASK_BUFFER (1U << DUK_TYPE_BUFFER) #define DUK_TYPE_MASK_POINTER (1U << DUK_TYPE_POINTER) #define DUK_TYPE_MASK_LIGHTFUNC (1U << DUK_TYPE_LIGHTFUNC) #define DUK_TYPE_MASK_THROW (1U << 10) /* internal flag value: throw if mask doesn't match */ #define DUK_TYPE_MASK_PROMOTE (1U << 11) /* internal flag value: promote to object if mask matches */ /* Coercion hints */ #define DUK_HINT_NONE 0 /* prefer number, unless input is a Date, in which * case prefer string (E5 Section 8.12.8) */ #define DUK_HINT_STRING 1 /* prefer string */ #define DUK_HINT_NUMBER 2 /* prefer number */ /* Enumeration flags for duk_enum() */ #define DUK_ENUM_INCLUDE_NONENUMERABLE (1U << 0) /* enumerate non-numerable properties in addition to enumerable */ #define DUK_ENUM_INCLUDE_HIDDEN (1U << 1) /* enumerate hidden symbols too (in Duktape 1.x called internal properties) */ #define DUK_ENUM_INCLUDE_SYMBOLS (1U << 2) /* enumerate symbols */ #define DUK_ENUM_EXCLUDE_STRINGS (1U << 3) /* exclude strings */ #define DUK_ENUM_OWN_PROPERTIES_ONLY (1U << 4) /* don't walk prototype chain, only check own properties */ #define DUK_ENUM_ARRAY_INDICES_ONLY (1U << 5) /* only enumerate array indices */ /* XXX: misleading name */ #define DUK_ENUM_SORT_ARRAY_INDICES (1U << 6) /* sort array indices (applied to full enumeration result, including inherited array indices); XXX: misleading name */ #define DUK_ENUM_NO_PROXY_BEHAVIOR (1U << 7) /* enumerate a proxy object itself without invoking proxy behavior */ /* Compilation flags for duk_compile() and duk_eval() */ /* DUK_COMPILE_xxx bits 0-2 are reserved for an internal 'nargs' argument. */ #define DUK_COMPILE_EVAL (1U << 3) /* compile eval code (instead of global code) */ #define DUK_COMPILE_FUNCTION (1U << 4) /* compile function code (instead of global code) */ #define DUK_COMPILE_STRICT (1U << 5) /* use strict (outer) context for global, eval, or function code */ #define DUK_COMPILE_SHEBANG (1U << 6) /* allow shebang ('#! ...') comment on first line of source */ #define DUK_COMPILE_SAFE (1U << 7) /* (internal) catch compilation errors */ #define DUK_COMPILE_NORESULT (1U << 8) /* (internal) omit eval result */ #define DUK_COMPILE_NOSOURCE (1U << 9) /* (internal) no source string on stack */ #define DUK_COMPILE_STRLEN (1U << 10) /* (internal) take strlen() of src_buffer (avoids double evaluation in macro) */ #define DUK_COMPILE_NOFILENAME (1U << 11) /* (internal) no filename on stack */ #define DUK_COMPILE_FUNCEXPR (1U << 12) /* (internal) source is a function expression (used for Function constructor) */ /* Flags for duk_def_prop() and its variants; base flags + a lot of convenience shorthands */ #define DUK_DEFPROP_WRITABLE (1U << 0) /* set writable (effective if DUK_DEFPROP_HAVE_WRITABLE set) */ #define DUK_DEFPROP_ENUMERABLE (1U << 1) /* set enumerable (effective if DUK_DEFPROP_HAVE_ENUMERABLE set) */ #define DUK_DEFPROP_CONFIGURABLE (1U << 2) /* set configurable (effective if DUK_DEFPROP_HAVE_CONFIGURABLE set) */ #define DUK_DEFPROP_HAVE_WRITABLE (1U << 3) /* set/clear writable */ #define DUK_DEFPROP_HAVE_ENUMERABLE (1U << 4) /* set/clear enumerable */ #define DUK_DEFPROP_HAVE_CONFIGURABLE (1U << 5) /* set/clear configurable */ #define DUK_DEFPROP_HAVE_VALUE (1U << 6) /* set value (given on value stack) */ #define DUK_DEFPROP_HAVE_GETTER (1U << 7) /* set getter (given on value stack) */ #define DUK_DEFPROP_HAVE_SETTER (1U << 8) /* set setter (given on value stack) */ #define DUK_DEFPROP_FORCE (1U << 9) /* force change if possible, may still fail for e.g. virtual properties */ #define DUK_DEFPROP_SET_WRITABLE (DUK_DEFPROP_HAVE_WRITABLE | DUK_DEFPROP_WRITABLE) #define DUK_DEFPROP_CLEAR_WRITABLE DUK_DEFPROP_HAVE_WRITABLE #define DUK_DEFPROP_SET_ENUMERABLE (DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE) #define DUK_DEFPROP_CLEAR_ENUMERABLE DUK_DEFPROP_HAVE_ENUMERABLE #define DUK_DEFPROP_SET_CONFIGURABLE (DUK_DEFPROP_HAVE_CONFIGURABLE | DUK_DEFPROP_CONFIGURABLE) #define DUK_DEFPROP_CLEAR_CONFIGURABLE DUK_DEFPROP_HAVE_CONFIGURABLE #define DUK_DEFPROP_W DUK_DEFPROP_WRITABLE #define DUK_DEFPROP_E DUK_DEFPROP_ENUMERABLE #define DUK_DEFPROP_C DUK_DEFPROP_CONFIGURABLE #define DUK_DEFPROP_WE (DUK_DEFPROP_WRITABLE | DUK_DEFPROP_ENUMERABLE) #define DUK_DEFPROP_WC (DUK_DEFPROP_WRITABLE | DUK_DEFPROP_CONFIGURABLE) #define DUK_DEFPROP_EC (DUK_DEFPROP_ENUMERABLE | DUK_DEFPROP_CONFIGURABLE) #define DUK_DEFPROP_WEC (DUK_DEFPROP_WRITABLE | DUK_DEFPROP_ENUMERABLE | DUK_DEFPROP_CONFIGURABLE) #define DUK_DEFPROP_HAVE_W DUK_DEFPROP_HAVE_WRITABLE #define DUK_DEFPROP_HAVE_E DUK_DEFPROP_HAVE_ENUMERABLE #define DUK_DEFPROP_HAVE_C DUK_DEFPROP_HAVE_CONFIGURABLE #define DUK_DEFPROP_HAVE_WE (DUK_DEFPROP_HAVE_WRITABLE | DUK_DEFPROP_HAVE_ENUMERABLE) #define DUK_DEFPROP_HAVE_WC (DUK_DEFPROP_HAVE_WRITABLE | DUK_DEFPROP_HAVE_CONFIGURABLE) #define DUK_DEFPROP_HAVE_EC (DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_HAVE_CONFIGURABLE) #define DUK_DEFPROP_HAVE_WEC (DUK_DEFPROP_HAVE_WRITABLE | DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_HAVE_CONFIGURABLE) #define DUK_DEFPROP_SET_W DUK_DEFPROP_SET_WRITABLE #define DUK_DEFPROP_SET_E DUK_DEFPROP_SET_ENUMERABLE #define DUK_DEFPROP_SET_C DUK_DEFPROP_SET_CONFIGURABLE #define DUK_DEFPROP_SET_WE (DUK_DEFPROP_SET_WRITABLE | DUK_DEFPROP_SET_ENUMERABLE) #define DUK_DEFPROP_SET_WC (DUK_DEFPROP_SET_WRITABLE | DUK_DEFPROP_SET_CONFIGURABLE) #define DUK_DEFPROP_SET_EC (DUK_DEFPROP_SET_ENUMERABLE | DUK_DEFPROP_SET_CONFIGURABLE) #define DUK_DEFPROP_SET_WEC (DUK_DEFPROP_SET_WRITABLE | DUK_DEFPROP_SET_ENUMERABLE | DUK_DEFPROP_SET_CONFIGURABLE) #define DUK_DEFPROP_CLEAR_W DUK_DEFPROP_CLEAR_WRITABLE #define DUK_DEFPROP_CLEAR_E DUK_DEFPROP_CLEAR_ENUMERABLE #define DUK_DEFPROP_CLEAR_C DUK_DEFPROP_CLEAR_CONFIGURABLE #define DUK_DEFPROP_CLEAR_WE (DUK_DEFPROP_CLEAR_WRITABLE | DUK_DEFPROP_CLEAR_ENUMERABLE) #define DUK_DEFPROP_CLEAR_WC (DUK_DEFPROP_CLEAR_WRITABLE | DUK_DEFPROP_CLEAR_CONFIGURABLE) #define DUK_DEFPROP_CLEAR_EC (DUK_DEFPROP_CLEAR_ENUMERABLE | DUK_DEFPROP_CLEAR_CONFIGURABLE) #define DUK_DEFPROP_CLEAR_WEC (DUK_DEFPROP_CLEAR_WRITABLE | DUK_DEFPROP_CLEAR_ENUMERABLE | DUK_DEFPROP_CLEAR_CONFIGURABLE) #define DUK_DEFPROP_ATTR_W (DUK_DEFPROP_HAVE_WEC | DUK_DEFPROP_W) #define DUK_DEFPROP_ATTR_E (DUK_DEFPROP_HAVE_WEC | DUK_DEFPROP_E) #define DUK_DEFPROP_ATTR_C (DUK_DEFPROP_HAVE_WEC | DUK_DEFPROP_C) #define DUK_DEFPROP_ATTR_WE (DUK_DEFPROP_HAVE_WEC | DUK_DEFPROP_WE) #define DUK_DEFPROP_ATTR_WC (DUK_DEFPROP_HAVE_WEC | DUK_DEFPROP_WC) #define DUK_DEFPROP_ATTR_EC (DUK_DEFPROP_HAVE_WEC | DUK_DEFPROP_EC) #define DUK_DEFPROP_ATTR_WEC (DUK_DEFPROP_HAVE_WEC | DUK_DEFPROP_WEC) /* Flags for duk_push_thread_raw() */ #define DUK_THREAD_NEW_GLOBAL_ENV (1U << 0) /* create a new global environment */ /* Flags for duk_gc() */ #define DUK_GC_COMPACT (1U << 0) /* compact heap objects */ /* Error codes (must be 8 bits at most, see duk_error.h) */ #define DUK_ERR_NONE 0 /* no error (e.g. from duk_get_error_code()) */ #define DUK_ERR_ERROR 1 /* Error */ #define DUK_ERR_EVAL_ERROR 2 /* EvalError */ #define DUK_ERR_RANGE_ERROR 3 /* RangeError */ #define DUK_ERR_REFERENCE_ERROR 4 /* ReferenceError */ #define DUK_ERR_SYNTAX_ERROR 5 /* SyntaxError */ #define DUK_ERR_TYPE_ERROR 6 /* TypeError */ #define DUK_ERR_URI_ERROR 7 /* URIError */ /* Return codes for C functions (shortcut for throwing an error) */ #define DUK_RET_ERROR (-DUK_ERR_ERROR) #define DUK_RET_EVAL_ERROR (-DUK_ERR_EVAL_ERROR) #define DUK_RET_RANGE_ERROR (-DUK_ERR_RANGE_ERROR) #define DUK_RET_REFERENCE_ERROR (-DUK_ERR_REFERENCE_ERROR) #define DUK_RET_SYNTAX_ERROR (-DUK_ERR_SYNTAX_ERROR) #define DUK_RET_TYPE_ERROR (-DUK_ERR_TYPE_ERROR) #define DUK_RET_URI_ERROR (-DUK_ERR_URI_ERROR) /* Return codes for protected calls (duk_safe_call(), duk_pcall()) */ #define DUK_EXEC_SUCCESS 0 #define DUK_EXEC_ERROR 1 /* Debug levels for DUK_USE_DEBUG_WRITE(). */ #define DUK_LEVEL_DEBUG 0 #define DUK_LEVEL_DDEBUG 1 #define DUK_LEVEL_DDDEBUG 2 /* * Macros to create Symbols as C statically constructed strings. * * Call e.g. as DUK_HIDDEN_SYMBOL("myProperty") <=> ("\xFF" "myProperty"). * * Local symbols have a unique suffix, caller should take care to avoid * conflicting with the Duktape internal representation by e.g. prepending * a '!' character: DUK_LOCAL_SYMBOL("myLocal", "!123"). * * Note that these can only be used for string constants, not dynamically * created strings. * * You shouldn't normally use DUK_INTERNAL_SYMBOL() at all. It is reserved * for Duktape internal symbols only. There are no versioning guarantees * for internal symbols. */ #define DUK_HIDDEN_SYMBOL(x) ("\xFF" x) #define DUK_GLOBAL_SYMBOL(x) ("\x80" x) #define DUK_LOCAL_SYMBOL(x,uniq) ("\x81" x "\xff" uniq) #define DUK_WELLKNOWN_SYMBOL(x) ("\x81" x "\xff") #define DUK_INTERNAL_SYMBOL(x) ("\x82" x) /* * If no variadic macros, __FILE__ and __LINE__ are passed through globals * which is ugly and not thread safe. */ #if !defined(DUK_API_VARIADIC_MACROS) DUK_EXTERNAL_DECL const char *duk_api_global_filename; DUK_EXTERNAL_DECL duk_int_t duk_api_global_line; #endif /* * Context management */ DUK_EXTERNAL_DECL duk_context *duk_create_heap(duk_alloc_function alloc_func, duk_realloc_function realloc_func, duk_free_function free_func, void *heap_udata, duk_fatal_function fatal_handler); DUK_EXTERNAL_DECL void duk_destroy_heap(duk_context *ctx); DUK_EXTERNAL_DECL void duk_suspend(duk_context *ctx, duk_thread_state *state); DUK_EXTERNAL_DECL void duk_resume(duk_context *ctx, const duk_thread_state *state); #define duk_create_heap_default() \ duk_create_heap(NULL, NULL, NULL, NULL, NULL) /* * Memory management * * Raw functions have no side effects (cannot trigger GC). */ DUK_EXTERNAL_DECL void *duk_alloc_raw(duk_context *ctx, duk_size_t size); DUK_EXTERNAL_DECL void duk_free_raw(duk_context *ctx, void *ptr); DUK_EXTERNAL_DECL void *duk_realloc_raw(duk_context *ctx, void *ptr, duk_size_t size); DUK_EXTERNAL_DECL void *duk_alloc(duk_context *ctx, duk_size_t size); DUK_EXTERNAL_DECL void duk_free(duk_context *ctx, void *ptr); DUK_EXTERNAL_DECL void *duk_realloc(duk_context *ctx, void *ptr, duk_size_t size); DUK_EXTERNAL_DECL void duk_get_memory_functions(duk_context *ctx, duk_memory_functions *out_funcs); DUK_EXTERNAL_DECL void duk_gc(duk_context *ctx, duk_uint_t flags); /* * Error handling */ DUK_API_NORETURN(DUK_EXTERNAL_DECL void duk_throw_raw(duk_context *ctx)); #define duk_throw(ctx) \ (duk_throw_raw((ctx)), (duk_ret_t) 0) DUK_API_NORETURN(DUK_EXTERNAL_DECL void duk_fatal_raw(duk_context *ctx, const char *err_msg)); #define duk_fatal(ctx,err_msg) \ (duk_fatal_raw((ctx), (err_msg)), (duk_ret_t) 0) DUK_API_NORETURN(DUK_EXTERNAL_DECL void duk_error_raw(duk_context *ctx, duk_errcode_t err_code, const char *filename, duk_int_t line, const char *fmt, ...)); #if defined(DUK_API_VARIADIC_MACROS) #define duk_error(ctx,err_code,...) \ (duk_error_raw((ctx), (duk_errcode_t) (err_code), (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__), (duk_ret_t) 0) #define duk_generic_error(ctx,...) \ (duk_error_raw((ctx), (duk_errcode_t) DUK_ERR_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__), (duk_ret_t) 0) #define duk_eval_error(ctx,...) \ (duk_error_raw((ctx), (duk_errcode_t) DUK_ERR_EVAL_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__), (duk_ret_t) 0) #define duk_range_error(ctx,...) \ (duk_error_raw((ctx), (duk_errcode_t) DUK_ERR_RANGE_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__), (duk_ret_t) 0) #define duk_reference_error(ctx,...) \ (duk_error_raw((ctx), (duk_errcode_t) DUK_ERR_REFERENCE_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__), (duk_ret_t) 0) #define duk_syntax_error(ctx,...) \ (duk_error_raw((ctx), (duk_errcode_t) DUK_ERR_SYNTAX_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__), (duk_ret_t) 0) #define duk_type_error(ctx,...) \ (duk_error_raw((ctx), (duk_errcode_t) DUK_ERR_TYPE_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__), (duk_ret_t) 0) #define duk_uri_error(ctx,...) \ (duk_error_raw((ctx), (duk_errcode_t) DUK_ERR_URI_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__), (duk_ret_t) 0) #else /* DUK_API_VARIADIC_MACROS */ /* For legacy compilers without variadic macros a macro hack is used to allow * variable arguments. While the macro allows "return duk_error(...)", it * will fail with e.g. "(void) duk_error(...)". The calls are noreturn but * with a return value to allow the "return duk_error(...)" idiom. This may * cause some compiler warnings, but without noreturn the generated code is * often worse. The same approach as with variadic macros (using * "(duk_error(...), 0)") won't work due to the macro hack structure. */ DUK_API_NORETURN(DUK_EXTERNAL_DECL duk_ret_t duk_error_stash(duk_context *ctx, duk_errcode_t err_code, const char *fmt, ...)); DUK_API_NORETURN(DUK_EXTERNAL_DECL duk_ret_t duk_generic_error_stash(duk_context *ctx, const char *fmt, ...)); DUK_API_NORETURN(DUK_EXTERNAL_DECL duk_ret_t duk_eval_error_stash(duk_context *ctx, const char *fmt, ...)); DUK_API_NORETURN(DUK_EXTERNAL_DECL duk_ret_t duk_range_error_stash(duk_context *ctx, const char *fmt, ...)); DUK_API_NORETURN(DUK_EXTERNAL_DECL duk_ret_t duk_reference_error_stash(duk_context *ctx, const char *fmt, ...)); DUK_API_NORETURN(DUK_EXTERNAL_DECL duk_ret_t duk_syntax_error_stash(duk_context *ctx, const char *fmt, ...)); DUK_API_NORETURN(DUK_EXTERNAL_DECL duk_ret_t duk_type_error_stash(duk_context *ctx, const char *fmt, ...)); DUK_API_NORETURN(DUK_EXTERNAL_DECL duk_ret_t duk_uri_error_stash(duk_context *ctx, const char *fmt, ...)); #define duk_error \ (duk_api_global_filename = (const char *) (DUK_FILE_MACRO), \ duk_api_global_line = (duk_int_t) (DUK_LINE_MACRO), \ duk_error_stash) /* last value is func pointer, arguments follow in parens */ #define duk_generic_error \ (duk_api_global_filename = (const char *) (DUK_FILE_MACRO), \ duk_api_global_line = (duk_int_t) (DUK_LINE_MACRO), \ duk_generic_error_stash) #define duk_eval_error \ (duk_api_global_filename = (const char *) (DUK_FILE_MACRO), \ duk_api_global_line = (duk_int_t) (DUK_LINE_MACRO), \ duk_eval_error_stash) #define duk_range_error \ (duk_api_global_filename = (const char *) (DUK_FILE_MACRO), \ duk_api_global_line = (duk_int_t) (DUK_LINE_MACRO), \ duk_range_error_stash) #define duk_reference_error \ (duk_api_global_filename = (const char *) (DUK_FILE_MACRO), \ duk_api_global_line = (duk_int_t) (DUK_LINE_MACRO), \ duk_reference_error_stash) #define duk_syntax_error \ (duk_api_global_filename = (const char *) (DUK_FILE_MACRO), \ duk_api_global_line = (duk_int_t) (DUK_LINE_MACRO), \ duk_syntax_error_stash) #define duk_type_error \ (duk_api_global_filename = (const char *) (DUK_FILE_MACRO), \ duk_api_global_line = (duk_int_t) (DUK_LINE_MACRO), \ duk_type_error_stash) #define duk_uri_error \ (duk_api_global_filename = (const char *) (DUK_FILE_MACRO), \ duk_api_global_line = (duk_int_t) (DUK_LINE_MACRO), \ duk_uri_error_stash) #endif /* DUK_API_VARIADIC_MACROS */ DUK_API_NORETURN(DUK_EXTERNAL_DECL void duk_error_va_raw(duk_context *ctx, duk_errcode_t err_code, const char *filename, duk_int_t line, const char *fmt, va_list ap)); #define duk_error_va(ctx,err_code,fmt,ap) \ (duk_error_va_raw((ctx), (duk_errcode_t) (err_code), (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), (fmt), (ap)), (duk_ret_t) 0) #define duk_generic_error_va(ctx,fmt,ap) \ (duk_error_va_raw((ctx), (duk_errcode_t) DUK_ERR_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), (fmt), (ap)), (duk_ret_t) 0) #define duk_eval_error_va(ctx,fmt,ap) \ (duk_error_va_raw((ctx), (duk_errcode_t) DUK_ERR_EVAL_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), (fmt), (ap)), (duk_ret_t) 0) #define duk_range_error_va(ctx,fmt,ap) \ (duk_error_va_raw((ctx), (duk_errcode_t) DUK_ERR_RANGE_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), (fmt), (ap)), (duk_ret_t) 0) #define duk_reference_error_va(ctx,fmt,ap) \ (duk_error_va_raw((ctx), (duk_errcode_t) DUK_ERR_REFERENCE_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), (fmt), (ap)), (duk_ret_t) 0) #define duk_syntax_error_va(ctx,fmt,ap) \ (duk_error_va_raw((ctx), (duk_errcode_t) DUK_ERR_SYNTAX_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), (fmt), (ap)), (duk_ret_t) 0) #define duk_type_error_va(ctx,fmt,ap) \ (duk_error_va_raw((ctx), (duk_errcode_t) DUK_ERR_TYPE_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), (fmt), (ap)), (duk_ret_t) 0) #define duk_uri_error_va(ctx,fmt,ap) \ (duk_error_va_raw((ctx), (duk_errcode_t) DUK_ERR_URI_ERROR, (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), (fmt), (ap)), (duk_ret_t) 0) /* * Other state related functions */ DUK_EXTERNAL_DECL duk_bool_t duk_is_strict_call(duk_context *ctx); DUK_EXTERNAL_DECL duk_bool_t duk_is_constructor_call(duk_context *ctx); /* * Stack management */ DUK_EXTERNAL_DECL duk_idx_t duk_normalize_index(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_idx_t duk_require_normalize_index(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_valid_index(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_require_valid_index(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_idx_t duk_get_top(duk_context *ctx); DUK_EXTERNAL_DECL void duk_set_top(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_idx_t duk_get_top_index(duk_context *ctx); DUK_EXTERNAL_DECL duk_idx_t duk_require_top_index(duk_context *ctx); /* Although extra/top could be an unsigned type here, using a signed type * makes the API more robust to calling code calculation errors or corner * cases (where caller might occasionally come up with negative values). * Negative values are treated as zero, which is better than casting them * to a large unsigned number. (This principle is used elsewhere in the * API too.) */ DUK_EXTERNAL_DECL duk_bool_t duk_check_stack(duk_context *ctx, duk_idx_t extra); DUK_EXTERNAL_DECL void duk_require_stack(duk_context *ctx, duk_idx_t extra); DUK_EXTERNAL_DECL duk_bool_t duk_check_stack_top(duk_context *ctx, duk_idx_t top); DUK_EXTERNAL_DECL void duk_require_stack_top(duk_context *ctx, duk_idx_t top); /* * Stack manipulation (other than push/pop) */ DUK_EXTERNAL_DECL void duk_swap(duk_context *ctx, duk_idx_t idx1, duk_idx_t idx2); DUK_EXTERNAL_DECL void duk_swap_top(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_dup(duk_context *ctx, duk_idx_t from_idx); DUK_EXTERNAL_DECL void duk_dup_top(duk_context *ctx); DUK_EXTERNAL_DECL void duk_insert(duk_context *ctx, duk_idx_t to_idx); DUK_EXTERNAL_DECL void duk_pull(duk_context *ctx, duk_idx_t from_idx); DUK_EXTERNAL_DECL void duk_replace(duk_context *ctx, duk_idx_t to_idx); DUK_EXTERNAL_DECL void duk_copy(duk_context *ctx, duk_idx_t from_idx, duk_idx_t to_idx); DUK_EXTERNAL_DECL void duk_remove(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_xcopymove_raw(duk_context *to_ctx, duk_context *from_ctx, duk_idx_t count, duk_bool_t is_copy); #define duk_xmove_top(to_ctx,from_ctx,count) \ duk_xcopymove_raw((to_ctx), (from_ctx), (count), 0 /*is_copy*/) #define duk_xcopy_top(to_ctx,from_ctx,count) \ duk_xcopymove_raw((to_ctx), (from_ctx), (count), 1 /*is_copy*/) /* * Push operations * * Push functions return the absolute (relative to bottom of frame) * position of the pushed value for convenience. * * Note: duk_dup() is technically a push. */ DUK_EXTERNAL_DECL void duk_push_undefined(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_null(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_boolean(duk_context *ctx, duk_bool_t val); DUK_EXTERNAL_DECL void duk_push_true(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_false(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_number(duk_context *ctx, duk_double_t val); DUK_EXTERNAL_DECL void duk_push_nan(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_int(duk_context *ctx, duk_int_t val); DUK_EXTERNAL_DECL void duk_push_uint(duk_context *ctx, duk_uint_t val); DUK_EXTERNAL_DECL const char *duk_push_string(duk_context *ctx, const char *str); DUK_EXTERNAL_DECL const char *duk_push_lstring(duk_context *ctx, const char *str, duk_size_t len); DUK_EXTERNAL_DECL void duk_push_pointer(duk_context *ctx, void *p); DUK_EXTERNAL_DECL const char *duk_push_sprintf(duk_context *ctx, const char *fmt, ...); DUK_EXTERNAL_DECL const char *duk_push_vsprintf(duk_context *ctx, const char *fmt, va_list ap); /* duk_push_literal() may evaluate its argument (a C string literal) more than * once on purpose. When speed is preferred, sizeof() avoids an unnecessary * strlen() at runtime. Sizeof("foo") == 4, so subtract 1. The argument * must be non-NULL and should not contain internal NUL characters as the * behavior will then depend on config options. */ #if defined(DUK_USE_PREFER_SIZE) #define duk_push_literal(ctx,cstring) duk_push_string((ctx), (cstring)) #else DUK_EXTERNAL_DECL const char *duk_push_literal_raw(duk_context *ctx, const char *str, duk_size_t len); #define duk_push_literal(ctx,cstring) duk_push_literal_raw((ctx), (cstring), sizeof((cstring)) - 1U) #endif DUK_EXTERNAL_DECL void duk_push_this(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_new_target(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_current_function(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_current_thread(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_global_object(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_heap_stash(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_global_stash(duk_context *ctx); DUK_EXTERNAL_DECL void duk_push_thread_stash(duk_context *ctx, duk_context *target_ctx); DUK_EXTERNAL_DECL duk_idx_t duk_push_object(duk_context *ctx); DUK_EXTERNAL_DECL duk_idx_t duk_push_bare_object(duk_context *ctx); DUK_EXTERNAL_DECL duk_idx_t duk_push_array(duk_context *ctx); DUK_EXTERNAL_DECL duk_idx_t duk_push_bare_array(duk_context *ctx); DUK_EXTERNAL_DECL duk_idx_t duk_push_c_function(duk_context *ctx, duk_c_function func, duk_idx_t nargs); DUK_EXTERNAL_DECL duk_idx_t duk_push_c_lightfunc(duk_context *ctx, duk_c_function func, duk_idx_t nargs, duk_idx_t length, duk_int_t magic); DUK_EXTERNAL_DECL duk_idx_t duk_push_thread_raw(duk_context *ctx, duk_uint_t flags); DUK_EXTERNAL_DECL duk_idx_t duk_push_proxy(duk_context *ctx, duk_uint_t proxy_flags); #define duk_push_thread(ctx) \ duk_push_thread_raw((ctx), 0 /*flags*/) #define duk_push_thread_new_globalenv(ctx) \ duk_push_thread_raw((ctx), DUK_THREAD_NEW_GLOBAL_ENV /*flags*/) DUK_EXTERNAL_DECL duk_idx_t duk_push_error_object_raw(duk_context *ctx, duk_errcode_t err_code, const char *filename, duk_int_t line, const char *fmt, ...); #if defined(DUK_API_VARIADIC_MACROS) #define duk_push_error_object(ctx,err_code,...) \ duk_push_error_object_raw((ctx), (err_code), (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__) #else DUK_EXTERNAL_DECL duk_idx_t duk_push_error_object_stash(duk_context *ctx, duk_errcode_t err_code, const char *fmt, ...); /* Note: parentheses are required so that the comma expression works in assignments. */ #define duk_push_error_object \ (duk_api_global_filename = (const char *) (DUK_FILE_MACRO), \ duk_api_global_line = (duk_int_t) (DUK_LINE_MACRO), \ duk_push_error_object_stash) /* last value is func pointer, arguments follow in parens */ #endif DUK_EXTERNAL_DECL duk_idx_t duk_push_error_object_va_raw(duk_context *ctx, duk_errcode_t err_code, const char *filename, duk_int_t line, const char *fmt, va_list ap); #define duk_push_error_object_va(ctx,err_code,fmt,ap) \ duk_push_error_object_va_raw((ctx), (err_code), (const char *) (DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), (fmt), (ap)) #define DUK_BUF_FLAG_DYNAMIC (1 << 0) /* internal flag: dynamic buffer */ #define DUK_BUF_FLAG_EXTERNAL (1 << 1) /* internal flag: external buffer */ #define DUK_BUF_FLAG_NOZERO (1 << 2) /* internal flag: don't zero allocated buffer */ DUK_EXTERNAL_DECL void *duk_push_buffer_raw(duk_context *ctx, duk_size_t size, duk_small_uint_t flags); #define duk_push_buffer(ctx,size,dynamic) \ duk_push_buffer_raw((ctx), (size), (dynamic) ? DUK_BUF_FLAG_DYNAMIC : 0) #define duk_push_fixed_buffer(ctx,size) \ duk_push_buffer_raw((ctx), (size), 0 /*flags*/) #define duk_push_dynamic_buffer(ctx,size) \ duk_push_buffer_raw((ctx), (size), DUK_BUF_FLAG_DYNAMIC /*flags*/) #define duk_push_external_buffer(ctx) \ ((void) duk_push_buffer_raw((ctx), 0, DUK_BUF_FLAG_DYNAMIC | DUK_BUF_FLAG_EXTERNAL)) #define DUK_BUFOBJ_ARRAYBUFFER 0 #define DUK_BUFOBJ_NODEJS_BUFFER 1 #define DUK_BUFOBJ_DATAVIEW 2 #define DUK_BUFOBJ_INT8ARRAY 3 #define DUK_BUFOBJ_UINT8ARRAY 4 #define DUK_BUFOBJ_UINT8CLAMPEDARRAY 5 #define DUK_BUFOBJ_INT16ARRAY 6 #define DUK_BUFOBJ_UINT16ARRAY 7 #define DUK_BUFOBJ_INT32ARRAY 8 #define DUK_BUFOBJ_UINT32ARRAY 9 #define DUK_BUFOBJ_FLOAT32ARRAY 10 #define DUK_BUFOBJ_FLOAT64ARRAY 11 DUK_EXTERNAL_DECL void duk_push_buffer_object(duk_context *ctx, duk_idx_t idx_buffer, duk_size_t byte_offset, duk_size_t byte_length, duk_uint_t flags); DUK_EXTERNAL_DECL duk_idx_t duk_push_heapptr(duk_context *ctx, void *ptr); /* * Pop operations */ DUK_EXTERNAL_DECL void duk_pop(duk_context *ctx); DUK_EXTERNAL_DECL void duk_pop_n(duk_context *ctx, duk_idx_t count); DUK_EXTERNAL_DECL void duk_pop_2(duk_context *ctx); DUK_EXTERNAL_DECL void duk_pop_3(duk_context *ctx); /* * Type checks * * duk_is_none(), which would indicate whether index it outside of stack, * is not needed; duk_is_valid_index() gives the same information. */ DUK_EXTERNAL_DECL duk_int_t duk_get_type(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_check_type(duk_context *ctx, duk_idx_t idx, duk_int_t type); DUK_EXTERNAL_DECL duk_uint_t duk_get_type_mask(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_check_type_mask(duk_context *ctx, duk_idx_t idx, duk_uint_t mask); DUK_EXTERNAL_DECL duk_bool_t duk_is_undefined(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_null(duk_context *ctx, duk_idx_t idx); #define duk_is_null_or_undefined(ctx, idx) \ ((duk_get_type_mask((ctx), (idx)) & (DUK_TYPE_MASK_NULL | DUK_TYPE_MASK_UNDEFINED)) ? 1 : 0) DUK_EXTERNAL_DECL duk_bool_t duk_is_boolean(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_number(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_nan(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_string(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_object(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_buffer(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_buffer_data(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_pointer(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_lightfunc(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_symbol(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_array(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_function(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_c_function(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_ecmascript_function(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_bound_function(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_thread(duk_context *ctx, duk_idx_t idx); #define duk_is_callable(ctx,idx) \ duk_is_function((ctx), (idx)) DUK_EXTERNAL_DECL duk_bool_t duk_is_constructable(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_dynamic_buffer(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_fixed_buffer(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_is_external_buffer(duk_context *ctx, duk_idx_t idx); /* Buffers and lightfuncs are not considered primitive because they mimic * objects and e.g. duk_to_primitive() will coerce them instead of returning * them as is. Symbols are represented as strings internally. */ #define duk_is_primitive(ctx,idx) \ duk_check_type_mask((ctx), (idx), DUK_TYPE_MASK_UNDEFINED | \ DUK_TYPE_MASK_NULL | \ DUK_TYPE_MASK_BOOLEAN | \ DUK_TYPE_MASK_NUMBER | \ DUK_TYPE_MASK_STRING | \ DUK_TYPE_MASK_POINTER) /* Symbols are object coercible, covered by DUK_TYPE_MASK_STRING. */ #define duk_is_object_coercible(ctx,idx) \ duk_check_type_mask((ctx), (idx), DUK_TYPE_MASK_BOOLEAN | \ DUK_TYPE_MASK_NUMBER | \ DUK_TYPE_MASK_STRING | \ DUK_TYPE_MASK_OBJECT | \ DUK_TYPE_MASK_BUFFER | \ DUK_TYPE_MASK_POINTER | \ DUK_TYPE_MASK_LIGHTFUNC) DUK_EXTERNAL_DECL duk_errcode_t duk_get_error_code(duk_context *ctx, duk_idx_t idx); #define duk_is_error(ctx,idx) \ (duk_get_error_code((ctx), (idx)) != 0) #define duk_is_eval_error(ctx,idx) \ (duk_get_error_code((ctx), (idx)) == DUK_ERR_EVAL_ERROR) #define duk_is_range_error(ctx,idx) \ (duk_get_error_code((ctx), (idx)) == DUK_ERR_RANGE_ERROR) #define duk_is_reference_error(ctx,idx) \ (duk_get_error_code((ctx), (idx)) == DUK_ERR_REFERENCE_ERROR) #define duk_is_syntax_error(ctx,idx) \ (duk_get_error_code((ctx), (idx)) == DUK_ERR_SYNTAX_ERROR) #define duk_is_type_error(ctx,idx) \ (duk_get_error_code((ctx), (idx)) == DUK_ERR_TYPE_ERROR) #define duk_is_uri_error(ctx,idx) \ (duk_get_error_code((ctx), (idx)) == DUK_ERR_URI_ERROR) /* * Get operations: no coercion, returns default value for invalid * indices and invalid value types. * * duk_get_undefined() and duk_get_null() would be pointless and * are not included. */ DUK_EXTERNAL_DECL duk_bool_t duk_get_boolean(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_double_t duk_get_number(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_int_t duk_get_int(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_uint_t duk_get_uint(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL const char *duk_get_string(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL const char *duk_get_lstring(duk_context *ctx, duk_idx_t idx, duk_size_t *out_len); DUK_EXTERNAL_DECL void *duk_get_buffer(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size); DUK_EXTERNAL_DECL void *duk_get_buffer_data(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size); DUK_EXTERNAL_DECL void *duk_get_pointer(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_c_function duk_get_c_function(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_context *duk_get_context(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void *duk_get_heapptr(duk_context *ctx, duk_idx_t idx); /* * Get-with-explicit default operations: like get operations but with an * explicit default value. */ DUK_EXTERNAL_DECL duk_bool_t duk_get_boolean_default(duk_context *ctx, duk_idx_t idx, duk_bool_t def_value); DUK_EXTERNAL_DECL duk_double_t duk_get_number_default(duk_context *ctx, duk_idx_t idx, duk_double_t def_value); DUK_EXTERNAL_DECL duk_int_t duk_get_int_default(duk_context *ctx, duk_idx_t idx, duk_int_t def_value); DUK_EXTERNAL_DECL duk_uint_t duk_get_uint_default(duk_context *ctx, duk_idx_t idx, duk_uint_t def_value); DUK_EXTERNAL_DECL const char *duk_get_string_default(duk_context *ctx, duk_idx_t idx, const char *def_value); DUK_EXTERNAL_DECL const char *duk_get_lstring_default(duk_context *ctx, duk_idx_t idx, duk_size_t *out_len, const char *def_ptr, duk_size_t def_len); DUK_EXTERNAL_DECL void *duk_get_buffer_default(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size, void *def_ptr, duk_size_t def_len); DUK_EXTERNAL_DECL void *duk_get_buffer_data_default(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size, void *def_ptr, duk_size_t def_len); DUK_EXTERNAL_DECL void *duk_get_pointer_default(duk_context *ctx, duk_idx_t idx, void *def_value); DUK_EXTERNAL_DECL duk_c_function duk_get_c_function_default(duk_context *ctx, duk_idx_t idx, duk_c_function def_value); DUK_EXTERNAL_DECL duk_context *duk_get_context_default(duk_context *ctx, duk_idx_t idx, duk_context *def_value); DUK_EXTERNAL_DECL void *duk_get_heapptr_default(duk_context *ctx, duk_idx_t idx, void *def_value); /* * Opt operations: like require operations but with an explicit default value * when value is undefined or index is invalid, null and non-matching types * cause a TypeError. */ DUK_EXTERNAL_DECL duk_bool_t duk_opt_boolean(duk_context *ctx, duk_idx_t idx, duk_bool_t def_value); DUK_EXTERNAL_DECL duk_double_t duk_opt_number(duk_context *ctx, duk_idx_t idx, duk_double_t def_value); DUK_EXTERNAL_DECL duk_int_t duk_opt_int(duk_context *ctx, duk_idx_t idx, duk_int_t def_value); DUK_EXTERNAL_DECL duk_uint_t duk_opt_uint(duk_context *ctx, duk_idx_t idx, duk_uint_t def_value); DUK_EXTERNAL_DECL const char *duk_opt_string(duk_context *ctx, duk_idx_t idx, const char *def_ptr); DUK_EXTERNAL_DECL const char *duk_opt_lstring(duk_context *ctx, duk_idx_t idx, duk_size_t *out_len, const char *def_ptr, duk_size_t def_len); DUK_EXTERNAL_DECL void *duk_opt_buffer(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size, void *def_ptr, duk_size_t def_size); DUK_EXTERNAL_DECL void *duk_opt_buffer_data(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size, void *def_ptr, duk_size_t def_size); DUK_EXTERNAL_DECL void *duk_opt_pointer(duk_context *ctx, duk_idx_t idx, void *def_value); DUK_EXTERNAL_DECL duk_c_function duk_opt_c_function(duk_context *ctx, duk_idx_t idx, duk_c_function def_value); DUK_EXTERNAL_DECL duk_context *duk_opt_context(duk_context *ctx, duk_idx_t idx, duk_context *def_value); DUK_EXTERNAL_DECL void *duk_opt_heapptr(duk_context *ctx, duk_idx_t idx, void *def_value); /* * Require operations: no coercion, throw error if index or type * is incorrect. No defaulting. */ #define duk_require_type_mask(ctx,idx,mask) \ ((void) duk_check_type_mask((ctx), (idx), (mask) | DUK_TYPE_MASK_THROW)) DUK_EXTERNAL_DECL void duk_require_undefined(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_require_null(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_require_boolean(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_double_t duk_require_number(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_int_t duk_require_int(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_uint_t duk_require_uint(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL const char *duk_require_string(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL const char *duk_require_lstring(duk_context *ctx, duk_idx_t idx, duk_size_t *out_len); DUK_EXTERNAL_DECL void duk_require_object(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void *duk_require_buffer(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size); DUK_EXTERNAL_DECL void *duk_require_buffer_data(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size); DUK_EXTERNAL_DECL void *duk_require_pointer(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_c_function duk_require_c_function(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_context *duk_require_context(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_require_function(duk_context *ctx, duk_idx_t idx); #define duk_require_callable(ctx,idx) \ duk_require_function((ctx), (idx)) DUK_EXTERNAL_DECL void duk_require_constructor_call(duk_context *ctx); DUK_EXTERNAL_DECL void duk_require_constructable(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void *duk_require_heapptr(duk_context *ctx, duk_idx_t idx); /* Symbols are object coercible and covered by DUK_TYPE_MASK_STRING. */ #define duk_require_object_coercible(ctx,idx) \ ((void) duk_check_type_mask((ctx), (idx), DUK_TYPE_MASK_BOOLEAN | \ DUK_TYPE_MASK_NUMBER | \ DUK_TYPE_MASK_STRING | \ DUK_TYPE_MASK_OBJECT | \ DUK_TYPE_MASK_BUFFER | \ DUK_TYPE_MASK_POINTER | \ DUK_TYPE_MASK_LIGHTFUNC | \ DUK_TYPE_MASK_THROW)) /* * Coercion operations: in-place coercion, return coerced value where * applicable. If index is invalid, throw error. Some coercions may * throw an expected error (e.g. from a toString() or valueOf() call) * or an internal error (e.g. from out of memory). */ DUK_EXTERNAL_DECL void duk_to_undefined(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_to_null(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_bool_t duk_to_boolean(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_double_t duk_to_number(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_int_t duk_to_int(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_uint_t duk_to_uint(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_int32_t duk_to_int32(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_uint32_t duk_to_uint32(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_uint16_t duk_to_uint16(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL const char *duk_to_string(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL const char *duk_to_lstring(duk_context *ctx, duk_idx_t idx, duk_size_t *out_len); DUK_EXTERNAL_DECL void *duk_to_buffer_raw(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size, duk_uint_t flags); DUK_EXTERNAL_DECL void *duk_to_pointer(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_to_object(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_to_primitive(duk_context *ctx, duk_idx_t idx, duk_int_t hint); #define DUK_BUF_MODE_FIXED 0 /* internal: request fixed buffer result */ #define DUK_BUF_MODE_DYNAMIC 1 /* internal: request dynamic buffer result */ #define DUK_BUF_MODE_DONTCARE 2 /* internal: don't care about fixed/dynamic nature */ #define duk_to_buffer(ctx,idx,out_size) \ duk_to_buffer_raw((ctx), (idx), (out_size), DUK_BUF_MODE_DONTCARE) #define duk_to_fixed_buffer(ctx,idx,out_size) \ duk_to_buffer_raw((ctx), (idx), (out_size), DUK_BUF_MODE_FIXED) #define duk_to_dynamic_buffer(ctx,idx,out_size) \ duk_to_buffer_raw((ctx), (idx), (out_size), DUK_BUF_MODE_DYNAMIC) /* safe variants of a few coercion operations */ DUK_EXTERNAL_DECL const char *duk_safe_to_lstring(duk_context *ctx, duk_idx_t idx, duk_size_t *out_len); DUK_EXTERNAL_DECL const char *duk_to_stacktrace(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL const char *duk_safe_to_stacktrace(duk_context *ctx, duk_idx_t idx); #define duk_safe_to_string(ctx,idx) \ duk_safe_to_lstring((ctx), (idx), NULL) /* * Value length */ DUK_EXTERNAL_DECL duk_size_t duk_get_length(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_set_length(duk_context *ctx, duk_idx_t idx, duk_size_t len); #if 0 /* duk_require_length()? */ /* duk_opt_length()? */ #endif /* * Misc conversion */ DUK_EXTERNAL_DECL const char *duk_base64_encode(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_base64_decode(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL const char *duk_hex_encode(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_hex_decode(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL const char *duk_json_encode(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_json_decode(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_cbor_encode(duk_context *ctx, duk_idx_t idx, duk_uint_t encode_flags); DUK_EXTERNAL_DECL void duk_cbor_decode(duk_context *ctx, duk_idx_t idx, duk_uint_t decode_flags); DUK_EXTERNAL_DECL const char *duk_buffer_to_string(duk_context *ctx, duk_idx_t idx); /* * Buffer */ DUK_EXTERNAL_DECL void *duk_resize_buffer(duk_context *ctx, duk_idx_t idx, duk_size_t new_size); DUK_EXTERNAL_DECL void *duk_steal_buffer(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size); DUK_EXTERNAL_DECL void duk_config_buffer(duk_context *ctx, duk_idx_t idx, void *ptr, duk_size_t len); /* * Property access * * The basic function assumes key is on stack. The _(l)string variant takes * a C string as a property name; the _literal variant takes a C literal. * The _index variant takes an array index as a property name (e.g. 123 is * equivalent to the key "123"). The _heapptr variant takes a raw, borrowed * heap pointer. */ DUK_EXTERNAL_DECL duk_bool_t duk_get_prop(duk_context *ctx, duk_idx_t obj_idx); DUK_EXTERNAL_DECL duk_bool_t duk_get_prop_string(duk_context *ctx, duk_idx_t obj_idx, const char *key); DUK_EXTERNAL_DECL duk_bool_t duk_get_prop_lstring(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len); #if defined(DUK_USE_PREFER_SIZE) #define duk_get_prop_literal(ctx,obj_idx,key) duk_get_prop_string((ctx), (obj_idx), (key)) #else DUK_EXTERNAL_DECL duk_bool_t duk_get_prop_literal_raw(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len); #define duk_get_prop_literal(ctx,obj_idx,key) duk_get_prop_literal_raw((ctx), (obj_idx), (key), sizeof((key)) - 1U) #endif DUK_EXTERNAL_DECL duk_bool_t duk_get_prop_index(duk_context *ctx, duk_idx_t obj_idx, duk_uarridx_t arr_idx); DUK_EXTERNAL_DECL duk_bool_t duk_get_prop_heapptr(duk_context *ctx, duk_idx_t obj_idx, void *ptr); DUK_EXTERNAL_DECL duk_bool_t duk_put_prop(duk_context *ctx, duk_idx_t obj_idx); DUK_EXTERNAL_DECL duk_bool_t duk_put_prop_string(duk_context *ctx, duk_idx_t obj_idx, const char *key); DUK_EXTERNAL_DECL duk_bool_t duk_put_prop_lstring(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len); #if defined(DUK_USE_PREFER_SIZE) #define duk_put_prop_literal(ctx,obj_idx,key) duk_put_prop_string((ctx), (obj_idx), (key)) #else DUK_EXTERNAL_DECL duk_bool_t duk_put_prop_literal_raw(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len); #define duk_put_prop_literal(ctx,obj_idx,key) duk_put_prop_literal_raw((ctx), (obj_idx), (key), sizeof((key)) - 1U) #endif DUK_EXTERNAL_DECL duk_bool_t duk_put_prop_index(duk_context *ctx, duk_idx_t obj_idx, duk_uarridx_t arr_idx); DUK_EXTERNAL_DECL duk_bool_t duk_put_prop_heapptr(duk_context *ctx, duk_idx_t obj_idx, void *ptr); DUK_EXTERNAL_DECL duk_bool_t duk_del_prop(duk_context *ctx, duk_idx_t obj_idx); DUK_EXTERNAL_DECL duk_bool_t duk_del_prop_string(duk_context *ctx, duk_idx_t obj_idx, const char *key); DUK_EXTERNAL_DECL duk_bool_t duk_del_prop_lstring(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len); #if defined(DUK_USE_PREFER_SIZE) #define duk_del_prop_literal(ctx,obj_idx,key) duk_del_prop_string((ctx), (obj_idx), (key)) #else DUK_EXTERNAL_DECL duk_bool_t duk_del_prop_literal_raw(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len); #define duk_del_prop_literal(ctx,obj_idx,key) duk_del_prop_literal_raw((ctx), (obj_idx), (key), sizeof((key)) - 1U) #endif DUK_EXTERNAL_DECL duk_bool_t duk_del_prop_index(duk_context *ctx, duk_idx_t obj_idx, duk_uarridx_t arr_idx); DUK_EXTERNAL_DECL duk_bool_t duk_del_prop_heapptr(duk_context *ctx, duk_idx_t obj_idx, void *ptr); DUK_EXTERNAL_DECL duk_bool_t duk_has_prop(duk_context *ctx, duk_idx_t obj_idx); DUK_EXTERNAL_DECL duk_bool_t duk_has_prop_string(duk_context *ctx, duk_idx_t obj_idx, const char *key); DUK_EXTERNAL_DECL duk_bool_t duk_has_prop_lstring(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len); #if defined(DUK_USE_PREFER_SIZE) #define duk_has_prop_literal(ctx,obj_idx,key) duk_has_prop_string((ctx), (obj_idx), (key)) #else DUK_EXTERNAL_DECL duk_bool_t duk_has_prop_literal_raw(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len); #define duk_has_prop_literal(ctx,obj_idx,key) duk_has_prop_literal_raw((ctx), (obj_idx), (key), sizeof((key)) - 1U) #endif DUK_EXTERNAL_DECL duk_bool_t duk_has_prop_index(duk_context *ctx, duk_idx_t obj_idx, duk_uarridx_t arr_idx); DUK_EXTERNAL_DECL duk_bool_t duk_has_prop_heapptr(duk_context *ctx, duk_idx_t obj_idx, void *ptr); DUK_EXTERNAL_DECL void duk_get_prop_desc(duk_context *ctx, duk_idx_t obj_idx, duk_uint_t flags); DUK_EXTERNAL_DECL void duk_def_prop(duk_context *ctx, duk_idx_t obj_idx, duk_uint_t flags); DUK_EXTERNAL_DECL duk_bool_t duk_get_global_string(duk_context *ctx, const char *key); DUK_EXTERNAL_DECL duk_bool_t duk_get_global_lstring(duk_context *ctx, const char *key, duk_size_t key_len); #if defined(DUK_USE_PREFER_SIZE) #define duk_get_global_literal(ctx,key) duk_get_global_string((ctx), (key)) #else DUK_EXTERNAL_DECL duk_bool_t duk_get_global_literal_raw(duk_context *ctx, const char *key, duk_size_t key_len); #define duk_get_global_literal(ctx,key) duk_get_global_literal_raw((ctx), (key), sizeof((key)) - 1U) #endif DUK_EXTERNAL_DECL duk_bool_t duk_get_global_heapptr(duk_context *ctx, void *ptr); DUK_EXTERNAL_DECL duk_bool_t duk_put_global_string(duk_context *ctx, const char *key); DUK_EXTERNAL_DECL duk_bool_t duk_put_global_lstring(duk_context *ctx, const char *key, duk_size_t key_len); #if defined(DUK_USE_PREFER_SIZE) #define duk_put_global_literal(ctx,key) duk_put_global_string((ctx), (key)) #else DUK_EXTERNAL_DECL duk_bool_t duk_put_global_literal_raw(duk_context *ctx, const char *key, duk_size_t key_len); #define duk_put_global_literal(ctx,key) duk_put_global_literal_raw((ctx), (key), sizeof((key)) - 1U) #endif DUK_EXTERNAL_DECL duk_bool_t duk_put_global_heapptr(duk_context *ctx, void *ptr); /* * Inspection */ DUK_EXTERNAL_DECL void duk_inspect_value(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_inspect_callstack_entry(duk_context *ctx, duk_int_t level); /* * Object prototype */ DUK_EXTERNAL_DECL void duk_get_prototype(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_set_prototype(duk_context *ctx, duk_idx_t idx); /* * Object finalizer */ DUK_EXTERNAL_DECL void duk_get_finalizer(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_set_finalizer(duk_context *ctx, duk_idx_t idx); /* * Global object */ DUK_EXTERNAL_DECL void duk_set_global_object(duk_context *ctx); /* * Duktape/C function magic value */ DUK_EXTERNAL_DECL duk_int_t duk_get_magic(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL void duk_set_magic(duk_context *ctx, duk_idx_t idx, duk_int_t magic); DUK_EXTERNAL_DECL duk_int_t duk_get_current_magic(duk_context *ctx); /* * Module helpers: put multiple function or constant properties */ DUK_EXTERNAL_DECL void duk_put_function_list(duk_context *ctx, duk_idx_t obj_idx, const duk_function_list_entry *funcs); DUK_EXTERNAL_DECL void duk_put_number_list(duk_context *ctx, duk_idx_t obj_idx, const duk_number_list_entry *numbers); /* * Object operations */ DUK_EXTERNAL_DECL void duk_compact(duk_context *ctx, duk_idx_t obj_idx); DUK_EXTERNAL_DECL void duk_enum(duk_context *ctx, duk_idx_t obj_idx, duk_uint_t enum_flags); DUK_EXTERNAL_DECL duk_bool_t duk_next(duk_context *ctx, duk_idx_t enum_idx, duk_bool_t get_value); DUK_EXTERNAL_DECL void duk_seal(duk_context *ctx, duk_idx_t obj_idx); DUK_EXTERNAL_DECL void duk_freeze(duk_context *ctx, duk_idx_t obj_idx); /* * String manipulation */ DUK_EXTERNAL_DECL void duk_concat(duk_context *ctx, duk_idx_t count); DUK_EXTERNAL_DECL void duk_join(duk_context *ctx, duk_idx_t count); DUK_EXTERNAL_DECL void duk_decode_string(duk_context *ctx, duk_idx_t idx, duk_decode_char_function callback, void *udata); DUK_EXTERNAL_DECL void duk_map_string(duk_context *ctx, duk_idx_t idx, duk_map_char_function callback, void *udata); DUK_EXTERNAL_DECL void duk_substring(duk_context *ctx, duk_idx_t idx, duk_size_t start_char_offset, duk_size_t end_char_offset); DUK_EXTERNAL_DECL void duk_trim(duk_context *ctx, duk_idx_t idx); DUK_EXTERNAL_DECL duk_codepoint_t duk_char_code_at(duk_context *ctx, duk_idx_t idx, duk_size_t char_offset); /* * ECMAScript operators */ DUK_EXTERNAL_DECL duk_bool_t duk_equals(duk_context *ctx, duk_idx_t idx1, duk_idx_t idx2); DUK_EXTERNAL_DECL duk_bool_t duk_strict_equals(duk_context *ctx, duk_idx_t idx1, duk_idx_t idx2); DUK_EXTERNAL_DECL duk_bool_t duk_samevalue(duk_context *ctx, duk_idx_t idx1, duk_idx_t idx2); DUK_EXTERNAL_DECL duk_bool_t duk_instanceof(duk_context *ctx, duk_idx_t idx1, duk_idx_t idx2); /* * Random */ DUK_EXTERNAL_DECL duk_double_t duk_random(duk_context *ctx); /* * Function (method) calls */ DUK_EXTERNAL_DECL void duk_call(duk_context *ctx, duk_idx_t nargs); DUK_EXTERNAL_DECL void duk_call_method(duk_context *ctx, duk_idx_t nargs); DUK_EXTERNAL_DECL void duk_call_prop(duk_context *ctx, duk_idx_t obj_idx, duk_idx_t nargs); DUK_EXTERNAL_DECL duk_int_t duk_pcall(duk_context *ctx, duk_idx_t nargs); DUK_EXTERNAL_DECL duk_int_t duk_pcall_method(duk_context *ctx, duk_idx_t nargs); DUK_EXTERNAL_DECL duk_int_t duk_pcall_prop(duk_context *ctx, duk_idx_t obj_idx, duk_idx_t nargs); DUK_EXTERNAL_DECL void duk_new(duk_context *ctx, duk_idx_t nargs); DUK_EXTERNAL_DECL duk_int_t duk_pnew(duk_context *ctx, duk_idx_t nargs); DUK_EXTERNAL_DECL duk_int_t duk_safe_call(duk_context *ctx, duk_safe_call_function func, void *udata, duk_idx_t nargs, duk_idx_t nrets); /* * Thread management */ /* There are currently no native functions to yield/resume, due to the internal * limitations on coroutine handling. These will be added later. */ /* * Compilation and evaluation */ DUK_EXTERNAL_DECL duk_int_t duk_eval_raw(duk_context *ctx, const char *src_buffer, duk_size_t src_length, duk_uint_t flags); DUK_EXTERNAL_DECL duk_int_t duk_compile_raw(duk_context *ctx, const char *src_buffer, duk_size_t src_length, duk_uint_t flags); /* plain */ #define duk_eval(ctx) \ ((void) duk_eval_raw((ctx), NULL, 0, 1 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_NOFILENAME)) #define duk_eval_noresult(ctx) \ ((void) duk_eval_raw((ctx), NULL, 0, 1 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_NORESULT | DUK_COMPILE_NOFILENAME)) #define duk_peval(ctx) \ (duk_eval_raw((ctx), NULL, 0, 1 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOFILENAME)) #define duk_peval_noresult(ctx) \ (duk_eval_raw((ctx), NULL, 0, 1 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NORESULT | DUK_COMPILE_NOFILENAME)) #define duk_compile(ctx,flags) \ ((void) duk_compile_raw((ctx), NULL, 0, 2 /*args*/ | (flags))) #define duk_pcompile(ctx,flags) \ (duk_compile_raw((ctx), NULL, 0, 2 /*args*/ | (flags) | DUK_COMPILE_SAFE)) /* string */ #define duk_eval_string(ctx,src) \ ((void) duk_eval_raw((ctx), (src), 0, 0 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN | DUK_COMPILE_NOFILENAME)) #define duk_eval_string_noresult(ctx,src) \ ((void) duk_eval_raw((ctx), (src), 0, 0 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN | DUK_COMPILE_NORESULT | DUK_COMPILE_NOFILENAME)) #define duk_peval_string(ctx,src) \ (duk_eval_raw((ctx), (src), 0, 0 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN | DUK_COMPILE_NOFILENAME)) #define duk_peval_string_noresult(ctx,src) \ (duk_eval_raw((ctx), (src), 0, 0 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN | DUK_COMPILE_NORESULT | DUK_COMPILE_NOFILENAME)) #define duk_compile_string(ctx,flags,src) \ ((void) duk_compile_raw((ctx), (src), 0, 0 /*args*/ | (flags) | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN | DUK_COMPILE_NOFILENAME)) #define duk_compile_string_filename(ctx,flags,src) \ ((void) duk_compile_raw((ctx), (src), 0, 1 /*args*/ | (flags) | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN)) #define duk_pcompile_string(ctx,flags,src) \ (duk_compile_raw((ctx), (src), 0, 0 /*args*/ | (flags) | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN | DUK_COMPILE_NOFILENAME)) #define duk_pcompile_string_filename(ctx,flags,src) \ (duk_compile_raw((ctx), (src), 0, 1 /*args*/ | (flags) | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN)) /* lstring */ #define duk_eval_lstring(ctx,buf,len) \ ((void) duk_eval_raw((ctx), buf, len, 0 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_NOSOURCE | DUK_COMPILE_NOFILENAME)) #define duk_eval_lstring_noresult(ctx,buf,len) \ ((void) duk_eval_raw((ctx), buf, len, 0 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_NOSOURCE | DUK_COMPILE_NORESULT | DUK_COMPILE_NOFILENAME)) #define duk_peval_lstring(ctx,buf,len) \ (duk_eval_raw((ctx), buf, len, 0 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_NOSOURCE | DUK_COMPILE_SAFE | DUK_COMPILE_NOFILENAME)) #define duk_peval_lstring_noresult(ctx,buf,len) \ (duk_eval_raw((ctx), buf, len, 0 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_NORESULT | DUK_COMPILE_NOFILENAME)) #define duk_compile_lstring(ctx,flags,buf,len) \ ((void) duk_compile_raw((ctx), buf, len, 0 /*args*/ | (flags) | DUK_COMPILE_NOSOURCE | DUK_COMPILE_NOFILENAME)) #define duk_compile_lstring_filename(ctx,flags,buf,len) \ ((void) duk_compile_raw((ctx), buf, len, 1 /*args*/ | (flags) | DUK_COMPILE_NOSOURCE)) #define duk_pcompile_lstring(ctx,flags,buf,len) \ (duk_compile_raw((ctx), buf, len, 0 /*args*/ | (flags) | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_NOFILENAME)) #define duk_pcompile_lstring_filename(ctx,flags,buf,len) \ (duk_compile_raw((ctx), buf, len, 1 /*args*/ | (flags) | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE)) /* * Bytecode load/dump */ DUK_EXTERNAL_DECL void duk_dump_function(duk_context *ctx); DUK_EXTERNAL_DECL void duk_load_function(duk_context *ctx); /* * Debugging */ DUK_EXTERNAL_DECL void duk_push_context_dump(duk_context *ctx); /* * Debugger (debug protocol) */ DUK_EXTERNAL_DECL void duk_debugger_attach(duk_context *ctx, duk_debug_read_function read_cb, duk_debug_write_function write_cb, duk_debug_peek_function peek_cb, duk_debug_read_flush_function read_flush_cb, duk_debug_write_flush_function write_flush_cb, duk_debug_request_function request_cb, duk_debug_detached_function detached_cb, void *udata); DUK_EXTERNAL_DECL void duk_debugger_detach(duk_context *ctx); DUK_EXTERNAL_DECL void duk_debugger_cooperate(duk_context *ctx); DUK_EXTERNAL_DECL duk_bool_t duk_debugger_notify(duk_context *ctx, duk_idx_t nvalues); DUK_EXTERNAL_DECL void duk_debugger_pause(duk_context *ctx); /* * Time handling */ DUK_EXTERNAL_DECL duk_double_t duk_get_now(duk_context *ctx); DUK_EXTERNAL_DECL void duk_time_to_components(duk_context *ctx, duk_double_t timeval, duk_time_components *comp); DUK_EXTERNAL_DECL duk_double_t duk_components_to_time(duk_context *ctx, duk_time_components *comp); /* * Date provider related constants * * NOTE: These are "semi public" - you should only use these if you write * your own platform specific Date provider, see doc/datetime.rst. */ /* Millisecond count constants. */ #define DUK_DATE_MSEC_SECOND 1000L #define DUK_DATE_MSEC_MINUTE (60L * 1000L) #define DUK_DATE_MSEC_HOUR (60L * 60L * 1000L) #define DUK_DATE_MSEC_DAY (24L * 60L * 60L * 1000L) /* ECMAScript date range is 100 million days from Epoch: * > 100e6 * 24 * 60 * 60 * 1000 // 100M days in millisecs * 8640000000000000 * (= 8.64e15) */ #define DUK_DATE_MSEC_100M_DAYS (8.64e15) #define DUK_DATE_MSEC_100M_DAYS_LEEWAY (8.64e15 + 24 * 3600e3) /* ECMAScript year range: * > new Date(100e6 * 24 * 3600e3).toISOString() * '+275760-09-13T00:00:00.000Z' * > new Date(-100e6 * 24 * 3600e3).toISOString() * '-271821-04-20T00:00:00.000Z' */ #define DUK_DATE_MIN_ECMA_YEAR (-271821L) #define DUK_DATE_MAX_ECMA_YEAR 275760L /* Part indices for internal breakdowns. Part order from DUK_DATE_IDX_YEAR * to DUK_DATE_IDX_MILLISECOND matches argument ordering of ECMAScript API * calls (like Date constructor call). Some functions in duk_bi_date.c * depend on the specific ordering, so change with care. 16 bits are not * enough for all parts (year, specifically). * * Must be in-sync with genbuiltins.py. */ #define DUK_DATE_IDX_YEAR 0 /* year */ #define DUK_DATE_IDX_MONTH 1 /* month: 0 to 11 */ #define DUK_DATE_IDX_DAY 2 /* day within month: 0 to 30 */ #define DUK_DATE_IDX_HOUR 3 #define DUK_DATE_IDX_MINUTE 4 #define DUK_DATE_IDX_SECOND 5 #define DUK_DATE_IDX_MILLISECOND 6 #define DUK_DATE_IDX_WEEKDAY 7 /* weekday: 0 to 6, 0=sunday, 1=monday, etc */ #define DUK_DATE_IDX_NUM_PARTS 8 /* Internal API call flags, used for various functions in duk_bi_date.c. * Certain flags are used by only certain functions, but since the flags * don't overlap, a single flags value can be passed around to multiple * functions. * * The unused top bits of the flags field are also used to pass values * to helpers (duk__get_part_helper() and duk__set_part_helper()). * * Must be in-sync with genbuiltins.py. */ /* NOTE: when writing a Date provider you only need a few specific * flags from here, the rest are internal. Avoid using anything you * don't need. */ #define DUK_DATE_FLAG_NAN_TO_ZERO (1 << 0) /* timeval breakdown: internal time value NaN -> zero */ #define DUK_DATE_FLAG_NAN_TO_RANGE_ERROR (1 << 1) /* timeval breakdown: internal time value NaN -> RangeError (toISOString) */ #define DUK_DATE_FLAG_ONEBASED (1 << 2) /* timeval breakdown: convert month and day-of-month parts to one-based (default is zero-based) */ #define DUK_DATE_FLAG_EQUIVYEAR (1 << 3) /* timeval breakdown: replace year with equivalent year in the [1971,2037] range for DST calculations */ #define DUK_DATE_FLAG_LOCALTIME (1 << 4) /* convert time value to local time */ #define DUK_DATE_FLAG_SUB1900 (1 << 5) /* getter: subtract 1900 from year when getting year part */ #define DUK_DATE_FLAG_TOSTRING_DATE (1 << 6) /* include date part in string conversion result */ #define DUK_DATE_FLAG_TOSTRING_TIME (1 << 7) /* include time part in string conversion result */ #define DUK_DATE_FLAG_TOSTRING_LOCALE (1 << 8) /* use locale specific formatting if available */ #define DUK_DATE_FLAG_TIMESETTER (1 << 9) /* setter: call is a time setter (affects hour, min, sec, ms); otherwise date setter (affects year, month, day-in-month) */ #define DUK_DATE_FLAG_YEAR_FIXUP (1 << 10) /* setter: perform 2-digit year fixup (00...99 -> 1900...1999) */ #define DUK_DATE_FLAG_SEP_T (1 << 11) /* string conversion: use 'T' instead of ' ' as a separator */ #define DUK_DATE_FLAG_VALUE_SHIFT 12 /* additional values begin at bit 12 */ /* * ROM pointer compression */ /* Support array for ROM pointer compression. Only declared when ROM * pointer compression is active. */ #if defined(DUK_USE_ROM_OBJECTS) && defined(DUK_USE_HEAPPTR16) DUK_EXTERNAL_DECL const void * const duk_rom_compressed_pointers[]; #endif /* * C++ name mangling */ #if defined(__cplusplus) /* end 'extern "C"' wrapper */ } #endif /* * END PUBLIC API */ #endif /* DUKTAPE_H_INCLUDED */
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/duktape/duktape.h
C
apache-2.0
74,955
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <stdarg.h> #include <string.h> #include "amp_config.h" #include "aos_system.h" #include "amp_task.h" #include "amp_defines.h" #include "aos_hal_uart.h" #include "duktape.h" #include "be_inl.h" #include "repl.h" #ifdef AOS_COMP_CLI #include "aos/cli.h" #endif #define MOD_STR "REPL" #define RET_CHAR '\n' #define END_CHAR '\r' struct repl_status { int32_t inited; uint32_t num; int32_t echo_disabled; uint32_t bp; /* Buffer pointer */ char inbuf[REPL_INBUF_SIZE]; char *outbuf; int32_t his_idx; int32_t his_cur; char history[REPL_INBUF_SIZE]; }; static struct repl_status *g_repl = NULL; static uart_dev_t g_repl_uart; static char g_repl_tag[64] = {0}; static uint8_t g_repl_tag_len = 0; static int execute_finish = 0; static char repl_message[REPL_OUTBUF_SIZE] = {0}; static int32_t repl_getchar(char *inbuf) { int32_t ret = REPL_OK; uint32_t recv_size = 0; ret = aos_hal_uart_recv_II(&g_repl_uart, inbuf, 1, &recv_size, AOS_WAIT_FOREVER); if ((ret == 0) && (recv_size == 1)) { return recv_size; } else { return 0; } } static int32_t repl_putstr(char *msg) { if (msg[0] != 0) { aos_hal_uart_send(&g_repl_uart, (void *)msg, strlen(msg), 0xFFFFFFFFU); } return REPL_OK; } int32_t repl_printf(const char *buffer, ...) { va_list ap; int32_t sz, len; char *pos = NULL; memset(repl_message, 0, REPL_OUTBUF_SIZE); sz = 0; if (g_repl_tag_len > 0) { len = strlen(g_repl_tag); strncpy(repl_message, g_repl_tag, len); sz = len; } pos = repl_message + sz; va_start(ap, buffer); len = vsnprintf(pos, REPL_OUTBUF_SIZE - sz, buffer, ap); va_end(ap); if (len <= 0) { return REPL_OK; } repl_putstr(repl_message); return REPL_OK; } static duk_ret_t wrapped_compile_execute(duk_context *ctx, void *udata) { const char *src_data; duk_size_t src_len; duk_uint_t comp_flags; (void)udata; // duk_context *ctx = be_get_context(); /* XXX: Here it'd be nice to get some stats for the compilation result * when a suitable command line is given (e.g. code size, constant * count, function count. These are available internally but not through * the public API. */ /* Use duk_compile_lstring_filename() variant which avoids interning * the source code. This only really matters for low memory environments. */ /* [ ... bytecode_filename src_data src_len filename ] */ src_data = (const char *)duk_require_pointer(ctx, -3); src_len = (duk_size_t)duk_require_uint(ctx, -2); if (src_data != NULL && src_len >= 1 && src_data[0] == (char)0xbf) { /* Bytecode. */ void *buf; buf = duk_push_fixed_buffer(ctx, src_len); memcpy(buf, (const void *)src_data, src_len); duk_load_function(ctx); } else { /* Source code. */ comp_flags = DUK_COMPILE_SHEBANG; duk_compile_lstring_filename(ctx, comp_flags, src_data, src_len); } duk_push_global_object(ctx); /* 'this' binding */ duk_call_method(ctx, 0); /* * In interactive mode, write to stdout so output won't * interleave as easily. * * NOTE: the ToString() coercion may fail in some cases; * for instance, if you evaluate: * * ( {valueOf: function() {return {}}, * toString: function() {return {}}}); * * The error is: * * TypeError: coercion to primitive failed * duk_api.c:1420 * * These are handled now by the caller which also has stack * trace printing support. User code can print out errors * safely using duk_safe_to_string(). */ duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "dukFormat"); duk_dup(ctx, -3); /* duk_call(ctx, 1); /\* -> [ ... res stash formatted ] *\/ */ repl_printf("%s", duk_to_string(ctx, -1)); return 0; /* duk_safe_call() cleans up */ } static void repl_handle_input(void *inbuf) { int retval = 0; repl_printf("\r\n"); duk_context *ctx = be_get_context(); duk_push_pointer(ctx, inbuf); duk_push_uint(ctx, (duk_uint_t)strlen((char *)inbuf)); duk_push_string(ctx, "input"); int rc = duk_safe_call(ctx, wrapped_compile_execute, NULL /*udata*/, 3 /*nargs*/, 1 /*nret*/); if (rc != DUK_EXEC_SUCCESS) { /* in interactive mode, write to stdout */ repl_printf("%s", duk_safe_to_stacktrace(ctx, -1)); retval = -1; /* an error 'taints' the execution */ } else { duk_pop(ctx); } repl_printf("\r\n"); g_repl_tag[0] = '\x0'; g_repl_tag_len = 0; repl_printf(REPL_PROMPT); execute_finish = 1; } static void repl_history_input(void) { char *inbuf = g_repl->inbuf; int32_t charnum = strlen(g_repl->inbuf) + 1; int32_t his_cur = g_repl->his_cur; int32_t left_num = REPL_INBUF_SIZE - his_cur; char lastchar; int32_t tmp_idx; g_repl->his_idx = his_cur; if (left_num >= charnum) { tmp_idx = his_cur + charnum - 1; lastchar = g_repl->history[tmp_idx]; strncpy(&(g_repl->history[his_cur]), inbuf, charnum); } else { tmp_idx = (his_cur + charnum - 1) % REPL_INBUF_SIZE; lastchar = g_repl->history[tmp_idx]; strncpy(&(g_repl->history[his_cur]), inbuf, left_num); strncpy(&(g_repl->history[0]), inbuf + left_num, charnum - left_num); } tmp_idx = (tmp_idx + 1) % REPL_INBUF_SIZE; g_repl->his_cur = tmp_idx; /*overwrite*/ if ('\0' != lastchar) { while (g_repl->history[tmp_idx] != '\0') { g_repl->history[tmp_idx] = '\0'; tmp_idx = (tmp_idx + 1) % REPL_INBUF_SIZE; } } } static void repl_up_history(char *inaddr) { int index; int lastindex = 0; lastindex = g_repl->his_idx; index = (g_repl->his_idx - 1 + REPL_INBUF_SIZE) % REPL_INBUF_SIZE; while ((g_repl->history[index] == '\0') && (index != g_repl->his_idx)) { index = (index - 1 + REPL_INBUF_SIZE) % REPL_INBUF_SIZE; } if (index != g_repl->his_idx) { while (g_repl->history[index] != '\0') { index = (index - 1 + REPL_INBUF_SIZE) % REPL_INBUF_SIZE; } index = (index + 1) % REPL_INBUF_SIZE; } g_repl->his_idx = index; while (g_repl->history[lastindex] != '\0') { *inaddr++ = g_repl->history[lastindex]; lastindex = (lastindex + 1) % REPL_INBUF_SIZE; } *inaddr = '\0'; return; } static void repl_down_history(char *inaddr) { int index; int lastindex = 0; lastindex = g_repl->his_idx; index = g_repl->his_idx; while ((g_repl->history[index] != '\0')) { index = (index + 1) % REPL_INBUF_SIZE; } if (index != g_repl->his_idx) { while (g_repl->history[index] == '\0') { index = (index + 1) % REPL_INBUF_SIZE; } } g_repl->his_idx = index; while (g_repl->history[lastindex] != '\0') { *inaddr++ = g_repl->history[lastindex]; lastindex = (lastindex + 1) % REPL_INBUF_SIZE; } *inaddr = '\0'; return; } /** * @brief Get an input line * * @param[in/out] inbuf poiner to the input buffer * @param[out] bp the current buffer pointer * * @return 1 if there is input, 0 if the line should be ignored * */ static int32_t repl_get_input(char *inbuf, uint32_t *bp) { char c; int32_t esc = 0; int32_t key1 = -1; int32_t key2 = -1; uint8_t repl_tag_len = 0; if (inbuf == NULL) { repl_printf("input null\r\n"); return 0; } while (repl_getchar(&c) == 1) { if (c == RET_CHAR || c == END_CHAR) { /* end of input line */ inbuf[*bp] = '\0'; *bp = 0; if (repl_tag_len > 0) { g_repl_tag_len = repl_tag_len; repl_tag_len = 0; } return 1; } if (c == 0x1b) { /* escape sequence */ esc = 1; key1 = -1; key2 = -1; continue; } if (c == 0x3) { /* CTRL+C */ // task_to_cancel = debug_task_find("cpuusage"); // if (task_to_cancel != NULL) { // krhino_task_cancel(task_to_cancel); // } continue; } if (esc) { if (key1 < 0) { key1 = c; if (key1 != 0x5b) { /* not '[' */ inbuf[*bp] = 0x1b; (*bp)++; inbuf[*bp] = key1; (*bp)++; if (!g_repl->echo_disabled) { repl_printf("\x1b%c", key1); /* Ignore the cli tag */ } esc = 0; } continue; } if (key2 < 0) { key2 = c; if (key2 == 't') { g_repl_tag[0] = 0x1b; g_repl_tag[1] = key1; repl_tag_len = 2; } } if (key2 != 0x41 && key2 != 0x42 && key2 != 't') { if(key2 == 0x43 || key2 == 0x44) { /* TODO: LEFT/RIGHT key */ } /* not UP key, not DOWN key, not ESC_TAG */ inbuf[*bp] = 0x1b; (*bp)++; inbuf[*bp] = key1; (*bp)++; inbuf[*bp] = key2; (*bp)++; g_repl_tag[0] = '\x0'; repl_tag_len = 0; esc = 0; if (!g_repl->echo_disabled) { repl_printf("\x1b%c%c", key1, key2); } continue; } if (key2 == 0x41 || key2 == 0x42) { /* clear last input */ int backspace = *bp - 1; while(backspace && inbuf[backspace--]){ repl_printf("\b \b"); } /* UP or DWOWN key */ if (key2 == 0x41) { repl_up_history(inbuf); } else { repl_down_history(inbuf); } *bp = strlen(inbuf); g_repl_tag[0] = '\x0'; repl_tag_len = 0; esc = 0; repl_printf("\r" REPL_PROMPT "%s", inbuf); continue; } if (key2 == 't') { /* ESC_TAG */ if (repl_tag_len >= sizeof(g_repl_tag)) { g_repl_tag[0] = '\x0'; repl_tag_len = 0; esc = 0; amp_error(MOD_STR, "Error: cli tag buffer overflow\r\n"); continue; } g_repl_tag[repl_tag_len++] = c; if (c == 'm') { g_repl_tag[repl_tag_len++] = '\x0'; if (!g_repl->echo_disabled) { repl_printf("%s", g_repl_tag); } esc = 0; } continue; } } inbuf[*bp] = c; if ((c == 0x08) || (c == 0x7f)) { if (*bp > 0) { (*bp)--; if (!g_repl->echo_disabled) { repl_printf("%c %c", 0x08, 0x08); } } continue; } if (c == '\t') { // inbuf[*bp] = '\0'; continue; } if (!g_repl->echo_disabled) { repl_printf("%c", c); } (*bp)++; if (*bp >= REPL_INBUF_SIZE) { amp_error(MOD_STR, "Error: input buffer overflow\r\n"); repl_printf(REPL_PROMPT); *bp = 0; return 0; } } return 0; } /** * @brief Print out a bad command string * * @param[in] cmd_string the command string * * @return none * * @Note print including a hex representation of non-printable characters. * Non-printable characters show as "\0xXX". */ static void repl_print_bad_command(char *cmd_string) { if (cmd_string != NULL) { amp_error(MOD_STR, "command '%s' not found\r\n", cmd_string); } } /** * @brief Main CLI processing loop * * @param[in] data pointer to the process arguments * * @return none * * @Note Waits to receive a command buffer pointer from an input collector, * and then process. it must cleanup the buffer when done with it. * Input collectors handle their own lexical analysis and must pass complete * command lines to CLI. * */ void repl_main(void *data) { int32_t ret; #ifdef AOS_COMP_CLI aos_cli_suspend(); #endif while (1) { if (repl_get_input(g_repl->inbuf, &g_repl->bp) != 0) { if (strcmp(g_repl->inbuf, "exit") == 0) { break; } if (strlen(g_repl->inbuf) > 0) { repl_history_input(); amp_task_schedule_call(repl_handle_input, g_repl->inbuf); /* wait for js code execute finished */ execute_finish = 0; while(!execute_finish) { aos_msleep(100); } } else { repl_printf("\r\n"); g_repl_tag[0] = '\x0'; g_repl_tag_len = 0; repl_printf(REPL_PROMPT); } } } amp_warn(MOD_STR, "CLI exited\r\n"); aos_free(g_repl); g_repl = NULL; #ifdef AOS_COMP_CLI aos_cli_resume(); #endif return; } int32_t repl_init(void) { int32_t ret; aos_task_t repl_task; if (g_repl) { amp_debug(MOD_STR, "REPL is already inited!"); return REPL_OK; } g_repl = (struct repl_status *)aos_malloc(sizeof(struct repl_status)); if (g_repl == NULL) { return REPL_ERR_NOMEM; } g_repl_uart.port = AMP_REPL_UART_PORT; g_repl_uart.config.baud_rate = AMP_REPL_UART_BAUDRATE; g_repl_uart.config.data_width = DATA_WIDTH_8BIT; g_repl_uart.config.flow_control = FLOW_CONTROL_DISABLED; g_repl_uart.config.mode = MODE_TX_RX; g_repl_uart.config.parity = NO_PARITY; g_repl_uart.config.stop_bits = STOP_BITS_1; aos_hal_uart_init(&g_repl_uart); memset((void *)g_repl, 0, sizeof(struct repl_status)); if (aos_task_new_ext(&repl_task, "repl_task", repl_main, NULL, REPL_STACK_SIZE, AOS_DEFAULT_APP_PRI) != 0) { amp_error(MOD_STR, "Error: Failed to create cli thread: %d\r\n", ret); goto init_err; } g_repl->inited = 1; g_repl->echo_disabled = 0; amp_debug(MOD_STR, "REPL Enabled\r\n"); return REPL_OK; init_err: if (g_repl != NULL) { aos_free(g_repl); g_repl = NULL; } return ret; } #ifdef AOS_COMP_CLI void jsrepl_startup() { repl_init(); } /* reg args: fun, cmd, description*/ ALIOS_CLI_CMD_REGISTER(jsrepl_startup, jsrepl, "start js amp repl") #endif
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/repl.c
C
apache-2.0
15,761
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef __AMP_REPL_H #define __AMP_REPL_H #include <stdint.h> #include "duktape/duktape.h" #ifdef __cplusplus extern "C" { #endif #define REPL_OK 0 #define REPL_ERR_NOMEM -10000 #define REPL_ERR_DENIED -10001 #define REPL_ERR_INVALID -10002 #define REPL_ERR_BADCMD -10003 #define REPL_ERR_SYNTAX -10004 /* repl prompt tag */ #ifndef AMP_REPL_PROMPT #define REPL_PROMPT "amp > " #else #define REPL_PROMPT AMP_REPL_PROMPT #endif /* repl port */ #ifndef AMP_REPL_STDIO #define STDIO_UART 0 #else #define STDIO_UART AMP_REPL_STDIO #endif /* repl port bandrate */ #ifndef AMP_REPL_STDIO_BANDRATE #define STDIO_UART_BANDRATE 115200 #else #define STDIO_UART_BANDRATE AMP_REPL_STDIO_BANDRATE #endif /* repl task stack size */ #ifndef AMP_REPL_STACK_SIZE #define REPL_STACK_SIZE 1024*4 #else #define REPL_STACK_SIZE AMP_REPL_STACK_SIZE #endif #define REPL_INBUF_SIZE 256 #define REPL_OUTBUF_SIZE 1024 int32_t repl_printf(const char *buffer, ...); #ifdef __cplusplus } #endif #endif /* __AMP_REPL_H */
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/repl.h
C
apache-2.0
1,067
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos_fs.h" #include "aos_system.h" #include "amp_config.h" #include "amp_defines.h" #include "amp_task.h" #include "board_mgr.h" #include "be_inl.h" #include "cJSON.h" #include "startup/app_entry.h" #define MOD_STR "APPENTRY" app_options_t app_options; /* App(Object options) entry */ static duk_ret_t native_app_entry(duk_context *ctx) { int i; /* check paramters */ if (!duk_is_object(ctx, 0)) { // amp_warn("parameter must be object\n"); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "parameter must be object"); return duk_throw(ctx); } memset(&app_options, 0, sizeof(app_options_t)); /* get options object */ duk_dup(ctx, -1); app_options.object = be_ref(ctx); /* find globalData */ if (duk_get_prop_string(ctx, 0, "globalData")) { if (!duk_is_object(ctx, -1)) { duk_pop(ctx); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "onLaunch must be function"); return duk_throw(ctx); } amp_debug(MOD_STR, "find globalData\n"); duk_dup(ctx, -1); app_options.global_data = be_ref(ctx); duk_pop(ctx); } /* find onLaunch() */ if (duk_get_prop_string(ctx, 0, "onLaunch")) { if (!duk_is_function(ctx, -1)) { duk_pop(ctx); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "onLaunch must be function"); return duk_throw(ctx); } amp_debug(MOD_STR, "find onLaunch()\n"); duk_dup(ctx, -1); app_options.on_launch = be_ref(ctx); duk_pop(ctx); } /* find onError() */ if (duk_get_prop_string(ctx, 0, "onError")) { if (!duk_is_function(ctx, -1)) { duk_pop(ctx); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "onError must be function"); return duk_throw(ctx); } amp_debug(MOD_STR, "find onError()\n"); duk_dup(ctx, -1); app_options.on_error = be_ref(ctx); duk_pop(ctx); } /* find onError() */ if (duk_get_prop_string(ctx, 0, "onExit")) { if (!duk_is_function(ctx, -1)) { duk_pop(ctx); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "onExit must be function"); return duk_throw(ctx); } amp_debug(MOD_STR, "find onExit()\n"); duk_dup(ctx, -1); app_options.on_exit = be_ref(ctx); duk_pop(ctx); } amp_task_schedule_call(app_entry, NULL); return 1; /* one return value */ } void app_entry(void *data) { int i = 0; duk_context *ctx = be_get_context(); /* onLaunch hook */ be_push_ref(ctx, app_options.on_launch); duk_push_object(ctx); if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) { amp_console("%s", duk_safe_to_stacktrace(ctx, -1)); } duk_pop(ctx); duk_gc(ctx, 0); /* onExit hook */ // be_push_ref(ctx, app_options.on_exit); // duk_push_object(ctx); // duk_pcall(ctx, 1); // duk_pop(ctx); } void app_entry_register(void) { duk_context *ctx = be_get_context(); duk_push_object(ctx); /* App({}) */ duk_push_c_function(ctx, native_app_entry, 1); duk_put_global_string(ctx, "App"); }
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/startup/app_entry.c
C
apache-2.0
3,332
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef __APP_ENTRY_H #define __APP_ENTRY_H #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { /* options object */ int object; /* ref of globalData */ int global_data; /* ref of onLaunch() */ int on_launch; /* ref of onError() */ int on_error; /* ref of onExit() */ int on_exit; }app_options_t; extern void app_entry_register(void); extern void app_entry(void* data); #endif /* __APP_ENTRY_H */
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/startup/app_entry.h
C
apache-2.0
527
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos_fs.h" #include "aos_system.h" #include "amp_config.h" #include "amp_defines.h" #include "amp_task.h" #include "board_mgr.h" #include "be_inl.h" #include "cJSON.h" #include "startup/page_entry.h" #include "render.h" #define MOD_STR "APPENTRY" //static dlist_t g_pages_list; #ifdef JSE_ADVANCED_ADDON_UI extern char g_app_path[128]; char app_file_path[128]; int search_js_page_entry(amp_app_desc_t *app) { int i; int size; cJSON *root = NULL; cJSON *item = NULL; cJSON *temp = NULL; void *json_data = NULL; void * js_app_fd = NULL; int file_len = 0; int json_fd = -1; page_desc_t *page; if (app == NULL) { return -1; } snprintf(app_file_path, 128, AMP_APP_MAIN_JSON); /* cannot find the index.js int current dir */ if ((json_fd = aos_open(app_file_path, O_RDONLY)) < 0) { amp_error(MOD_STR, "cannot find the file :%s", app_file_path); return -1; } /* read package config file to json_data buffer */ file_len = aos_lseek(json_fd, 0, SEEK_END); printf("%s %d\r\n", __func__, file_len); json_data = aos_calloc(1, sizeof(char) * (file_len + 1)); if (NULL == json_data) { aos_close(json_fd); json_fd = -1; return -1; } aos_lseek(json_fd, 0, SEEK_SET); aos_read(json_fd, json_data, file_len); aos_close(json_fd); /* parser the package json data */ root = cJSON_Parse(json_data); if (NULL == root) { aos_free(json_data); amp_error(MOD_STR, "cJSON_Parse failed"); return -1; } item = cJSON_GetObjectItem(root, "pages"); if (item == NULL) { return -1; } size = cJSON_GetArraySize(item); app->page = aos_malloc(sizeof(page_desc_t) * size); if (NULL == app->page) { return -1; } memset(app->page, 0, sizeof(page_desc_t) * size); app->num = size; app->cur_page = 0; for (i = 0; i < size; i++) { page = &app->page[i]; page->index = i; temp = cJSON_GetArrayItem(item, i); if(NULL == temp ) { continue; } //strncpy(page->path, temp->valuestring, 64); //printf("temp->valuestring == %s\n\r",temp->valuestring); snprintf(page->path, 64, "%s", temp->valuestring); snprintf(page->css_file, 128, "%s%s", temp->valuestring, ".css"); snprintf(page->xml_file, 128, "%s%s", temp->valuestring, ".xml"); snprintf(page->js_file, 128, "%s%s", temp->valuestring, ".js"); } aos_free(json_data); cJSON_Delete(root); return 0; } void page_config_parse() { memset(&g_app, 0, sizeof(g_app)); search_js_page_entry(&g_app); } #endif void set_active_page(void) { } page_options_t* page_get_cur_options(void) { int index; if (g_app.cur_page >= g_app.num) { return NULL; } index = g_app.cur_page; return &(g_app.page[index].options); } static int page_add_options(page_options_t *options) { int index; if (options == NULL) { return -1; } if (g_app.cur_page >= g_app.num) { return -1; } index = g_app.cur_page; g_app.page[index].options.object = options->object; g_app.page[index].options.data = options->data; g_app.page[index].options.on_show = options->on_show; g_app.page[index].options.on_update = options->on_update; g_app.page[index].options.on_exit = options->on_exit; return 0; } /* App(Object options) entry */ static duk_ret_t native_page_entry(duk_context *ctx) { int i; int ret; page_options_t page_options; /* check paramters */ if (!duk_is_object(ctx, 0)) { // amp_warn("parameter must be object"); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "parameter must be object"); return duk_throw(ctx); } memset(&page_options, 0, sizeof(page_options_t)); /* get options object */ duk_dup(ctx, -1); page_options.object = be_ref(ctx); /* find data */ if (duk_get_prop_string(ctx, 0, "data")) { if (!duk_is_object(ctx, -1)) { duk_pop(ctx); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "data must be function"); return duk_throw(ctx); } amp_debug(MOD_STR, "find Page#data"); duk_dup(ctx, -1); page_options.data = be_ref(ctx); duk_pop(ctx); } /* find onShow() */ if (duk_get_prop_string(ctx, 0, "onShow")) { if (!duk_is_function(ctx, -1)) { duk_pop(ctx); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "onShow must be function"); return duk_throw(ctx); } amp_debug(MOD_STR, "find Page#onShow()"); duk_dup(ctx, -1); page_options.on_show = be_ref(ctx); duk_pop(ctx); } /* find onUpdate() */ if (duk_get_prop_string(ctx, 0, "onUpdate")) { if (!duk_is_function(ctx, -1)) { duk_pop(ctx); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "onUpdate must be function"); return duk_throw(ctx); } amp_debug(MOD_STR, "find Page#onUpdate()"); duk_dup(ctx, -1); page_options.on_update = be_ref(ctx); duk_pop(ctx); } /* find onExit() */ if (duk_get_prop_string(ctx, 0, "onExit")) { if (!duk_is_function(ctx, -1)) { duk_pop(ctx); duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "onExit must be function"); return duk_throw(ctx); } amp_debug(MOD_STR, "find Page#onExit()"); duk_dup(ctx, -1); page_options.on_exit = be_ref(ctx); duk_pop(ctx); } /* one-by-one insert into page list */ ret = page_add_options(&page_options); // amp_task_schedule_call(page_entry, NULL); return 1; } void page_entry(void *para) { int i = 0; page_options_t *options; duk_context *ctx = be_get_context(); options = page_get_cur_options(); if (options == NULL) { return; } /* onShow hook */ be_push_ref(ctx, options->on_show); duk_push_object(ctx); if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) { amp_debug("page", "%s : %d---------------------------------", __func__, __LINE__); //amp_console("%s", duk_safe_to_stacktrace(ctx, -1)); } duk_pop(ctx); duk_gc(ctx, 0); } void page_exit(void *para) { int i = 0; page_options_t *options; duk_context *ctx = be_get_context(); options = page_get_cur_options(); if (options == NULL) { amp_debug("page", "%s : %d---------------------------------", __func__, __LINE__); return; } /* onShow hook */ be_push_ref(ctx, options->on_exit); duk_push_object(ctx); if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) { amp_debug("page", "%s : %d---------------------------------", __func__, __LINE__); //amp_console("%s", duk_safe_to_stacktrace(ctx, -1)); } duk_pop(ctx); duk_gc(ctx, 0); be_unref(ctx, options->object); } void page_update(void *para) { int i = 0; page_options_t *options; duk_context *ctx = be_get_context(); options = page_get_cur_options(); if (options == NULL) { return; } /* onShow hook */ be_push_ref(ctx, options->on_update); duk_push_object(ctx); if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) { amp_console("%s", duk_safe_to_stacktrace(ctx, -1)); } duk_pop(ctx); duk_gc(ctx, 0); /* onExit hook */ // be_push_ref(ctx, app_options.on_exit); // duk_push_object(ctx); // duk_pcall(ctx, 1); // duk_pop(ctx); } void page_entry_register(void) { duk_context *ctx = be_get_context(); duk_push_object(ctx); /* Page({}) */ duk_push_c_function(ctx, native_page_entry, 1); duk_put_global_string(ctx, "Page"); }
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/startup/page_entry.c
C
apache-2.0
8,015
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef __PAGE_ENTRY_H #define __PAGE_ENTRY_H #include <stdio.h> #include <stdlib.h> #include <string.h> //#include "infra_list.h" #include "render.h" extern void page_list_init(void); extern void page_list_add(const char *route); extern void page_list_dump(void); extern void page_list_free(void); extern void page_entry_register(void); extern void page_entry(void *para); extern void page_exit(void *para); extern void page_update(void *para); #endif /* __PAGE_ENTRY_H */
YifuLiu/AliOS-Things
components/amp/engine/duktape_engine/startup/page_entry.h
C
apache-2.0
540
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "stdint.h" #include "stdint.h" #include "aiot_mqtt_api.h" #include "quickjs.h" enum MODULE_NAME_E { HAAS600_EC100Y = 0, HAAS600_EC600S, HAAS600_EC600N, HAAS600_EC600U, HAAS600_N58, HAAS600_N715, HAAS510_EC600S, HAAS531_L610CN, HAAS610_L610CN, HAAS632_LT32V, HAAS100_HAAS1000, HAASEDUK1_HAAS1000, HAAS200_RTL8723DM, MODULE_NAME_LIMIT = 0xFFF }; enum PRODUCT_NAME_E { KIT = 0, CLOUD_SPEAKER, CHARGER, PRINTER, DTU, RTU, PRODUCT_NAME_LIMIT = 0xFFF }; /* device active info report */ #define PRODUCT_NAME (product_name[PRODUCT_ID]) #define MODULE_NAME (module_name[MODULE_ID]) #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif /* device info report format */ #define DEVICE_INFO_UPDATE_FMT \ ("[" \ "{\"attrKey\":\"SYS_SDK_LANGUAGE\",\"attrValue\":\"C\",\"domain\":\"SYSTEM\"}" \ "{\"attrKey\":\"SYS_LP_SDK_VERSION\",\"attrValue\":\"aos-r-3.0.0\",\"domain\":\"SYSTEM\"}" \ "{\"attrKey\":\"SYS_PARTNER_ID\",\"attrValue\":\"AliOS Things Team\",\"domain\":\"SYSTEM\"}" \ "{\"attrKey\":\"SYS_MODULE_ID\",\"attrValue\":\"%s@AMP-%s\",\"domain\":\"SYSTEM\"}" \ "]") typedef enum { AIOT_MQTT_CONNECT, AIOT_MQTT_RECONNECT, AIOT_MQTT_DISCONNECT, AIOT_MQTT_MESSAGE }aiot_mqtt_res_type_t; /** * @brief dev模块内部发生值得用户关注的状态变化时, 通知用户的事件类型 */ typedef enum { /** * @brief 非法的应答报文 */ AIOT_DEV_JSCALLBACK_INVALID_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_CREATE_DEV_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_SUBSCRIBE_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_UNSUBSCRIBE_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_PUBLISH_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_POST_PROPS_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_POST_EVENT_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_ONPROPS_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_ONSERVICE_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_REGISTER_DEV_REF, /** * @brief 应答报文的id字段非法 */ AIOT_DEV_JSCALLBACK_END_CLIENT_REF, /** * @brief 应答报文的code字段非法 */ AIOT_DEV_JSCALLBACK_INVALID_CODE } aiot_dev_jscallback_type_t; /** * @brief subdev模块内部发生值得用户关注的状态变化时, 通知用户的事件类型 */ typedef enum { AIOT_SUBDEV_JSCALLBACK_ADD_TOPO_REF, AIOT_SUBDEV_JSCALLBACK_REMOVE_TOPO_REF, AIOT_SUBDEV_JSCALLBACK_GET_TOPO_REF, AIOT_SUBDEV_JSCALLBACK_LOGIN_REF, AIOT_SUBDEV_JSCALLBACK_LOGOUT_REF, AIOT_SUBDEV_JSCALLBACK_REGISTER_SUBDEV_REF, AIOT_SUBDEV_JSCALLBACK_REGISTER_PRODUCT_REF, AIOT_SUBDEV_JSCALLBACK_CHANGE_TOPO_REF, AIOT_SUBDEV_JSCALLBACK_CREATE_GATEWAY_REF, AIOT_SUBDEV_JSCALLBACK_ON_MQTT_MESSAGE_REF, AIOT_SUBDEV_JSCALLBACK_SUBSCRIBE_REF, AIOT_SUBDEV_JSCALLBACK_UNSUBSCRIBE_REF, AIOT_SUBDEV_JSCALLBACK_PUBLISH_REF, AIOT_SUBDEV_JSCALLBACK_INVALID_REF } aiot_subdev_jscallback_type_t; typedef struct iot_device_hanlde{ void *mqtt_handle; void *dm_handle; char *region; JSValue js_cb_ref[AIOT_DEV_JSCALLBACK_INVALID_CODE]; uint16_t keepaliveSec; int res; }iot_device_handle_t; typedef struct iot_gateway_handle{ void *mqtt_handle; void *dm_handle; void *subdev_handle; JSValue js_cb_ref[AIOT_SUBDEV_JSCALLBACK_INVALID_REF]; uint16_t keepaliveSec; }iot_gateway_handle_t; typedef struct iot_gateway_response{ int js_cb_ref; int msg_id; int code; char productkey[IOTX_PRODUCT_KEY_LEN]; char devicename[IOTX_DEVICE_NAME_LEN]; char message[128]; }iot_gateway_response_t; typedef struct { aiot_mqtt_recv_type_t type; uint8_t qos; int code; int topic_len; int payload_len; char *topic; char *payload; int32_t res; uint8_t max_qos; uint16_t packet_id; } iot_mqtt_recv_t; typedef struct { aiot_mqtt_event_type_t type; int code; } iot_mqtt_event_t; typedef struct { aiot_mqtt_option_t option; iot_mqtt_recv_t recv; iot_mqtt_event_t event; }iot_mqtt_message_t; typedef struct { void (*callback)(iot_mqtt_message_t *message, void *userdata); void *handle; }iot_mqtt_userdata_t; /* create mqtt client */ int32_t aiot_mqtt_client_start(void **handle, int keepaliveSec, iot_mqtt_userdata_t *userdata); /* destroy mqtt client */ int32_t aiot_mqtt_client_stop(void **handle); /* app mqtt process thread */ void aiot_app_mqtt_process_thread(void *args); /* app mqtt recv thread */ void aiot_app_mqtt_recv_thread(void *args); /* property post */ int32_t aiot_app_send_property_post(void *dm_handle, char *params); /* event post */ int32_t aiot_app_send_event_post(void *dm_handle, char *event_id, char *params); /* device dynmic register */ int32_t aiot_dynreg_http(JSValue *js_cb_ref); /* device active info report */ int32_t amp_app_devinfo_report(void *mqtt_handle);
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/aiot/module_aiot.h
C
apache-2.0
5,450
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "aos_network.h" #include "aos/kv.h" #include "aiot_state_api.h" #include "aiot_sysdep_api.h" #include "aiot_mqtt_api.h" #include "aiot_devinfo_api.h" #include "module_aiot.h" #define MOD_STR "AIOT_ACTINFO" const char *module_name[] = { "HAAS600-EC100Y", "HAAS600-EC600S", "HAAS600-EC600N", "HAAS600-EC600U", "HAAS600-N58", "HAAS600-N715", "HAAS510-EC600S", "HAAS531-L610CN", "HAAS610-L610CN" "HAAS632-LT32V", "HAAS100-HAAS1000", "HAASEDUK1-HAAS1000", "HAAS200-RTL8723DM", }; const char *product_name[] = { "Dev_Board", "Cloud_Speaker", "Charging_Station", "Cloud_Pinter", "DTU", "RTU" }; int32_t amp_app_devinfo_report(void *mqtt_handle) { int32_t res = STATE_SUCCESS; void *devinfo_handle = NULL; aiot_devinfo_msg_t *devinfo = NULL; char *msg = NULL; int32_t msg_len = 0; char product_key[IOTX_PRODUCT_KEY_LEN] = {0}; char device_name[IOTX_DEVICE_NAME_LEN] = {0}; int productkey_len = IOTX_PRODUCT_KEY_LEN; int devicename_len = IOTX_DEVICE_NAME_LEN; devinfo_handle = aiot_devinfo_init(); if (devinfo_handle == NULL) { amp_debug(MOD_STR, "ntp service init failed"); return -1; } res = aiot_devinfo_setopt(devinfo_handle, AIOT_DEVINFOOPT_MQTT_HANDLE, (void *)mqtt_handle); if (res < STATE_SUCCESS) { amp_debug(MOD_STR, "devinfo set mqtt handle failed"); aiot_devinfo_deinit(&devinfo_handle); return -1; } aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, product_key, &productkey_len); aos_kv_get(AMP_CUSTOMER_DEVICENAME, device_name, &devicename_len); msg_len = strlen(DEVICE_INFO_UPDATE_FMT) + 32; msg = (char *)amp_malloc(msg_len); if (msg == NULL) { amp_debug(MOD_STR, "malloc msg err"); goto exit; } memset(msg, 0, msg_len); /* devinfo update message */ res = snprintf(msg, msg_len, DEVICE_INFO_UPDATE_FMT, PRODUCT_NAME, MODULE_NAME ); if (res <= 0) { amp_debug(MOD_STR, "topic msg generate err"); goto exit; } devinfo = amp_malloc(sizeof(aiot_devinfo_msg_t)); if (devinfo == NULL) { amp_debug(MOD_STR, "device update info malloc failed"); goto exit; } memset(devinfo, 0, sizeof(aiot_devinfo_msg_t)); devinfo->product_key = amp_malloc(IOTX_PRODUCT_KEY_LEN); if (devinfo->product_key == NULL) { amp_debug(MOD_STR, "device update info malloc failed"); goto exit; } memset(devinfo->product_key, 0, IOTX_PRODUCT_KEY_LEN); devinfo->device_name = amp_malloc(IOTX_DEVICE_NAME_LEN); if (devinfo->device_name == NULL) { amp_debug(MOD_STR, "device update info malloc failed"); goto exit; } memset(devinfo->device_name, 0, IOTX_DEVICE_NAME_LEN); devinfo->data.update.params = amp_malloc(msg_len); if (devinfo == NULL) { amp_debug(MOD_STR, "device update info malloc failed"); goto exit; } memset(devinfo->data.update.params, 0, msg_len); devinfo->type = AIOT_DEVINFO_MSG_UPDATE; memcpy(devinfo->product_key, product_key, strlen(product_key)); memcpy(devinfo->device_name, device_name, strlen(device_name)); memcpy(devinfo->data.update.params, msg, msg_len); res = aiot_devinfo_send(devinfo_handle, devinfo); if (res < STATE_SUCCESS) { amp_debug(MOD_STR, "das stepping failed"); goto exit; } exit: if (msg) amp_free(msg); if (devinfo) { if (devinfo->product_key) amp_free(devinfo->product_key); if (devinfo->device_name) { amp_free(devinfo->device_name); } if (devinfo->data.update.params) { amp_free(devinfo->data.update.params); } amp_free(devinfo); } aiot_devinfo_deinit(&devinfo_handle); return res; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/aiot/module_aiot_activeinfo.c
C
apache-2.0
4,099
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" #include "aos/kv.h" #include "aiot_sysdep_api.h" #include "aiot_mqtt_api.h" #include "aiot_dm_api.h" #include "aiot_state_api.h" #include "quickjs.h" #include "ota_agent.h" #include "module_aiot.h" #include "app_upgrade.h" #include "quickjs_addon_common.h" #define MOD_STR "AIOT" #define OTA_MODE_NAME "system" static char g_iot_close_flag = 0; static char g_iot_conn_flag = 0; static char g_iot_clean_flag = 0; static aos_sem_t g_iot_close_sem = NULL; JSClassID js_aiot_device_class_id; ota_service_t g_aiot_device_appota_service; static ota_store_module_info_t module_info[3]; // extern const char *aos_userjs_version_get(void); typedef struct { iot_device_handle_t *iot_device_handle; char *topic; char *payload; char *service_id; char *params; JSValue js_cb_ref; int ret_code; int topic_len; int payload_len; int params_len; int dm_recv; uint64_t msg_id; aiot_mqtt_option_t option; aiot_mqtt_event_type_t event_type; aiot_mqtt_recv_type_t recv_type; aiot_dm_recv_type_t dm_recv_type; aiot_dev_jscallback_type_t cb_type; } device_notify_param_t; static char *__amp_strdup(char *src) { char *dst; size_t len = 0; if (src == NULL) { return NULL; } len = strlen(src); dst = amp_malloc(len + 1); if (dst == NULL) { return NULL; } memcpy(dst, src, len); dst[len] = '\0'; return dst; } static void aiot_device_notify(void *pdata) { device_notify_param_t *param = (device_notify_param_t *)pdata; JSContext *ctx = js_get_context(); JSValue obj = JS_NewObject(ctx); if (param->dm_recv) { switch (param->dm_recv_type) { case AIOT_DMRECV_PROPERTY_SET: amp_error(MOD_STR, "AIOT_DMRECV_PROPERTY_SET CASE"); JS_SetPropertyStr(ctx, obj, "msg_id", JS_NewInt32(ctx, param->msg_id)); JS_SetPropertyStr(ctx, obj, "params_len", JS_NewInt32(ctx, param->params_len)); JS_SetPropertyStr(ctx, obj, "params", JS_NewStringLen(ctx, param->params,param->params_len)); amp_free(param->params); break; case AIOT_DMRECV_ASYNC_SERVICE_INVOKE: amp_error(MOD_STR, "AIOT_DMRECV_ASYNC_SERVICE_INVOKE CASE"); JS_SetPropertyStr(ctx, obj, "msg_id", JS_NewInt32(ctx, param->msg_id)); JS_SetPropertyStr(ctx, obj, "service_id", JS_NewString(ctx, param->service_id)); JS_SetPropertyStr(ctx, obj, "params_len", JS_NewInt32(ctx, param->params_len)); JS_SetPropertyStr(ctx, obj, "params", JS_NewStringLen(ctx, param->params,param->params_len)); amp_free(param->service_id); amp_free(param->params); break; default: amp_free(param); return; } } else if (param->option == AIOT_MQTTOPT_EVENT_HANDLER) { switch (param->event_type) { case AIOT_MQTTEVT_CONNECT: case AIOT_MQTTEVT_RECONNECT: case AIOT_MQTTEVT_DISCONNECT: JS_SetPropertyStr(ctx, obj, "code", JS_NewInt32(ctx, param->ret_code)); JSValue aiot = JS_NewObjectClass(ctx, js_aiot_device_class_id); aos_printf("iot linsdk handle %p\n", param->iot_device_handle); JS_SetOpaque(aiot, param->iot_device_handle); JS_SetPropertyStr(ctx, obj, "handle", aiot); break; default: amp_free(param); return; } } else { switch (param->recv_type) { case AIOT_MQTTRECV_PUB: JS_SetPropertyStr(ctx, obj, "code", JS_NewInt32(ctx, param->ret_code)); JS_SetPropertyStr(ctx, obj, "handle", JS_NewInt32(ctx, param->iot_device_handle)); JS_SetPropertyStr(ctx, obj, "topic", JS_NewStringLen(ctx,param->topic, param->topic_len)); JS_SetPropertyStr(ctx, obj, "payload", JS_NewStringLen(ctx, param->payload,param->payload_len)); amp_free(param->topic); amp_free(param->payload); break; default: amp_free(param); return; } } JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &obj); JS_FreeValue(ctx, val); JS_FreeValue(ctx, obj); amp_free(param); } /* 用户数据接收处理回调函数 */ static void aiot_app_dm_recv_handler(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata) { iot_device_handle_t *iot_device_handle = (iot_device_handle_t *)userdata; device_notify_param_t *param; JSContext *ctx = js_get_context(); param = amp_malloc(sizeof(device_notify_param_t)); if (!param) { amp_error(MOD_STR, "alloc device_notify_param_t fail"); return; } memset(param, 0, sizeof(device_notify_param_t)); param->dm_recv = 1; param->dm_recv_type = recv->type; param->iot_device_handle = iot_device_handle; switch (recv->type) { /* 属性上报, 事件上报, 获取期望属性值或者删除期望属性值的应答 */ case AIOT_DMRECV_GENERIC_REPLY: { // printf("msg_id = %d, code = %d, data = %.*s, message = %.*s\r\n", // recv->data.generic_reply.msg_id, // recv->data.generic_reply.code, // recv->data.generic_reply.data_len, // recv->data.generic_reply.data, // recv->data.generic_reply.message_len, // recv->data.generic_reply.message); goto exit; } break; /* 属性设置 */ case AIOT_DMRECV_PROPERTY_SET: { amp_debug(MOD_STR, "msg_id = %ld, params = %.*s", (unsigned long)recv->data.property_set.msg_id, recv->data.property_set.params_len, recv->data.property_set.params); param->js_cb_ref = iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_ONPROPS_REF]; param->msg_id = recv->data.property_set.msg_id; param->params_len = recv->data.property_set.params_len; param->params = __amp_strdup(recv->data.property_set.params); param->cb_type = AIOT_DEV_JSCALLBACK_ONPROPS_REF; /* TODO: 以下代码演示如何对来自云平台的属性设置指令进行应答, 用户可取消注释查看演示效果 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_PROPERTY_SET_REPLY; msg.data.property_set_reply.msg_id = recv->data.property_set.msg_id; msg.data.property_set_reply.code = 200; msg.data.property_set_reply.data = "{}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ } break; /* 异步服务调用 */ case AIOT_DMRECV_ASYNC_SERVICE_INVOKE: { amp_debug(MOD_STR, "msg_id = %ld, service_id = %s, params = %.*s", (unsigned long)recv->data.async_service_invoke.msg_id, recv->data.async_service_invoke.service_id, recv->data.async_service_invoke.params_len, recv->data.async_service_invoke.params); param->js_cb_ref = iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_ONSERVICE_REF]; param->msg_id = recv->data.async_service_invoke.msg_id; param->params_len = recv->data.async_service_invoke.params_len; param->service_id = __amp_strdup(recv->data.async_service_invoke.service_id); param->params = __amp_strdup(recv->data.async_service_invoke.params); param->cb_type = AIOT_DEV_JSCALLBACK_ONSERVICE_REF; /* TODO: 以下代码演示如何对来自云平台的异步服务调用进行应答, 用户可取消注释查看演示效果 * * 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_ASYNC_SERVICE_REPLY; msg.data.async_service_reply.msg_id = recv->data.async_service_invoke.msg_id; msg.data.async_service_reply.code = 200; msg.data.async_service_reply.service_id = "ToggleLightSwitch"; msg.data.async_service_reply.data = "{\"dataA\": 20}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ } break; /* 同步服务调用 */ case AIOT_DMRECV_SYNC_SERVICE_INVOKE: { amp_debug(MOD_STR, "msg_id = %ld, rrpc_id = %s, service_id = %s, params = %.*s", (unsigned long)recv->data.sync_service_invoke.msg_id, recv->data.sync_service_invoke.rrpc_id, recv->data.sync_service_invoke.service_id, recv->data.sync_service_invoke.params_len, recv->data.sync_service_invoke.params); /* TODO: 以下代码演示如何对来自云平台的同步服务调用进行应答, 用户可取消注释查看演示效果 * * 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id和rrpc_id字符串, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_SYNC_SERVICE_REPLY; msg.data.sync_service_reply.rrpc_id = recv->data.sync_service_invoke.rrpc_id; msg.data.sync_service_reply.msg_id = recv->data.sync_service_invoke.msg_id; msg.data.sync_service_reply.code = 200; msg.data.sync_service_reply.service_id = "SetLightSwitchTimer"; msg.data.sync_service_reply.data = "{}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ goto exit; } break; /* 下行二进制数据 */ case AIOT_DMRECV_RAW_DATA: { amp_debug(MOD_STR, "raw data len = %d", recv->data.raw_data.data_len); /* TODO: 以下代码演示如何发送二进制格式数据, 若使用需要有相应的数据透传脚本部署在云端 */ /* { aiot_dm_msg_t msg; uint8_t raw_data[] = {0x01, 0x02}; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_RAW_DATA; msg.data.raw_data.data = raw_data; msg.data.raw_data.data_len = sizeof(raw_data); aiot_dm_send(dm_handle, &msg); } */ goto exit; } break; /* 二进制格式的同步服务调用, 比单纯的二进制数据消息多了个rrpc_id */ case AIOT_DMRECV_RAW_SYNC_SERVICE_INVOKE: { amp_debug(MOD_STR, "raw sync service rrpc_id = %s, data_len = %d", recv->data.raw_service_invoke.rrpc_id, recv->data.raw_service_invoke.data_len); goto exit; } break; default: goto exit; break; } amp_task_schedule_call(aiot_device_notify, param); return; exit: amp_free(param); } static void aiot_connect_event(iot_device_handle_t *iot_device_handle) { int res = 0; if (iot_device_handle->dm_handle != NULL) { amp_warn(MOD_STR, "dm_handle is already initialized"); return; } /* device model service */ iot_device_handle->dm_handle = aiot_dm_init(); if (iot_device_handle->dm_handle == NULL) { amp_debug(MOD_STR, "aiot_dm_init failed"); return; } /* 配置MQTT实例句柄 */ aiot_dm_setopt(iot_device_handle->dm_handle, AIOT_DMOPT_MQTT_HANDLE, iot_device_handle->mqtt_handle); /* 配置消息接收处理回调函数 */ aiot_dm_setopt(iot_device_handle->dm_handle, AIOT_DMOPT_RECV_HANDLER, (void *)aiot_app_dm_recv_handler); /* 配置回调函数参数 */ aiot_dm_setopt(iot_device_handle->dm_handle, AIOT_DMOPT_USERDATA, iot_device_handle); /* app device active info report */ res = amp_app_devinfo_report(iot_device_handle->mqtt_handle); if (res < STATE_SUCCESS) { amp_debug(MOD_STR, "device active info report failed"); } } static void aiot_mqtt_message_cb(iot_mqtt_message_t *message, void *userdata) { iot_mqtt_userdata_t *udata = (iot_mqtt_userdata_t *)userdata; device_notify_param_t *param; if (!message || !udata) return; amp_error(MOD_STR, "aiot_mqtt_message_cb IS CALLED"); param = amp_malloc(sizeof(device_notify_param_t)); if (!param) { amp_error(MOD_STR, "alloc device notify param fail"); return; } memset(param, 0, sizeof(device_notify_param_t)); param->iot_device_handle = (iot_device_handle_t *)udata->handle; param->option = message->option; param->js_cb_ref = param->iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_CREATE_DEV_REF]; param->cb_type = AIOT_DEV_JSCALLBACK_CREATE_DEV_REF; if (message->option == AIOT_MQTTOPT_EVENT_HANDLER) { switch (message->event.type) { case AIOT_MQTTEVT_CONNECT: case AIOT_MQTTEVT_RECONNECT: aiot_connect_event(param->iot_device_handle); case AIOT_MQTTEVT_DISCONNECT: param->ret_code = message->event.code; param->event_type = message->event.type; break; default: amp_free(param); return; } } else if (message->option == AIOT_MQTTOPT_RECV_HANDLER) { switch (message->recv.type) { case AIOT_MQTTRECV_PUB: param->ret_code = message->recv.code; param->topic_len = message->recv.topic_len; param->payload_len = message->recv.payload_len; param->topic = __amp_strdup(message->recv.topic); param->payload = __amp_strdup(message->recv.payload); param->recv_type = message->recv.type; break; default: amp_free(param); return; } } else { amp_free(param); return; } amp_task_schedule_call(aiot_device_notify, param); } static void aiot_device_connect(void *pdata) { int res = -1; char current_amp_ver[64]; ota_service_t *ota_svc = &g_aiot_device_appota_service; iot_device_handle_t *iot_device_handle = (iot_device_handle_t *)pdata; iot_mqtt_userdata_t *userdata; JSContext *ctx = js_get_context(); uint16_t keepaliveSec = 0; if (!iot_device_handle) { amp_error(MOD_STR, "mqtt client hadnle null"); return; } keepaliveSec = iot_device_handle->keepaliveSec; userdata = amp_malloc(sizeof(iot_mqtt_userdata_t)); if (!userdata) { amp_error(MOD_STR, "alloc mqtt userdata fail"); return; } memset(userdata, 0, sizeof(iot_mqtt_userdata_t)); userdata->callback = aiot_mqtt_message_cb; userdata->handle = iot_device_handle; res = aiot_mqtt_client_start(&iot_device_handle->mqtt_handle, keepaliveSec, userdata); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "mqtt client create failed"); amp_free(userdata); amp_free(iot_device_handle); return; } g_iot_conn_flag = 1; iot_device_handle->res = res; while (!g_iot_close_flag){ aos_msleep(1000); } aiot_mqtt_client_stop(&iot_device_handle->mqtt_handle); for (int i = 0; i < AIOT_DEV_JSCALLBACK_INVALID_CODE; i++) { if (!JS_IsUndefined(iot_device_handle->js_cb_ref[i])) { JS_FreeValue(ctx, iot_device_handle->js_cb_ref[i]); } } amp_free(userdata); amp_free(iot_device_handle); g_iot_conn_flag = 0; aos_sem_signal(&g_iot_close_sem); aos_task_exit(0); return; } /************************************************************************************* * Function: native_aiot_create_device * Description: js native addon for UDP.createSocket(); * Called by: js api * Input: none * Output: return socket fd when create socket success, * return error number when create socket fail **************************************************************************************/ static JSValue native_aiot_create_device(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { int res = -1; void *mqtt_handle = NULL; const char *productKey; const char *productSecret; const char *deviceName; const char *deviceSecret; uint32_t keepaliveSec = 0; JSValue js_cb_ref; aos_task_t iot_device_task; iot_device_handle_t *iot_device_handle = NULL; ota_service_t *ota_svc = &g_aiot_device_appota_service; /* check paramters */ JSValue options = argv[0]; JSValue cb = argv[1]; if (!JS_IsObject(options) || !JS_IsFunction(ctx, cb)) { amp_warn(MOD_STR, "parameter must be object and function\n"); res = -1; goto out; } if (g_iot_clean_flag) { amp_warn(MOD_STR, "module source clean, ignore"); goto out; } /* get device certificate */ JSValue j_productKey = JS_GetPropertyStr(ctx, argv[0], "productKey"); JSValue j_deviceName = JS_GetPropertyStr(ctx, argv[0], "deviceName"); JSValue j_deviceSecret = JS_GetPropertyStr(ctx, argv[0], "deviceSecret"); JSValue j_keepaliveSec = JS_GetPropertyStr(ctx, argv[0], "keepaliveSec"); if(!JS_IsString(j_productKey) || !JS_IsString(j_deviceName) || !JS_IsString(j_deviceSecret) || !JS_IsNumber(j_keepaliveSec)){ amp_warn(MOD_STR, "Parameter invalid"); res = -2; goto out; } productKey = JS_ToCString(ctx, j_productKey); deviceName = JS_ToCString(ctx, j_deviceName); deviceSecret = JS_ToCString(ctx,j_deviceSecret); JS_ToUint32(ctx, &keepaliveSec, j_keepaliveSec); amp_info(MOD_STR, "productKey=%s deviceName=%s deviceSecret=%s keepaliveSec=%d\n",productKey,deviceName,deviceSecret,keepaliveSec); memset(ota_svc->pk, 0, sizeof(ota_svc->pk)); memset(ota_svc->dn, 0, sizeof(ota_svc->dn)); memset(ota_svc->ds, 0, sizeof(ota_svc->ds)); memcpy(ota_svc->pk, productKey, strlen(productKey)); memcpy(ota_svc->dn, deviceName, strlen(deviceName)); memcpy(ota_svc->ds, deviceSecret, strlen(deviceSecret)); aos_kv_set(AMP_CUSTOMER_PRODUCTKEY, productKey, IOTX_PRODUCT_KEY_LEN, 1); aos_kv_set(AMP_CUSTOMER_DEVICENAME, deviceName, IOTX_DEVICE_NAME_LEN, 1); aos_kv_set(AMP_CUSTOMER_DEVICESECRET, deviceSecret, IOTX_DEVICE_SECRET_LEN, 1); js_cb_ref = JS_DupValue(ctx, cb); iot_device_handle = (iot_device_handle_t *)amp_malloc(sizeof(iot_device_handle_t)); if (!iot_device_handle) { amp_error(MOD_STR, "allocate memory failed\n"); goto out; } memset(iot_device_handle, 0, sizeof(iot_device_handle_t)); for (int i = 0; i < AIOT_DEV_JSCALLBACK_INVALID_CODE; i++) { iot_device_handle->js_cb_ref[i] = JS_UNDEFINED; } iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_CREATE_DEV_REF] = js_cb_ref; iot_device_handle->keepaliveSec = keepaliveSec; res = aos_task_new_ext(&iot_device_task, "amp aiot device task", aiot_device_connect, iot_device_handle, 1024 * 10, AOS_DEFAULT_APP_PRI); if (res != STATE_SUCCESS) { amp_warn(MOD_STR, "iot create task failed"); JS_FreeValue(ctx, js_cb_ref); amp_free(iot_device_handle); goto out; } out: if(productKey != NULL){ JS_FreeCString(ctx, productKey); } if(deviceName != NULL){ JS_FreeCString(ctx, deviceName); } if(deviceSecret != NULL){ JS_FreeCString(ctx, deviceSecret); } if (iot_device_handle != NULL) { JSValue obj; obj = JS_NewObjectClass(ctx, js_aiot_device_class_id); JS_SetOpaque(obj, (void *)iot_device_handle); return obj; } return JS_NewInt32(ctx, res); } static JSValue native_aiot_get_ntp_time(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { int res = -1; iot_device_handle_t *iot_device_handle = NULL; amp_debug(MOD_STR, "native_aiot_get_ntp_time called"); iot_device_handle = JS_GetOpaque2(ctx, this_val, js_aiot_device_class_id); if (!iot_device_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } JSValue js_cb = JS_DupValue(ctx, argv[0]); res = aiot_amp_ntp_service(iot_device_handle->mqtt_handle, js_cb); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "device dynmic register failed"); } out: return JS_NewInt32(ctx, res); } /* dynmic register */ static JSValue native_aiot_dynreg(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; char *productKey = NULL; char *deviceName = NULL; char *productSecret = NULL; /* check paramters */ JSValue options = argv[0]; JSValue cb = argv[1]; if (!JS_IsObject(options) || !JS_IsFunction(ctx, cb)) { amp_warn(MOD_STR, "parameter must be object and function\n"); res = -1; goto out; } if (g_iot_clean_flag) { amp_warn(MOD_STR, "module source clean, ignore"); goto out; } /* get device certificate */ JSValue j_productKey = JS_GetPropertyStr(ctx, argv[0], "productKey"); JSValue j_deviceName = JS_GetPropertyStr(ctx, argv[0], "deviceName"); JSValue j_productSecret = JS_GetPropertyStr(ctx, argv[0], "productSecret"); if (!JS_IsString(j_productKey) || !JS_IsString(j_deviceName) || !JS_IsString(j_productSecret)) { amp_warn(MOD_STR, "Parameter invalid"); res = -2; goto out; } productKey = JS_ToCString(ctx, j_productKey); deviceName = JS_ToCString(ctx, j_deviceName); productSecret = JS_ToCString(ctx, j_productSecret); aos_kv_set(AMP_CUSTOMER_PRODUCTKEY, productKey, IOTX_PRODUCT_KEY_LEN, 1); aos_kv_set(AMP_CUSTOMER_DEVICENAME, deviceName, IOTX_DEVICE_NAME_LEN, 1); aos_kv_set(AMP_CUSTOMER_PRODUCTSECRET, productSecret, IOTX_PRODUCT_SECRET_LEN, 1); JSValue js_cb_ref = JS_DupValue(ctx, argv[1]); res = aiot_dynreg_http(&js_cb_ref); aos_printf("native_aiot_dynreg res is %d\n", res); if (res < STATE_SUCCESS) { amp_debug(MOD_STR, "device dynmic register failed"); } out: JS_FreeValue(ctx, j_productKey); JS_FreeValue(ctx, j_deviceName); JS_FreeValue(ctx, j_productSecret); JS_FreeCString(ctx, productKey); JS_FreeCString(ctx, deviceName); JS_FreeCString(ctx, productSecret); aos_printf("res is %d\n", res); return JS_NewInt32(ctx, res); } /* post event */ static JSValue native_aiot_postEvent(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { int res = -1; iot_device_handle_t *iot_device_handle = NULL; char *event_id = NULL; char *event_payload = NULL; iot_device_handle = JS_GetOpaque2(ctx, this_val, js_aiot_device_class_id); if (!iot_device_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } JSValue id = JS_GetPropertyStr(ctx, argv[0], "id"); if (JS_IsString(id)) { event_id = JS_ToCString(ctx, id); } JSValue params = JS_GetPropertyStr(ctx, argv[0], "params"); JSValue jjson = JS_UNDEFINED; if (!JS_IsUndefined(params)) { if (JS_VALUE_GET_TAG(params) != JS_TAG_STRING) { jjson = JS_JSONStringify(ctx, params, JS_NULL, JS_NULL); event_payload = JS_ToCString(ctx, jjson); } else { event_payload = JS_ToCString(ctx, params); } } JS_FreeValue(ctx, params); amp_debug(MOD_STR, "native_aiot_postEvent event_id=%s event_payload=%s\n",event_id,event_payload); /* callback */ // iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_POST_EVENT_REF] = JS_DupValue(ctx, argv[1]); res = aiot_app_send_event_post(iot_device_handle->dm_handle, event_id, event_payload); if (res < STATE_SUCCESS) { amp_warn(MOD_STR, "post event failed!"); } if (event_id != NULL) { JS_FreeCString(ctx, event_id); } if (event_payload != NULL) { JS_FreeCString(ctx, event_payload); } if (!JS_IsUndefined(jjson)) { JS_FreeValue(ctx, jjson); } JS_FreeValue(ctx, id); out: return JS_NewInt32(ctx, res); } /* post props */ static JSValue native_aiot_postProps(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { int res = -1; iot_device_handle_t *iot_device_handle = NULL; char *payload_str= NULL; iot_device_handle = JS_GetOpaque2(ctx, this_val, js_aiot_device_class_id); if (!iot_device_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } JSValue payload = argv[0]; JSValue jjson = JS_UNDEFINED; if (!JS_IsUndefined(payload)) { if (JS_VALUE_GET_TAG(payload) != JS_TAG_STRING) { jjson = JS_JSONStringify(ctx, payload, JS_NULL, JS_NULL); payload_str = JS_ToCString(ctx, jjson); } else { payload_str = JS_ToCString(ctx, payload); } } // iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_POST_PROPS_REF] = JS_DupValue(ctx, argv[1]); res = aiot_app_send_property_post(iot_device_handle->dm_handle, payload_str); if (res < STATE_SUCCESS) { amp_warn(MOD_STR, "property post failed, res:%d", res); } JS_FreeCString(ctx, payload_str); if (!JS_IsUndefined(jjson)) { JS_FreeValue(ctx, jjson); } out: return JS_NewInt32(ctx, res); } /* onprops */ static JSValue native_aiot_onProps(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { int res = STATE_SUCCESS; iot_device_handle_t *iot_device_handle = NULL; iot_device_handle = JS_GetOpaque2(ctx, this_val, js_aiot_device_class_id); if (!iot_device_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } JSValue js_cb_ref = JS_DupValue(ctx, argv[0]); iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_ONPROPS_REF] = js_cb_ref; out: return JS_NewInt32(ctx, res); } /* onService */ static JSValue native_aiot_onService(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { int res = STATE_SUCCESS; iot_device_handle_t *iot_device_handle = NULL; iot_device_handle = JS_GetOpaque2(ctx, this_val, js_aiot_device_class_id); if (!iot_device_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_ONSERVICE_REF] = JS_DupValue(ctx, argv[0]); out: return JS_NewInt32(ctx, res); } /* publish */ static JSValue native_aiot_publish(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { int res = -1; iot_device_handle_t *iot_device_handle = NULL; char *topic; char *payload; uint16_t payload_len = 0; uint8_t qos = 0; iot_device_handle = JS_GetOpaque2(ctx, this_val, js_aiot_device_class_id); if (!iot_device_handle) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } JSValue val = JS_GetPropertyStr(ctx, argv[0], "topic"); topic = JS_ToCString(ctx,val); JS_FreeValue(ctx,val); val = JS_GetPropertyStr(ctx, argv[0], "payload"); payload = JS_ToCString(ctx,val); JS_FreeValue(ctx,val); payload_len = strlen(payload); val = JS_GetPropertyStr(ctx, argv[0], "qos"); JS_ToInt32(ctx,&qos, val); JS_FreeValue(ctx,val); // iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_PUBLISH_REF] = JS_DupValue(ctx, argv[1]); amp_debug(MOD_STR, "publish topic: %s, payload: %s, qos is: %d", topic, payload, qos); res = aiot_mqtt_pub(iot_device_handle->mqtt_handle, topic, payload, payload_len, qos); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "aiot app mqtt publish failed\n"); goto out; } out: if(topic != NULL){ JS_FreeCString(ctx, topic); } if(payload != NULL){ JS_FreeCString(ctx, payload); } return JS_NewInt32(ctx, res); } /* unsubscribe */ static JSValue native_aiot_unsubscribe(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { int res = -1; iot_device_handle_t *iot_device_handle = NULL; char *topic; uint8_t qos = 0; iot_device_handle = JS_GetOpaque2(ctx, this_val, js_aiot_device_class_id); if (!iot_device_handle) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } topic = JS_ToCString(ctx, argv[0]); iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_UNSUBSCRIBE_REF] = JS_DupValue(ctx, argv[1]); amp_debug(MOD_STR, "unsubscribe topic: %s", topic); res = aiot_mqtt_unsub(iot_device_handle->mqtt_handle, topic); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "aiot app mqtt unsubscribe failed, ret %d", res); goto out; } out: if(topic != NULL) { JS_FreeCString(ctx, topic); } return JS_NewInt32(ctx,res); } /* subscribe */ static JSValue native_aiot_subscribe(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { int res = -1; iot_device_handle_t *iot_device_handle = NULL; char *topic = NULL; uint32_t qos = 0; iot_device_handle = JS_GetOpaque2(ctx, this_val, js_aiot_device_class_id); if (!iot_device_handle) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } JSValue val = JS_GetPropertyStr(ctx, argv[0], "topic"); topic = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); val = JS_GetPropertyStr(ctx, argv[0], "qos"); JS_ToInt32(ctx,&qos, val); JS_FreeValue(ctx, val); iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_SUBSCRIBE_REF] = JS_DupValue(ctx, argv[1]); amp_debug(MOD_STR, "subscribe topic: %s, qos is: %d", topic, qos); res = aiot_mqtt_sub(iot_device_handle->mqtt_handle, topic, NULL, (uint8_t)qos, NULL); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "aiot app mqtt subscribe failed\n"); goto out; } out: if(topic != NULL){ JS_FreeCString(ctx, topic); } return JS_NewInt32(ctx,res); } static void module_iot_source_clean(void) { JSContext *ctx = js_get_context(); if (g_iot_conn_flag) { g_iot_close_flag = 1; aos_sem_wait(&g_iot_close_sem, 8000); g_iot_close_flag = 0; aos_msleep(10); } g_iot_clean_flag = 1; } static JSValue native_aiot_close(JSContext *ctx, JSValueConst this_val,int argc, JSValueConst *argv) { if (g_iot_conn_flag) { g_iot_close_flag = 1; aos_sem_wait(&g_iot_close_sem, 8000); g_iot_close_flag = 0; aos_msleep(10); } return JS_NewInt32(ctx,0); } static JSClassDef js_aiot_device_class = { "AIOT_DEVICE", }; static const JSCFunctionListEntry js_aiot_device_funcs[] = { JS_CFUNC_DEF("device", 1, native_aiot_create_device ), JS_CFUNC_DEF("subscribe", 3, native_aiot_subscribe), JS_CFUNC_DEF("unsubscribe", 3, native_aiot_unsubscribe), JS_CFUNC_DEF("publish", 3, native_aiot_publish), JS_CFUNC_DEF("postProps", 3, native_aiot_postProps), JS_CFUNC_DEF("onProps", 2, native_aiot_onProps), JS_CFUNC_DEF("postEvent", 3, native_aiot_postEvent), JS_CFUNC_DEF("getNtpTime", 2, native_aiot_get_ntp_time), JS_CFUNC_DEF("register", 2, native_aiot_dynreg), JS_CFUNC_DEF("onService", 2, native_aiot_onService), JS_CFUNC_DEF("close", 2, native_aiot_close), }; static int js_aiot_device_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_aiot_device_class_id); JS_NewClass(JS_GetRuntime(ctx), js_aiot_device_class_id, &js_aiot_device_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_aiot_device_funcs, countof(js_aiot_device_funcs)); JS_SetClassProto(ctx, js_aiot_device_class_id, proto); return JS_SetModuleExportList(ctx, m, js_aiot_device_funcs, countof(js_aiot_device_funcs)); } JSModuleDef *js_init_module_aiot_device(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_aiot_device_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_aiot_device_funcs, countof(js_aiot_device_funcs)); return m; } void module_aiot_device_register(void) { amp_debug(MOD_STR, "module_aiot_device_register"); JSContext *ctx = js_get_context(); if (!g_iot_close_sem) { if (aos_sem_new(&g_iot_close_sem, 0) != 0) { amp_error(MOD_STR, "create iot sem fail"); return; } } g_iot_clean_flag = 0; aos_printf("module iot register\n"); amp_module_free_register(module_iot_source_clean); js_init_module_aiot_device(ctx, "AIOT_DEVICE"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/aiot/module_aiot_device.c
C
apache-2.0
33,582
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "aiot_state_api.h" #include "aiot_sysdep_api.h" #include "aiot_dynreg_api.h" #include "aiot_mqtt_api.h" #include "module_aiot.h" #define MOD_STR "AIOT_DYNREG" /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */ extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile; /* 位于external/ali_ca_cert.c中的服务器证书 */ extern const char *ali_ca_cert; void aiot_app_dynreg_recv_handler(void *handle, const aiot_dynreg_recv_t *packet, void *userdata) { JSValue *js_cb_ref = (JSValue *)userdata; JSContext *ctx = js_get_context(); if (packet->type == AIOT_DYNREGRECV_STATUS_CODE) { amp_debug(MOD_STR, "dynreg rsp code = %d", packet->data.status_code.code); } else { if (packet->type == AIOT_DYNREGRECV_DEVICE_INFO) { amp_debug(MOD_STR, "dynreg DS = %s", packet->data.device_info.device_secret); aos_kv_set(AMP_CUSTOMER_DEVICESECRET, packet->data.device_info.device_secret, strlen(packet->data.device_info.device_secret), 1); JSValue sec = JS_NewString(ctx, packet->data.device_info.device_secret); JSValue val = JS_Call(ctx, *js_cb_ref, JS_UNDEFINED, 1, &sec); JS_FreeValue(ctx, val); JS_FreeValue(ctx, sec); JS_FreeValue(ctx, *js_cb_ref); } } } int32_t aiot_dynreg_http(JSValue *js_cb_ref) { int32_t res = STATE_SUCCESS; char *auth_url = "iot-auth.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */ char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */ uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */ aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */ /* get device tripple info */ char product_key[IOTX_PRODUCT_KEY_LEN] = {0}; char product_secret[IOTX_PRODUCT_SECRET_LEN] = {0}; char device_name[IOTX_DEVICE_NAME_LEN] = {0}; char device_secret[IOTX_DEVICE_SECRET_LEN] = {0}; int productkey_len = IOTX_PRODUCT_KEY_LEN; int productsecret_len = IOTX_PRODUCT_SECRET_LEN; int devicename_len = IOTX_DEVICE_NAME_LEN; int devicesecret_len = IOTX_DEVICE_SECRET_LEN; aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, product_key, &productkey_len); aos_kv_get(AMP_CUSTOMER_PRODUCTSECRET, product_secret, &productsecret_len); aos_kv_get(AMP_CUSTOMER_DEVICENAME, device_name, &devicename_len); amp_debug(MOD_STR, "dev info pk: %s, ps: %s, dn: %s", product_key, product_secret, device_name); /* end get device tripple info */ /* 配置SDK的底层依赖 */ aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile); /* 配置SDK的日志输出 */ // aiot_state_set_logcb(demo_state_logcb); /* 创建SDK的安全凭据, 用于建立TLS连接 */ memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t)); cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */ cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */ cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */ cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */ cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */ aos_kv_get(AMP_CUSTOMER_DEVICESECRET, device_secret, &devicesecret_len); if (device_secret[0] == '\0' || device_secret[IOTX_DEVICE_SECRET_LEN] != '\0') { if (product_secret[0] == '\0' || product_secret[IOTX_PRODUCT_SECRET_LEN] != '\0') { amp_error(MOD_STR, "need dynamic register, product secret is null"); return -1; } void *dynreg_handle = NULL; dynreg_handle = aiot_dynreg_init(); if (dynreg_handle == NULL) { amp_error(MOD_STR, "dynreg handle is null"); aos_task_exit(0); return NULL; } /* 配置网络连接的安全凭据, 上面已经创建好了 */ aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_NETWORK_CRED, (void *)&cred); /* 配置MQTT服务器地址 */ aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_HOST, (void *)auth_url); /* 配置MQTT服务器端口 */ aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_PORT, (void *)&port); /* 配置设备productKey */ aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_PRODUCT_KEY, (void *)product_key); /* 配置设备productSecret */ aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_PRODUCT_SECRET, (void *)product_secret); /* 配置设备deviceName */ aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_DEVICE_NAME, (void *)device_name); /* 配置DYNREG默认消息接收回调函数 */ aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_RECV_HANDLER, (void *)aiot_app_dynreg_recv_handler); /* 配置DYNREG默认消息接收回调函数参数 */ aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_USERDATA, js_cb_ref); res = aiot_dynreg_send_request(dynreg_handle); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "dynamic register send fail res = %d\n\r", res); aiot_dynreg_deinit(&dynreg_handle); return -1; } res = aiot_dynreg_recv(dynreg_handle); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "dynamic register recv fail res = %d\n\r", res); aiot_dynreg_deinit(&dynreg_handle); return -1; } aos_kv_get(AMP_CUSTOMER_DEVICESECRET, device_secret, &devicesecret_len); res = aiot_dynreg_deinit(&dynreg_handle); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "dynamic register deinit fail res = %d\n\r", res); return -1; } } else { amp_debug(MOD_STR, "device is already activated"); return -1; } return STATE_SUCCESS; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/aiot/module_aiot_dynreg.c
C
apache-2.0
6,357
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" #include "aos/kv.h" #include "aiot_sysdep_api.h" #include "aiot_mqtt_api.h" #include "aiot_dm_api.h" #include "aiot_subdev_api.h" #include "aiot_state_api.h" #include "quickjs.h" #include "ota_agent.h" #include "module_aiot.h" #define MOD_STR "AIOT_GATEWAY" #define OTA_MODE_NAME "system" static JSClassID js_aiot_gateway_class_id; typedef struct { iot_gateway_handle_t *handle; JSValue js_cb_ref; int ret_code; char *message; char *data; iot_mqtt_recv_t recv; aiot_mqtt_option_t option; aiot_subdev_jscallback_type_t cb_type; } subdev_notify_param_t; static char g_iot_close_flag = 0; static char g_iot_conn_flag = 0; static char g_iot_clean_flag = 0; static aos_sem_t g_iot_close_sem = NULL; static ota_store_module_info_t g_module_info[3]; ota_service_t g_appota_service; static JSValue g_on_message_cb_ref = 0; extern const char *aos_userjs_version_get(void); static char *__amp_strdup(char *src) { char *dst; size_t len = 0; if (src == NULL) { return NULL; } len = strlen(src); dst = amp_malloc(len + 1); if (dst == NULL) { return NULL; } memcpy(dst, src, len); dst[len] = '\0'; return dst; } static int user_jsapp_ota_triger_cb(void *pctx, char *ver, char *module_name) { int ret = OTA_TRANSPORT_PAR_FAIL; ota_service_t *ota_svc = (ota_service_t *)pctx; if ((pctx == NULL) || (ver == NULL) || (module_name == NULL)) { return ret; } if (strncmp(module_name, "default", strlen(module_name)) == 0) { char *current_ver = NULL; current_ver = aos_userjs_version_get(); if (current_ver == NULL) { return ret; } ret = 0; if (strncmp(ver, current_ver, strlen(ver)) <= 0) { ret = OTA_TRANSPORT_VER_FAIL; amp_error(MOD_STR, "user ota version too old!"); } else { if (ota_svc->feedback_func.on_user_event_cb != NULL) { ota_svc->feedback_func.on_user_event_cb(OTA_EVENT_UPGRADE_TRIGGER, 0, ota_svc->feedback_func.param); } else { ret = OTA_TRANSPORT_PAR_FAIL; amp_error(MOD_STR, "user ota trigger cb is NULL!"); } } } else { const char *current_amp_ver = aos_app_version_get(); ret = 0; if (strncmp(ver, current_amp_ver, strlen(ver)) <= 0) { ret = OTA_TRANSPORT_VER_FAIL; amp_error(MOD_STR, "system ota version too old!"); } else { if (ota_svc->feedback_func.on_user_event_cb != NULL) { ota_svc->feedback_func.on_user_event_cb(OTA_EVENT_UPGRADE_TRIGGER, 0, ota_svc->feedback_func.param); } else { ret = OTA_TRANSPORT_PAR_FAIL; amp_error(MOD_STR, "user ota trigger cb is NULL!"); } } } return ret; } static void aiot_subdev_notify(void *pdata) { subdev_notify_param_t *param = (subdev_notify_param_t *)pdata; iot_gateway_handle_t *handle = param->handle; JSContext *ctx = js_get_context(); JSValue obj = JS_NewObject(ctx); amp_debug(MOD_STR, "param->cb_type: %d", param->cb_type); switch (param->cb_type) { case AIOT_SUBDEV_JSCALLBACK_CREATE_GATEWAY_REF: { JS_SetPropertyStr(ctx, obj, "code", JS_NewInt32(ctx, param->ret_code)); JSValue aiot = JS_NewObjectClass(ctx, js_aiot_gateway_class_id); JS_SetOpaque(aiot, param->handle); JS_SetPropertyStr(ctx, obj, "handle", aiot); JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &obj); JS_FreeValue(ctx, val); } break; case AIOT_SUBDEV_JSCALLBACK_ADD_TOPO_REF: case AIOT_SUBDEV_JSCALLBACK_REMOVE_TOPO_REF: case AIOT_SUBDEV_JSCALLBACK_GET_TOPO_REF: case AIOT_SUBDEV_JSCALLBACK_LOGIN_REF: case AIOT_SUBDEV_JSCALLBACK_LOGOUT_REF: case AIOT_SUBDEV_JSCALLBACK_REGISTER_SUBDEV_REF: { JS_SetPropertyStr(ctx, obj, "code", JS_NewInt32(ctx, param->ret_code)); JS_SetPropertyStr(ctx, obj, "data", JS_NewStringLen(ctx, param->data, strlen(param->data))); JS_SetPropertyStr(ctx, obj, "message", JS_NewStringLen(ctx, param->message, strlen(param->message))); amp_debug(MOD_STR, "JS_Call param->cb_type: %d", param->cb_type); JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &obj); JS_FreeValue(ctx, val); if (param->message) amp_free(param->message); if (param->data) amp_free(param->data); } break; case AIOT_SUBDEV_JSCALLBACK_ON_MQTT_MESSAGE_REF: { JS_SetPropertyStr(ctx, obj, "code", JS_NewInt32(ctx, param->ret_code)); if (param->option == AIOT_MQTTOPT_RECV_HANDLER) { JS_SetPropertyStr(ctx, obj, "topic", JS_NewStringLen(ctx, param->recv.topic, param->recv.topic_len)); JS_SetPropertyStr(ctx, obj, "payload", JS_NewStringLen(ctx, param->recv.payload, param->recv.payload_len)); } JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &obj); JS_FreeValue(ctx, val); amp_free(param->recv.topic); amp_free(param->recv.payload); } break; case AIOT_SUBDEV_JSCALLBACK_SUBSCRIBE_REF: { JS_SetPropertyStr(ctx, obj, "code", JS_NewInt32(ctx, param->ret_code)); if (param->option == AIOT_MQTTOPT_RECV_HANDLER) { JS_SetPropertyStr(ctx, obj, "res", JS_NewInt32(ctx, param->recv.res)); JS_SetPropertyStr(ctx, obj, "max_qos", JS_NewInt32(ctx, param->recv.max_qos)); JS_SetPropertyStr(ctx, obj, "packet_id", JS_NewInt32(ctx, param->recv.packet_id)); } JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &obj); JS_FreeValue(ctx, val); } break; case AIOT_SUBDEV_JSCALLBACK_UNSUBSCRIBE_REF: { JS_SetPropertyStr(ctx, obj, "code", JS_NewInt32(ctx, param->ret_code)); JS_SetPropertyStr(ctx, obj, "packet_id", JS_NewInt32(ctx, param->recv.packet_id)); JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &obj); JS_FreeValue(ctx, val); } break; default: break; } JS_FreeValue(ctx, obj); amp_free(param); } static void aiot_subdev_packet_dump(const aiot_subdev_recv_t *packet) { amp_debug(MOD_STR, "%s: packet->type %d", __func__, packet->type); if (packet->type >= AIOT_SUBDEVRECV_TOPO_ADD_REPLY && packet->type <= AIOT_SUBDEVRECV_PRODUCT_REGISTER_REPLY) { amp_debug(MOD_STR, "msgid : %d", packet->data.generic_reply.msg_id); amp_debug(MOD_STR, "code : %d", packet->data.generic_reply.code); amp_debug(MOD_STR, "product key : %s", packet->data.generic_reply.product_key); amp_debug(MOD_STR, "device name : %s", packet->data.generic_reply.device_name); amp_debug(MOD_STR, "message : %s", (packet->data.generic_reply.message == NULL) ? ("NULL") : (packet->data.generic_reply.message)); amp_debug(MOD_STR, "data : %s", packet->data.generic_reply.data); } else if (packet->type == AIOT_SUBDEVRECV_TOPO_CHANGE_NOTIFY) { amp_debug(MOD_STR, "msgid : %d", packet->data.generic_notify.msg_id); amp_debug(MOD_STR, "product key : %s", packet->data.generic_notify.product_key); amp_debug(MOD_STR, "device name : %s", packet->data.generic_notify.device_name); amp_debug(MOD_STR, "params : %s", packet->data.generic_notify.params); } amp_debug(MOD_STR, "%s exit", __func__); } static void aiot_subdev_recv_handler(void *handle, const aiot_subdev_recv_t *packet, void *user_data) { iot_gateway_handle_t *iot_gateway_handle = (iot_gateway_handle_t *)user_data; subdev_notify_param_t *param = amp_malloc(sizeof(subdev_notify_param_t)); if (!param) { amp_error(MOD_STR, "alloc gateway notify param fail"); return; } memset(param, 0, sizeof(subdev_notify_param_t)); aiot_subdev_packet_dump(packet); param->handle = iot_gateway_handle; if (packet->type >= AIOT_SUBDEVRECV_TOPO_ADD_REPLY && packet->type <= AIOT_SUBDEVRECV_SUB_REGISTER_REPLY) { param->ret_code = packet->data.generic_reply.code; param->message = __amp_strdup(packet->data.generic_reply.message); param->data = __amp_strdup(packet->data.generic_reply.data); param->cb_type = packet->type; param->js_cb_ref = iot_gateway_handle->js_cb_ref[packet->type]; amp_debug(MOD_STR, "param->cb_type:%d, param->js_cb_ref: %d", param->cb_type, param->js_cb_ref); } else { amp_free(param); return; } amp_task_schedule_call(aiot_subdev_notify, param); } static void aiot_mqtt_message_cb(iot_mqtt_message_t *message, void *userdata) { iot_mqtt_userdata_t *udata = (iot_mqtt_userdata_t *)userdata; subdev_notify_param_t *param; if (!message || !udata) { return; } param = amp_malloc(sizeof(subdev_notify_param_t)); if (!param) { amp_error(MOD_STR, "alloc gateway notify param fail"); return; } param->handle = (iot_gateway_handle_t *)udata->handle; param->option = message->option; if (message->option == AIOT_MQTTOPT_RECV_HANDLER) { switch (message->recv.type) { case AIOT_MQTTRECV_PUB: if (JS_IsNull(g_on_message_cb_ref)) { amp_free(param); return; } param->ret_code = message->recv.code; param->recv.qos = message->recv.qos; param->recv.topic_len = message->recv.topic_len; param->recv.payload_len = message->recv.payload_len; param->recv.topic = __amp_strdup(message->recv.topic); param->recv.payload = __amp_strdup(message->recv.payload); param->js_cb_ref = g_on_message_cb_ref; param->cb_type = AIOT_SUBDEV_JSCALLBACK_ON_MQTT_MESSAGE_REF; break; case AIOT_MQTTRECV_SUB_ACK: param->ret_code = message->recv.code; param->recv.res = message->recv.res; param->recv.max_qos = message->recv.max_qos; param->recv.packet_id = message->recv.packet_id; param->js_cb_ref = param->handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_SUBSCRIBE_REF]; param->cb_type = AIOT_SUBDEV_JSCALLBACK_SUBSCRIBE_REF; break; case AIOT_MQTTRECV_UNSUB_ACK: param->recv.packet_id = message->recv.packet_id; param->js_cb_ref = param->handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_UNSUBSCRIBE_REF]; param->cb_type = AIOT_SUBDEV_JSCALLBACK_UNSUBSCRIBE_REF; break; default: amp_free(param); return; } } else if (message->option == AIOT_MQTTOPT_EVENT_HANDLER) { switch (message->event.type) { case AIOT_MQTTEVT_CONNECT: amp_free(param); return; case AIOT_MQTTEVT_RECONNECT: case AIOT_MQTTEVT_DISCONNECT: if (JS_IsNull(g_on_message_cb_ref)) { amp_free(param); return; } param->cb_type = AIOT_SUBDEV_JSCALLBACK_ON_MQTT_MESSAGE_REF; param->js_cb_ref = g_on_message_cb_ref; param->ret_code = message->event.code; break; default: amp_free(param); return; } } amp_task_schedule_call(aiot_subdev_notify, param); } #define SUBDEV_FILE_PATH AMP_FS_ROOT_DIR"pack.bin" #define OS_APP_PATH AMP_FS_ROOT_DIR"os_app.bin" #define OS_KERNEL_PATH AMP_FS_ROOT_DIR"os_kernel.bin" static void aiot_gateway_connect(void *pdata) { int res = -1; char current_amp_ver[64]; ota_service_t *ota_svc = &g_appota_service; iot_gateway_handle_t *iot_gateway_handle = (iot_gateway_handle_t *)pdata; subdev_notify_param_t *param; iot_mqtt_userdata_t *userdata; uint16_t keepaliveSec = 0; keepaliveSec = iot_gateway_handle->keepaliveSec; param = amp_malloc(sizeof(subdev_notify_param_t)); if (!param) { amp_error(MOD_STR, "alloc gateway notify param fail"); return; } param->cb_type = AIOT_SUBDEV_JSCALLBACK_CREATE_GATEWAY_REF; param->js_cb_ref = iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_CREATE_GATEWAY_REF]; param->handle = iot_gateway_handle; userdata = amp_malloc(sizeof(iot_mqtt_userdata_t)); if (!userdata) { amp_error(MOD_STR, "alloc mqtt userdata fail"); amp_free(param); return; } userdata->callback = aiot_mqtt_message_cb; userdata->handle = iot_gateway_handle; res = aiot_mqtt_client_start(&iot_gateway_handle->mqtt_handle, keepaliveSec, userdata); if (res < STATE_SUCCESS) { amp_debug(MOD_STR, "mqtt client create failed"); amp_free(userdata); amp_free(param); amp_free(iot_gateway_handle); return; } g_iot_conn_flag = 1; param->ret_code = res; /* gateway model service */ iot_gateway_handle->subdev_handle = aiot_subdev_init(); if (iot_gateway_handle->subdev_handle == NULL) { amp_debug(MOD_STR, "aiot_subdev_init failed"); amp_free(param); amp_free(iot_gateway_handle); return; } /* set mqtt handle */ aiot_subdev_setopt(iot_gateway_handle->subdev_handle, AIOT_SUBDEVOPT_MQTT_HANDLE, iot_gateway_handle->mqtt_handle); /* set subdev handler */ aiot_subdev_setopt(iot_gateway_handle->subdev_handle, AIOT_SUBDEVOPT_RECV_HANDLER, aiot_subdev_recv_handler); /* 配置回调函数参数 */ aiot_subdev_setopt(iot_gateway_handle->subdev_handle, AIOT_SUBDEVOPT_USERDATA, (void *)iot_gateway_handle); /* return aiot_device_handle */ amp_task_schedule_call(aiot_subdev_notify, param); /* app device active info report */ res = amp_app_devinfo_report(iot_gateway_handle->mqtt_handle); if (res < STATE_SUCCESS) { amp_debug(MOD_STR, "device active info report failed"); } // /* app ota service */ // ota_service_param_reset(ota_svc); // memset(g_module_info, 0x00, sizeof(g_module_info)); // ota_register_module_store(ota_svc, g_module_info, 3); // ota_register_trigger_msg_cb(ota_svc, (void *)user_jsapp_ota_triger_cb); // amp_debug(MOD_STR, "[%s %d]module",__func__,__LINE__); // ota_set_module_information(ota_svc, OTA_MODE_NAME, OS_APP_PATH, OTA_UPGRADE_ALL); // ota_set_module_information(ota_svc, "default", SUBDEV_FILE_PATH, OTA_UPGRADE_ALL); // ota_svc->mqtt_client = iot_gateway_handle->mqtt_handle; // res = ota_service_init(ota_svc); // if (res >= 0) { // amp_debug(MOD_STR, "user ota init ok!"); // } // else { // amp_error(MOD_STR, "user ota init failed!"); // } // //report app js version // res = ota_report_module_version(ota_svc, "default", aos_userjs_version_get()); // if(res < 0) { // amp_error(MOD_STR, "user ota report ver failed!"); // } // memset(current_amp_ver, 0x00, sizeof(current_amp_ver)); // aos_app_version_get(current_amp_ver); // //report amp app version // res = ota_report_module_version(ota_svc, OTA_MODE_NAME, current_amp_ver); // if (res < 0) { // amp_error(MOD_STR, "system ota report ver failed!"); // } while (!g_iot_close_flag) { aos_msleep(1000); } aiot_mqtt_client_stop(&iot_gateway_handle->mqtt_handle); amp_free(userdata); amp_free(iot_gateway_handle); g_iot_conn_flag = 0; aos_sem_signal(&g_iot_close_sem); aos_task_exit(0); return; } /************************************************************************************* * Function: native_aiot_create_device * Description: js native addon for UDP.createSocket(); * Called by: js api * Input: none * Output: return socket fd when create socket success, * return error number when create socket fail **************************************************************************************/ static JSValue native_aiot_create_gateway(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; void *mqtt_handle = NULL; const char *productKey; const char *productSecret; const char *deviceName; const char *deviceSecret; int keepaliveSec = 0; aos_task_t iot_device_task; iot_gateway_handle_t *iot_gateway_handle = NULL; ota_service_t *ota_svc = &g_appota_service; /* check paramters */ if (!JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be object and function"); res = -1; goto out; } if (g_iot_clean_flag) { amp_warn(MOD_STR, "module source clean, ignore"); goto out; } /* get device certificate */ JSValue pk = JS_GetPropertyStr(ctx, argv[0], "productKey"); JSValue dn = JS_GetPropertyStr(ctx, argv[0], "deviceName"); JSValue ds = JS_GetPropertyStr(ctx, argv[0], "deviceSecret"); JSValue kl = JS_GetPropertyStr(ctx, argv[0], "keepaliveSec"); if (!JS_IsString(pk) || !JS_IsString(dn) || !JS_IsString(ds) || !JS_IsNumber(kl)) { amp_warn(MOD_STR, "Parameter invalid"); res = -2; goto out; } productKey = JS_ToCString(ctx, pk); deviceName = JS_ToCString(ctx, dn); deviceSecret = JS_ToCString(ctx, ds); JS_ToInt32(ctx, &keepaliveSec, kl); amp_debug(MOD_STR, "productKey=%s,deviceName=%s,deviceSecret=%s,keepaliveSec=%d", productKey, deviceName, deviceSecret, keepaliveSec); JS_FreeValue(ctx, pk); JS_FreeValue(ctx, dn); JS_FreeValue(ctx, ds); JS_FreeValue(ctx, kl); memset(ota_svc->pk, 0, sizeof(ota_svc->pk)); memset(ota_svc->dn, 0, sizeof(ota_svc->dn)); memset(ota_svc->ds, 0, sizeof(ota_svc->ds)); memcpy(ota_svc->pk, productKey, strlen(productKey)); memcpy(ota_svc->dn, deviceName, strlen(deviceName)); memcpy(ota_svc->ds, deviceSecret, strlen(deviceSecret)); aos_kv_set(AMP_CUSTOMER_PRODUCTKEY, productKey, IOTX_PRODUCT_KEY_LEN, 1); aos_kv_set(AMP_CUSTOMER_DEVICENAME, deviceName, IOTX_DEVICE_NAME_LEN, 1); aos_kv_set(AMP_CUSTOMER_DEVICESECRET, deviceSecret, IOTX_DEVICE_SECRET_LEN, 1); // duk_dup(ctx, 1); iot_gateway_handle = (iot_gateway_handle_t *)amp_malloc(sizeof(iot_gateway_handle_t)); if (!iot_gateway_handle) { amp_error(MOD_STR, "allocate memory failed"); goto out; } JSValue cb = argv[1]; iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_CREATE_GATEWAY_REF] = JS_DupValue(ctx, cb); iot_gateway_handle->keepaliveSec = keepaliveSec; res = aos_task_new_ext(&iot_device_task, "amp aiot device task", aiot_gateway_connect, iot_gateway_handle, 1024 * 10, AOS_DEFAULT_APP_PRI); if (res != 0) { amp_warn(MOD_STR, "iot create task failed"); amp_free(iot_gateway_handle); goto out; } JSValue obj; obj = JS_NewObjectClass(ctx, js_aiot_gateway_class_id); JS_SetOpaque(obj, (void *)iot_gateway_handle); return obj; out: return JS_NewInt32(ctx, res); } /* addTopo */ static JSValue native_aiot_addTopo(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; aiot_subdev_dev_t *subdev; int subdev_length = 0; int i; iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (JS_IsArray(ctx, argv[0])) { JSValue length = JS_GetPropertyStr(ctx, argv[0], "length"); JS_ToUint32(ctx, &subdev_length, length); subdev = amp_malloc(subdev_length * sizeof(aiot_subdev_dev_t)); if (subdev == NULL) { amp_debug(MOD_STR, "sub dev malloc failed"); goto out; } for (unsigned i = 0; i < subdev_length; i++) { JSValue subobj = JS_GetPropertyUint32(ctx, argv[0], i); JSValue pk = JS_GetPropertyStr(ctx, subobj, "productKey"); subdev[i].product_key = JS_ToCString(ctx, pk); JS_FreeValue(ctx, pk); JSValue dn = JS_GetPropertyStr(ctx, subobj, "deviceName"); subdev[i].device_name = JS_ToCString(ctx, dn); JS_FreeValue(ctx, dn); JSValue ds = JS_GetPropertyStr(ctx, subobj, "deviceSecret"); subdev[i].device_secret = JS_ToCString(ctx, ds); JS_FreeValue(ctx, ds); } JS_FreeValue(ctx, length); } JSValue cb = argv[1]; iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_ADD_TOPO_REF] = JS_DupValue(ctx, cb); res = aiot_subdev_send_topo_add(iot_gateway_handle->subdev_handle, subdev, subdev_length); if (res < STATE_SUCCESS) { amp_debug(MOD_STR, "send subdev topo add failed, res: -0x%04X", -res); } out: if (subdev) { for (i = 0; i < subdev_length; i++) { if (subdev[i].product_key) { JS_FreeCString(ctx, subdev[i].product_key); } if (subdev[i].device_name) { JS_FreeCString(ctx, subdev[i].device_name); } if (subdev[i].device_secret) { JS_FreeCString(ctx, subdev[i].device_secret); } } amp_free(subdev); } return JS_NewInt32(ctx, res); } /* getTopo */ static JSValue native_aiot_getTopo(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; int js_cb_ref = 0; iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); JSValue cb = argv[0]; iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_GET_TOPO_REF] = JS_DupValue(ctx, cb); res = aiot_subdev_send_topo_get(iot_gateway_handle->subdev_handle); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "send subdev topo get failed, res: -0x%04X", -res); } out: return JS_NewInt32(ctx, res); } /* removeTopo */ static JSValue native_aiot_removeTopo(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; aiot_subdev_dev_t *subdev; int subdev_length = 0; int i; iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (JS_IsArray(ctx, argv[0])) { JSValue length = JS_GetPropertyStr(ctx, argv[0], "length"); JS_ToUint32(ctx, &subdev_length, length); subdev = amp_malloc(subdev_length * sizeof(aiot_subdev_dev_t)); if (subdev == NULL) { amp_debug(MOD_STR, "sub dev malloc failed"); goto out; } for (unsigned i = 0; i < subdev_length; i++) { JSValue subobj = JS_GetPropertyUint32(ctx, argv[0], i); JSValue pk = JS_GetPropertyStr(ctx, subobj, "productKey"); subdev[i].product_key = JS_ToCString(ctx, pk); JS_FreeValue(ctx, pk); JSValue dn = JS_GetPropertyStr(ctx, subobj, "deviceName"); subdev[i].device_name = JS_ToCString(ctx, dn); JS_FreeValue(ctx, dn); JSValue ds = JS_GetPropertyStr(ctx, subobj, "deviceSecret"); subdev[i].device_secret = JS_ToCString(ctx, ds); JS_FreeValue(ctx, ds); JS_FreeValue(ctx, subobj); } JS_FreeValue(ctx, length); } JSValue cb = argv[1]; iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_REMOVE_TOPO_REF] = JS_DupValue(ctx, cb); res = aiot_subdev_send_topo_delete(iot_gateway_handle->subdev_handle, subdev, subdev_length); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "send subdev topo remove failed, res: -0x%04X", -res); } out: if (subdev) { for (i = 0; i < subdev_length; i++) { if (subdev[i].product_key) { JS_FreeCString(ctx, subdev[i].product_key); } if (subdev[i].device_name) { JS_FreeCString(ctx, subdev[i].device_name); } if (subdev[i].device_secret) { JS_FreeCString(ctx, subdev[i].device_secret); } } amp_free(subdev); } return JS_NewInt32(ctx, res); } /* registerSubDevice */ static JSValue native_aiot_registerSubDevice(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; aiot_subdev_dev_t *subdev; int subdev_length = 0; int i; iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (JS_IsArray(ctx, argv[0])) { JSValue length = JS_GetPropertyStr(ctx, argv[0], "length"); JS_ToUint32(ctx, &subdev_length, length); subdev = amp_malloc(subdev_length * sizeof(aiot_subdev_dev_t)); if (subdev == NULL) { amp_debug(MOD_STR, "sub dev malloc failed"); goto out; } for (unsigned i = 0; i < subdev_length; i++) { JSValue subobj = JS_GetPropertyUint32(ctx, argv[0], i); JSValue pk = JS_GetPropertyStr(ctx, subobj, "productKey"); subdev[i].product_key = JS_ToCString(ctx, pk); JS_FreeValue(ctx, pk); JSValue dn = JS_GetPropertyStr(ctx, subobj, "deviceName"); subdev[i].device_name = JS_ToCString(ctx, dn); JS_FreeValue(ctx, dn); } JS_FreeValue(ctx, length); } JSValue cb = argv[1]; iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_REGISTER_SUBDEV_REF] = JS_DupValue(ctx, cb); res = aiot_subdev_send_sub_register(iot_gateway_handle->subdev_handle, subdev, subdev_length); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "send subdev register failed, res: -0x%04X", -res); } out: if (subdev) { for (i = 0; i < subdev_length; i++) { if (subdev[i].product_key) { JS_FreeCString(ctx, subdev[i].product_key); } if (subdev[i].device_name) { JS_FreeCString(ctx, subdev[i].device_name); } } amp_free(subdev); } return JS_NewInt32(ctx, res); } /* login */ static JSValue native_aiot_login(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; aiot_subdev_dev_t *subdev; int subdev_length = 0; int i; amp_debug(MOD_STR, "native_aiot_login"); subdev = amp_malloc(subdev_length * sizeof(aiot_subdev_dev_t)); iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (JS_IsArray(ctx, argv[0])) { JSValue length = JS_GetPropertyStr(ctx, argv[0], "length"); JS_ToUint32(ctx, &subdev_length, length); amp_debug(MOD_STR, "subdev_length=%d", subdev_length); subdev = amp_malloc(subdev_length * sizeof(aiot_subdev_dev_t)); if (subdev == NULL) { amp_debug(MOD_STR, "sub dev malloc failed"); goto out; } for (unsigned i = 0; i < subdev_length; i++) { JSValue subobj = JS_GetPropertyUint32(ctx, argv[0], i); JSValue pk = JS_GetPropertyStr(ctx, subobj, "productKey"); subdev[i].product_key = JS_ToCString(ctx, pk); JS_FreeValue(ctx, pk); JSValue dn = JS_GetPropertyStr(ctx, subobj, "deviceName"); subdev[i].device_name = JS_ToCString(ctx, dn); JS_FreeValue(ctx, dn); amp_debug(MOD_STR, "device_name=%s", subdev[i].device_name); JSValue ds = JS_GetPropertyStr(ctx, subobj, "deviceSecret"); subdev[i].device_secret = JS_ToCString(ctx, ds); JS_FreeValue(ctx, ds); JS_FreeValue(ctx, subobj); } JS_FreeValue(ctx, length); } JSValue cb = argv[1]; iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_LOGIN_REF] = JS_DupValue(ctx, cb); res = aiot_subdev_send_batch_login(iot_gateway_handle->subdev_handle, subdev, subdev_length); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "send subdev batch login failed, res: -0x%04X", -res); } out: amp_free(subdev); return JS_NewInt32(ctx, res); } /* logout */ static JSValue native_aiot_logout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; aiot_subdev_dev_t *subdev; int subdev_length = 0; int i; iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (JS_IsArray(ctx, argv[0])) { JSValue length = JS_GetPropertyStr(ctx, argv[0], "length"); JS_ToUint32(ctx, &subdev_length, length); subdev = amp_malloc(subdev_length * sizeof(aiot_subdev_dev_t)); if (subdev == NULL) { amp_debug(MOD_STR, "sub dev malloc failed"); goto out; } for (unsigned i = 0; i < subdev_length; i++) { JSValue subobj = JS_GetPropertyUint32(ctx, argv[0], i); JSValue pk = JS_GetPropertyStr(ctx, subobj, "productKey"); subdev[i].product_key = JS_ToCString(ctx, pk); JS_FreeValue(ctx, pk); JSValue dn = JS_GetPropertyStr(ctx, subobj, "deviceName"); subdev[i].device_name = JS_ToCString(ctx, dn); JS_FreeValue(ctx, dn); JSValue ds = JS_GetPropertyStr(ctx, subobj, "deviceSecret"); subdev[i].device_secret = JS_ToCString(ctx, ds); JS_FreeValue(ctx, ds); JS_FreeValue(ctx, subobj); } JS_FreeValue(ctx, length); } JSValue cb = argv[1]; iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_LOGOUT_REF] = JS_DupValue(ctx, cb); res = aiot_subdev_send_batch_logout(iot_gateway_handle->subdev_handle, subdev, subdev_length); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "send subdev batch logout failed, res: -0x%04X", -res); } out: amp_free(subdev); return JS_NewInt32(ctx, res); } /************************************************************************************* * Function: native_aiot_close * Description: js native addon for * UDP.close(sock_id) * Called by: js api * Input: sock_id: interger * * Output: return 0 when UDP.close call ok * return error number UDP.close call fail **************************************************************************************/ static JSValue native_aiot_gateway_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; amp_debug(MOD_STR, "native_aiot_gateway_close"); iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (iot_gateway_handle == NULL) { amp_warn(MOD_STR, "iot_gateway_handle is null"); goto out; } g_iot_close_flag = 1; aos_sem_wait(&g_iot_close_sem, 200 + 50); res = aiot_mqtt_client_stop(&iot_gateway_handle->mqtt_handle); if (res < 0) { amp_debug(MOD_STR, "aiot stop failed"); goto out; } g_iot_close_flag = 0; amp_free(iot_gateway_handle); out: return JS_NewInt32(ctx, res); } /* publish */ static JSValue native_aiot_publish(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; char *topic = NULL; char *payload = NULL; uint16_t payload_len = 0; uint8_t qos = 0; amp_debug(MOD_STR, "native_aiot_publish"); iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (iot_gateway_handle == NULL) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } JSValue val = JS_GetPropertyStr(ctx, argv[0], "topic"); topic = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); val = JS_GetPropertyStr(ctx, argv[0], "payload"); payload = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); payload_len = strlen(payload); val = JS_GetPropertyStr(ctx, argv[0], "qos"); JS_ToInt32(ctx, &qos, val); JS_FreeValue(ctx, val); amp_debug(MOD_STR, "publish topic: %s, payload: %s, qos is: %d", topic, payload, qos); res = aiot_mqtt_pub(iot_gateway_handle->mqtt_handle, topic, payload, payload_len, qos); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "aiot app mqtt publish failed"); goto out; } out: JS_FreeCString(ctx, topic); JS_FreeCString(ctx, payload); return JS_NewInt32(ctx, res); } /* unsubscribe */ static JSValue native_aiot_unsubscribe(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; char *topic; uint8_t qos = 0; iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (iot_gateway_handle == NULL) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } JSValue val = JS_GetPropertyStr(ctx, argv[0], "topic"); topic = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); JSValue cb = argv[1]; iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_UNSUBSCRIBE_REF] = JS_DupValue(ctx, cb); amp_debug(MOD_STR, "unsubscribe topic: %s", topic); res = aiot_mqtt_unsub(iot_gateway_handle->mqtt_handle, topic); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "aiot app mqtt unsubscribe failed"); goto out; } out: return JS_NewInt32(ctx, res); } /* subscribe */ static JSValue native_aiot_subscribe(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_gateway_handle_t *iot_gateway_handle = NULL; char *topic = NULL; uint8_t qos = 0; iot_gateway_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (iot_gateway_handle == NULL) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } JSValue val = JS_GetPropertyStr(ctx, argv[0], "topic"); topic = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); val = JS_GetPropertyStr(ctx, argv[0], "qos"); JS_ToInt32(ctx, &qos, val); JS_FreeValue(ctx, val); JSValue cb = argv[1]; iot_gateway_handle->js_cb_ref[AIOT_SUBDEV_JSCALLBACK_SUBSCRIBE_REF] = JS_DupValue(ctx, cb); amp_debug(MOD_STR, "subscribe topic: %s", topic); res = aiot_mqtt_sub(iot_gateway_handle->mqtt_handle, topic, NULL, qos, NULL); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "aiot app mqtt subscribe failed"); goto out; } out: return JS_NewInt32(ctx, res); } static JSValue native_aiot_get_ntp_time(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_device_handle_t *iot_device_handle = NULL; amp_debug(MOD_STR, "native_aiot_get_ntp_time called"); iot_device_handle = JS_GetOpaque2(ctx, this_val, js_aiot_gateway_class_id); if (!iot_device_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } JSValue js_cb = JS_DupValue(ctx, argv[0]); res = aiot_amp_ntp_service(iot_device_handle->mqtt_handle, js_cb); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "device dynmic register failed"); } out: return JS_NewInt32(ctx, res); } /* on mqtt event */ static JSValue native_aiot_on_mqtt_event(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = STATE_SUCCESS; JSValue cb = argv[0]; if (!JS_IsFunction(ctx, cb)) { amp_warn(MOD_STR, "parameter must be (function)"); goto out; } g_on_message_cb_ref = JS_DupValue(ctx, cb); out: return JS_NewInt32(ctx, res); } static void module_iot_source_clean(void) { if (g_iot_conn_flag) { g_iot_close_flag = 1; aos_sem_wait(&g_iot_close_sem, 5100); g_iot_close_flag = 0; aos_msleep(10); } g_iot_clean_flag = 1; } static JSClassDef js_aiot_gateway_class = { "AIOT_GATEWAY", }; static const JSCFunctionListEntry js_aiot_gateway_funcs[] = { JS_CFUNC_DEF("gateway", 2, native_aiot_create_gateway), JS_CFUNC_DEF("addTopo", 3, native_aiot_addTopo), JS_CFUNC_DEF("getTopo", 1, native_aiot_getTopo), JS_CFUNC_DEF("removeTopo", 2, native_aiot_removeTopo), JS_CFUNC_DEF("registerSubDevice", 2, native_aiot_registerSubDevice), JS_CFUNC_DEF("login", 2, native_aiot_login), JS_CFUNC_DEF("logout", 2, native_aiot_logout), JS_CFUNC_DEF("subscribe", 2, native_aiot_subscribe), JS_CFUNC_DEF("unsubscribe", 2, native_aiot_unsubscribe), JS_CFUNC_DEF("publish", 2, native_aiot_publish), JS_CFUNC_DEF("onMqttMessage", 1, native_aiot_on_mqtt_event), JS_CFUNC_DEF("getNtpTime", 1, native_aiot_get_ntp_time), }; static int js_aiot_gateway_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_aiot_gateway_class_id); JS_NewClass(JS_GetRuntime(ctx), js_aiot_gateway_class_id, &js_aiot_gateway_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_aiot_gateway_funcs, countof(js_aiot_gateway_funcs)); JS_SetClassProto(ctx, js_aiot_gateway_class_id, proto); return JS_SetModuleExportList(ctx, m, js_aiot_gateway_funcs, countof(js_aiot_gateway_funcs)); } JSModuleDef *js_init_module_aiot_gateway(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_aiot_gateway_init); if (!m) { return NULL; } JS_AddModuleExportList(ctx, m, js_aiot_gateway_funcs, countof(js_aiot_gateway_funcs)); return m; } void module_aiot_gateway_register(void) { amp_debug(MOD_STR, "module_aiot_gateway_register"); JSContext *ctx = js_get_context(); aos_printf("module aiot_gateway register\n"); js_init_module_aiot_gateway(ctx, "AIOT_GATEWAY"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/aiot/module_aiot_gateway.c
C
apache-2.0
38,499
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" #include "aos/kv.h" #include "aiot_state_api.h" #include "aiot_sysdep_api.h" #include "aiot_mqtt_api.h" #include "aiot_dm_api.h" #include "aiot_subdev_api.h" // #include "be_inl.h" #include "module_aiot.h" #ifdef AOS_COMP_UAGENT #include "uagent.h" #endif #define MOD_STR "AIOT_MQTT" /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */ extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile; /* 位于external/ali_ca_cert.c中的服务器证书 */ extern const char *ali_ca_cert; uint8_t g_app_mqtt_process_thread_running = 0; uint8_t g_app_mqtt_recv_thread_running = 0; uint8_t g_app_mqtt_process_thread_exit = 0; uint8_t g_app_mqtt_recv_thread_exit = 0; static char *__amp_strdup(char *src, int len) { char *dst; if (src == NULL) { return NULL; } dst = amp_malloc(len + 1); if (dst == NULL) { return NULL; } memcpy(dst, src, len); dst[len] = '\0'; return dst; } /* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */ void aiot_app_mqtt_process_thread(void *args) { int32_t res = STATE_SUCCESS; g_app_mqtt_process_thread_exit = 0; while (g_app_mqtt_process_thread_running) { res = aiot_mqtt_process(args); if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } g_app_mqtt_process_thread_exit = 1; aos_task_exit(0); return; } /* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */ void aiot_app_mqtt_recv_thread(void *args) { int32_t res = STATE_SUCCESS; g_app_mqtt_recv_thread_exit = 0; while (g_app_mqtt_recv_thread_running) { res = aiot_mqtt_recv(args); if (res < STATE_SUCCESS) { if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } } g_app_mqtt_recv_thread_exit = 1; aos_task_exit(0); return; } /* MQTT默认消息处理回调, 当SDK从服务器收到MQTT消息时, 且无对应用户回调处理时被调用 */ void aiot_app_mqtt_recv_handler(void *handle, const aiot_mqtt_recv_t *packet, void *userdata) { iot_mqtt_userdata_t *udata = (iot_mqtt_userdata_t *)userdata; if (!udata || !udata->callback) { amp_error(MOD_STR, "mqtt_recv_handler userdata is null! recv type is %d!", packet->type); return; } iot_mqtt_message_t message; memset(&message, 0, sizeof(iot_mqtt_message_t)); message.option = AIOT_MQTTOPT_RECV_HANDLER; message.recv.type = packet->type; message.recv.code = AIOT_MQTT_MESSAGE; switch (packet->type) { case AIOT_MQTTRECV_HEARTBEAT_RESPONSE: { // amp_debug(MOD_STR, "heartbeat response"); /* TODO: 处理服务器对心跳的回应, 一般不处理 */ } break; case AIOT_MQTTRECV_SUB_ACK: { amp_debug(MOD_STR, "suback, res: -0x%04X, packet id: %d, max qos: %d", -packet->data.sub_ack.res, packet->data.sub_ack.packet_id, packet->data.sub_ack.max_qos); /* TODO: 处理服务器对订阅请求的回应, 一般不处理 */ message.recv.res = packet->data.sub_ack.res; message.recv.max_qos = packet->data.sub_ack.max_qos; message.recv.packet_id = packet->data.sub_ack.packet_id; udata->callback(&message, udata); } break; case AIOT_MQTTRECV_UNSUB_ACK: { amp_debug(MOD_STR, "unsuback, packet id: %d", packet->data.unsub_ack.packet_id); /* 处理服务器对取消订阅请求的回应, 一般不处理 */ message.recv.packet_id = packet->data.unsub_ack.packet_id; udata->callback(&message, udata); } break; case AIOT_MQTTRECV_PUB: { amp_debug(MOD_STR, "pub, qos: %d, topic: %.*s", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic); amp_debug(MOD_STR, "pub, payload: %.*s", packet->data.pub.payload_len, packet->data.pub.payload); /* TODO: 处理服务器下发的业务报文 */ message.recv.qos = packet->data.pub.qos; message.recv.topic = __amp_strdup(packet->data.pub.topic, packet->data.pub.topic_len); message.recv.payload = __amp_strdup(packet->data.pub.payload, packet->data.pub.payload_len); message.recv.topic_len = packet->data.pub.topic_len; message.recv.payload_len = packet->data.pub.payload_len; udata->callback(&message, udata); amp_free(message.recv.topic); amp_free(message.recv.payload); } break; case AIOT_MQTTRECV_PUB_ACK: { amp_debug(MOD_STR, "puback, packet id: %d", packet->data.pub_ack.packet_id); /* TODO: 处理服务器对QoS1上报消息的回应, 一般不处理 */ } break; default: { } } } /* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */ void aiot_app_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata) { iot_mqtt_userdata_t *udata = (iot_mqtt_userdata_t *)userdata; iot_mqtt_message_t message; memset(&message, 0, sizeof(iot_mqtt_message_t)); message.option = AIOT_MQTTOPT_EVENT_HANDLER; message.event.type = event->type; switch (event->type) { /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */ case AIOT_MQTTEVT_CONNECT: { amp_debug(MOD_STR, "AIOT_MQTTEVT_CONNECT"); /* TODO: 处理SDK建连成功, 不可以在这里调用耗时较长的阻塞函数 */ message.event.code = AIOT_MQTT_CONNECT; } break; /* SDK因为网络状况被动断连后, 自动发起重连已成功 */ case AIOT_MQTTEVT_RECONNECT: { amp_debug(MOD_STR, "AIOT_MQTTEVT_RECONNECT"); /* TODO: 处理SDK重连成功, 不可以在这里调用耗时较长的阻塞函数 */ message.event.code = AIOT_MQTT_RECONNECT; } break; /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */ case AIOT_MQTTEVT_DISCONNECT: { char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") : ("heartbeat disconnect"); amp_debug(MOD_STR, "AIOT_MQTTEVT_DISCONNECT: %s", cause); /* TODO: 处理SDK被动断连, 不可以在这里调用耗时较长的阻塞函数 */ message.event.code = AIOT_MQTT_DISCONNECT; } break; default: { return; } } if (udata && udata->callback) udata->callback(&message, udata); } /* 属性上报函数演示 */ int32_t aiot_app_send_property_post(void *dm_handle, char *params) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_PROPERTY_POST; msg.data.property_post.params = params; return aiot_dm_send(dm_handle, &msg); } /* 事件上报函数演示 */ int32_t aiot_app_send_event_post(void *dm_handle, char *event_id, char *params) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_EVENT_POST; msg.data.event_post.event_id = event_id; msg.data.event_post.params = params; return aiot_dm_send(dm_handle, &msg); } int32_t aiot_mqtt_client_start(void **handle, int keepaliveSec, iot_mqtt_userdata_t *userdata) { int32_t res = STATE_SUCCESS; void *mqtt_handle = NULL; char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */ char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */ uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */ aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */ /* get device tripple info */ char product_key[IOTX_PRODUCT_KEY_LEN] = {0}; char device_name[IOTX_DEVICE_NAME_LEN] = {0}; char device_secret[IOTX_DEVICE_SECRET_LEN] = {0}; int productkey_len = IOTX_PRODUCT_KEY_LEN; int devicename_len = IOTX_DEVICE_NAME_LEN; int devicesecret_len = IOTX_DEVICE_SECRET_LEN; aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, product_key, &productkey_len); aos_kv_get(AMP_CUSTOMER_DEVICENAME, device_name, &devicename_len); aos_kv_get(AMP_CUSTOMER_DEVICESECRET, device_secret, &devicesecret_len); /* end get device tripple info */ /* 配置SDK的底层依赖 */ aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile); /* 配置SDK的日志输出 */ // aiot_state_set_logcb(demo_state_logcb); /* 创建SDK的安全凭据, 用于建立TLS连接 */ memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t)); cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */ cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */ cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */ cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */ cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */ /* 创建1个MQTT客户端实例并内部初始化默认参数 */ mqtt_handle = aiot_mqtt_init(); if (mqtt_handle == NULL) { amp_debug(MOD_STR, "aiot_mqtt_init failed"); amp_free(mqtt_handle); return -1; } *handle = mqtt_handle; /* TODO: 如果以下代码不被注释, 则例程会用TCP而不是TLS连接云平台 */ { memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t)); cred.option = AIOT_SYSDEP_NETWORK_CRED_NONE; } snprintf(host, 100, "%s.%s", product_key, url); /* 配置MQTT服务器地址 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host); /* 配置MQTT服务器端口 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port); /* 配置设备productKey */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key); /* 配置设备deviceName */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name); /* 配置设备deviceSecret */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret); /* 配置网络连接的安全凭据, 上面已经创建好了 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred); /* 配置MQTT心跳间隔 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_KEEPALIVE_SEC, (void *)&keepaliveSec); /* 配置回调参数 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_USERDATA, userdata); /* 配置MQTT默认消息接收回调函数 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER, (void *)aiot_app_mqtt_recv_handler); /* 配置MQTT事件回调函数 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)aiot_app_mqtt_event_handler); /* 与服务器建立MQTT连接 */ res = aiot_mqtt_connect(mqtt_handle); if (res < STATE_SUCCESS) { /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */ aiot_mqtt_deinit(&mqtt_handle); amp_debug(MOD_STR, "aiot_mqtt_connect failed: -0x%04X", -res); aos_task_exit(0); return -1; } /* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */ g_app_mqtt_process_thread_running = 1; aos_task_t mqtt_process_task; if (aos_task_new_ext(&mqtt_process_task, "mqtt_process", aiot_app_mqtt_process_thread, mqtt_handle, 1024 * 4, AOS_DEFAULT_APP_PRI) != 0) { amp_debug(MOD_STR, "management mqtt process task create failed!"); aiot_mqtt_deinit(&mqtt_handle); aos_task_exit(0); return -1; } amp_debug(MOD_STR, "app mqtt process start"); /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */ g_app_mqtt_recv_thread_running = 1; aos_task_t mqtt_rec_task; if (aos_task_new_ext(&mqtt_rec_task, "mqtt_rec", aiot_app_mqtt_recv_thread, mqtt_handle, 1024 * 4, AOS_DEFAULT_APP_PRI) != 0) { amp_debug(MOD_STR, "management mqtt rec task create failed!"); aiot_mqtt_deinit(&mqtt_handle); aos_task_exit(0); return -1; } amp_debug(MOD_STR, "app mqtt rec start"); #ifdef AOS_COMP_UAGENT res = uagent_mqtt_client_set(mqtt_handle); if (res != 0) { amp_debug(MOD_STR, "uAgent mqtt handle set failed ret = %d\n", res); } res = uagent_ext_comm_start(product_key, device_name); if (res != 0) { amp_debug(MOD_STR, "uAgent ext comm start failed ret = %d\n", res); } #endif return STATE_SUCCESS; } /* mqtt stop */ int32_t aiot_mqtt_client_stop(void **handle) { int32_t res = STATE_SUCCESS; void *mqtt_handle = NULL; int cnt = 30; mqtt_handle = *handle; g_app_mqtt_process_thread_running = 0; g_app_mqtt_recv_thread_running = 0; while (cnt-- > 0) { if (g_app_mqtt_recv_thread_exit && g_app_mqtt_process_thread_exit) { break; } aos_msleep(200); } /* 断开MQTT连接 */ res = aiot_mqtt_disconnect(mqtt_handle); if (res < STATE_SUCCESS) { aiot_mqtt_deinit(&mqtt_handle); amp_debug(MOD_STR, "aiot_mqtt_disconnect failed: -0x%04X", -res); return -1; } /* 销毁MQTT实例 */ res = aiot_mqtt_deinit(&mqtt_handle); if (res < STATE_SUCCESS) { amp_debug(MOD_STR, "aiot_mqtt_deinit failed: -0x%04X", -res); return -1; } return res; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/aiot/module_aiot_mqtt.c
C
apache-2.0
14,276
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "aiot_state_api.h" #include "aiot_sysdep_api.h" #include "aiot_ntp_api.h" #include "aiot_mqtt_api.h" #include "module_aiot.h" #include "quickjs_addon_common.h" #define MOD_STR "AIOT_NTP" /* ntp timestamp */ extern int64_t g_ntp_time; extern int64_t g_up_time; typedef struct { JSValue js_cb_ref; uint32_t year; uint32_t month; uint32_t day; uint32_t hour; uint32_t minute; uint32_t second; uint32_t msecond; uint64_t timestamp; } aiot_ntp_notify_param_t; static void aiot_device_ntp_notify(void *pdata) { aiot_ntp_notify_param_t *param = (aiot_ntp_notify_param_t *)pdata; JSContext *ctx = js_get_context(); JSValue obj = JS_NewObject(ctx); JS_SetPropertyStr(ctx, obj, "year", JS_NewInt32(ctx, param->year)); JS_SetPropertyStr(ctx, obj, "month", JS_NewInt32(ctx, param->month)); JS_SetPropertyStr(ctx, obj, "day", JS_NewInt32(ctx, param->day)); JS_SetPropertyStr(ctx, obj, "hour", JS_NewInt32(ctx, param->hour)); JS_SetPropertyStr(ctx, obj, "minute", JS_NewInt32(ctx, param->minute)); JS_SetPropertyStr(ctx, obj, "second", JS_NewInt32(ctx, param->second)); JS_SetPropertyStr(ctx, obj, "msecond", JS_NewInt32(ctx, param->msecond)); JS_SetPropertyStr(ctx, obj, "timestamp", JS_NewInt64(ctx, param->timestamp)); JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &obj); JS_FreeValue(ctx, val); JS_FreeValue(ctx, obj); JS_FreeValue(ctx, param->js_cb_ref); amp_free(param); } static void aiot_app_ntp_recv_handler(void *handle, const aiot_ntp_recv_t *packet, void *userdata) { int res = -1; aiot_ntp_notify_param_t *ntp_params; switch (packet->type) { case AIOT_NTPRECV_LOCAL_TIME: /* print topic name and topic message */ amp_debug(MOD_STR, "year: %d, month: %d, day: %d, hour: %d, min: %d, sec: %d, msec: %d, timestamp: %d", packet->data.local_time.year, packet->data.local_time.mon, packet->data.local_time.day, packet->data.local_time.hour, packet->data.local_time.min, packet->data.local_time.sec, packet->data.local_time.msec, packet->data.local_time.timestamp ); g_ntp_time = packet->data.local_time.timestamp; g_up_time = aos_now_ms(); ntp_params = (aiot_ntp_notify_param_t *)userdata; ntp_params->year = packet->data.local_time.year; ntp_params->month = packet->data.local_time.mon; ntp_params->day = packet->data.local_time.day; ntp_params->hour = packet->data.local_time.hour; ntp_params->minute = packet->data.local_time.min; ntp_params->second = packet->data.local_time.sec; ntp_params->msecond = packet->data.local_time.msec; ntp_params->timestamp = packet->data.local_time.timestamp; break; default: amp_free(ntp_params); return; } amp_task_schedule_call(aiot_device_ntp_notify, ntp_params); res = aiot_ntp_deinit(&handle); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "ntp deinit failed"); } } static void aiot_app_ntp_event_handler(void *handle, const aiot_ntp_event_t *event, void *userdata) { switch (event->type) { case AIOT_NTPEVT_INVALID_RESPONSE: /* print topic name and topic message */ amp_debug(MOD_STR, "ntp receive data invalid"); break; case AIOT_NTPEVT_INVALID_TIME_FORMAT: amp_debug(MOD_STR, "ntp receive data error"); break; default: break; } } /* ntp service */ int32_t aiot_amp_ntp_service(void *mqtt_handle, JSValue js_cb_ref) { int32_t res = STATE_SUCCESS; int32_t time_zone = 8; void *ntp_handle = NULL; aiot_ntp_notify_param_t *ntp_params; if (mqtt_handle == NULL) { amp_error(MOD_STR, "ntp service init failed"); return -1; } ntp_handle = aiot_ntp_init(); if (ntp_handle == NULL) { amp_error(MOD_STR, "ntp service init failed"); return -1; } res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_MQTT_HANDLE, (void *)mqtt_handle); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "ntp set mqtt handle failed"); aiot_ntp_deinit(&ntp_handle); return -1; } res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_TIME_ZONE, (void *)&time_zone); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "ntp set time zone failed"); aiot_ntp_deinit(&ntp_handle); return -1; } res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_RECV_HANDLER, (void *)aiot_app_ntp_recv_handler); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "ntp set receive handler failed"); aiot_ntp_deinit(&ntp_handle); return -1; } res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_EVENT_HANDLER, (void *)aiot_app_ntp_event_handler); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "ntp set event handler failed"); aiot_ntp_deinit(&ntp_handle); return -1; } ntp_params = amp_malloc(sizeof(aiot_ntp_notify_param_t)); if (!ntp_params) { amp_error(MOD_STR, "alloc device_ntp_notify_param_t fail"); return; } memset(ntp_params, 0, sizeof(aiot_ntp_notify_param_t)); ntp_params->js_cb_ref = js_cb_ref; res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_USERDATA, ntp_params); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "ntp set user data failed"); aiot_ntp_deinit(&ntp_handle); amp_free(ntp_params); return -1; } res = aiot_ntp_send_request(ntp_handle); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "ntp send request failed"); aiot_ntp_deinit(&ntp_handle); amp_free(ntp_params); return -1; } return res; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/aiot/module_aiot_ntp.c
C
apache-2.0
6,013
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" #include "aos_fs.h" #include "board_mgr.h" #include "aos/vfs.h" #include "uvoice_types.h" #include "uvoice_event.h" #include "uvoice_player.h" #include "uvoice_comb.h" #include "aos_pcm.h" #include "aos_tts.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "audioplayer" typedef struct { uvoice_player_t *player; JSValue js_cb_ref; int list_playing; int state; } audio_player_t; typedef struct { void *userdata; JSValue js_cb_ref; int event; unsigned long timestamp; } audio_player_param_t; enum { AUDIOPLAYER_STAT_STOP = 0, AUDIOPLAYER_STAT_PAUSED = 1, AUDIOPLAYER_STAT_PLAYING = 2, AUDIOPLAYER_STAT_LIST_PLAY_BEGIN = 3, AUDIOPLAYER_STAT_LIST_PLAY_END = 4, AUDIOPLAYER_STAT_ERROR = 5, }; enum { JS_ATOM_NULL, #define DEF(name, str) JS_ATOM_##name, #include "quickjs-atom.h" #undef DEF JS_ATOM_END, }; static audio_player_t *g_audioplayer; static JSClassID js_audioplayer_class_id; static int js_get_length32(JSContext* ctx, uint32_t* pres, JSValueConst obj) { JSValue len_val; len_val = JS_GetProperty(ctx, obj, JS_ATOM_length); if (JS_IsException(len_val)) { *pres = 0; return -1; } return JS_ToInt32(ctx, pres, len_val); } static void audioplayer_state_notify(void *arg) { audio_player_t *audioplayer = (audio_player_t *)arg; JSValue state; JSContext *ctx = js_get_context(); state = JS_NewInt32(ctx, audioplayer->state); JSValue val = JS_Call(ctx, audioplayer->js_cb_ref, JS_UNDEFINED, 1, &state); JS_FreeValue(ctx, val); JS_FreeValue(ctx, state); } static void audioplayer_state_cb(uvoice_event_t *event, void *data) { audio_player_t *audioplayer = (audio_player_t *)data; player_state_t state; int audioplayer_state = PLAYER_STAT_IDLE; int ret; if (!audioplayer) return; if (event->type != UVOICE_EV_PLAYER) return; if (event->code == UVOICE_CODE_PLAYER_STATE) { state = event->value; switch (state) { case PLAYER_STAT_RUNNING: case PLAYER_STAT_COMPLETE: case PLAYER_STAT_RESUME: audioplayer_state = AUDIOPLAYER_STAT_PLAYING; break; case PLAYER_STAT_PAUSED: audioplayer_state = AUDIOPLAYER_STAT_PAUSED; break; case PLAYER_STAT_STOP: case PLAYER_STAT_IDLE: case PLAYER_STAT_READY: audioplayer_state = AUDIOPLAYER_STAT_STOP; break; case PLAYER_STAT_ERROR: audioplayer_state = AUDIOPLAYER_STAT_ERROR; break; case PLAYER_STAT_LIST_PLAY_START: audioplayer_state = AUDIOPLAYER_STAT_LIST_PLAY_BEGIN; audioplayer->list_playing = 1; break; case PLAYER_STAT_LIST_PLAY_STOP: audioplayer_state = AUDIOPLAYER_STAT_LIST_PLAY_END; audioplayer->list_playing = 0; break; default: return; } } if (audioplayer->state == audioplayer_state) { return; } audioplayer->state = audioplayer_state; amp_task_schedule_call(audioplayer_state_notify, audioplayer); } static void audioplayer_play_cplt_notify(void *arg) { audio_player_param_t *param = (audio_player_param_t *)arg; JSContext *ctx = js_get_context(); if (param == NULL) { return; } JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 0, NULL); JS_FreeValue(ctx, val); JS_FreeValue(ctx, param->js_cb_ref); aos_free(param); } static void audioplayer_play_cplt_cb(uvoice_event_t *event, void *data) { audio_player_param_t *param = (audio_player_param_t *)data; if (!param) return; if (event->type != UVOICE_EV_PLAYER) return; if (event->code == UVOICE_CODE_PLAYER_STATE && (event->value == PLAYER_STAT_COMPLETE || event->value == PLAYER_STAT_STOP) && (unsigned long)aos_now_ms() >= param->timestamp) { amp_task_schedule_call(audioplayer_play_cplt_notify, param); uvoice_event_unregister(UVOICE_EV_PLAYER, audioplayer_play_cplt_cb, param); } } static void audioplayer_listplay_cplt_cb(void *data, int event) { audio_player_param_t *param = (audio_player_param_t *)data; param->event = event; amp_task_schedule_call(audioplayer_play_cplt_notify, param); } static JSValue native_audioplayer_play(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; audio_player_param_t *param = NULL; uvoice_player_t *player; char *audiosource = NULL; char *source = NULL; int len; int is_http = 0; int ret = -1; if (!audioplayer) goto out; player = audioplayer->player; if (!JS_IsString(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_error(MOD_STR, "parameter must be (string, function)"); goto out; } param = aos_malloc(sizeof(audio_player_param_t)); if (!param) { amp_error(MOD_STR, "alloc param fail"); goto out; } audiosource = (char *)JS_ToCString(ctx, argv[0]); if (!audiosource) { amp_error(MOD_STR, "audio source null"); goto out; } if (!strncmp(audiosource, "http", strlen("http"))) { is_http = 1; source = audiosource; } else { source = aos_malloc(strlen(audiosource) + 4); if (!source) { amp_error(MOD_STR, "alloc source fail"); goto out; } snprintf(source, strlen(audiosource) + 4, "fs:%s", audiosource); } if (!JS_IsFunction(ctx, argv[1])) { JS_ThrowTypeError(ctx, "not a function"); goto out; } param->js_cb_ref = JS_DupValue(ctx, argv[1]); param->timestamp = (unsigned long)aos_now_ms(); if (comb_add_http_source(source, 0)) { amp_error(MOD_STR, "add source fail"); JS_FreeValue(ctx, param->js_cb_ref); goto out; } if (uvoice_event_register(UVOICE_EV_PLAYER, audioplayer_play_cplt_cb, param)) { amp_error(MOD_STR, "register event fail"); JS_FreeValue(ctx, param->js_cb_ref); aos_free(param); goto out; } ret = 0; out: if (!is_http && source) { aos_free(source); } if(audiosource != NULL) { JS_FreeCString(ctx, audiosource); } return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_stop(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; int ret = -1; if (!audioplayer) goto out; player = audioplayer->player; if (player->stop()) { comb_clr_http_source(); goto out; } player->clr_source(); comb_clr_http_source(); ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_pause(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; int ret = -1; if (!audioplayer) goto out; player = audioplayer->player; if (player->pause()) { amp_error(MOD_STR, "play pause fail"); goto out; } ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_resume(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; int ret = -1; if (!audioplayer) goto out; player = audioplayer->player; if (player->resume()) { amp_error(MOD_STR, "play resume fail"); goto out; } ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_seekto(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; int ret = -1; int seconds; if (!audioplayer) goto out; player = audioplayer->player; if (!JS_IsNumber(argv[0])) { amp_error(MOD_STR, "parameter must be (number)"); goto out; } JS_ToInt32(ctx, &seconds, argv[0]); if (seconds < 0) { amp_error(MOD_STR, "seconds %d invalid", seconds); goto out; } if (player->seek(seconds)) { amp_error(MOD_STR, "seek to %d fail", seconds); goto out; } ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_position_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; int position = 0; int ret = -1; if (!audioplayer) goto out; player = audioplayer->player; if (player->get_position(&position)) { amp_error(MOD_STR, "get position fail"); goto out; } ret = position; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_duration_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; int duration = 0; int ret = -1; if (!audioplayer) goto out; player = audioplayer->player; if (player->get_duration(&duration)) { amp_error(MOD_STR, "get duration fail"); goto out; } ret = duration; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_state_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; player_state_t state = PLAYER_STAT_IDLE; int audioplayer_state; int ret = -1; if (!audioplayer) goto out; player = audioplayer->player; if (player->get_state(&state)) { amp_error(MOD_STR, "get player state fail"); goto out; } switch (state) { case PLAYER_STAT_RUNNING: case PLAYER_STAT_COMPLETE: case PLAYER_STAT_RESUME: audioplayer_state = AUDIOPLAYER_STAT_PLAYING; break; case PLAYER_STAT_PAUSED: audioplayer_state = AUDIOPLAYER_STAT_PAUSED; break; case PLAYER_STAT_STOP: case PLAYER_STAT_IDLE: case PLAYER_STAT_READY: audioplayer_state = AUDIOPLAYER_STAT_STOP; break; case PLAYER_STAT_ERROR: audioplayer_state = AUDIOPLAYER_STAT_ERROR; break; case PLAYER_STAT_LIST_PLAY_START: audioplayer_state = AUDIOPLAYER_STAT_LIST_PLAY_BEGIN; break; case PLAYER_STAT_LIST_PLAY_STOP: audioplayer_state = AUDIOPLAYER_STAT_LIST_PLAY_END; break; default: audioplayer_state = AUDIOPLAYER_STAT_STOP; break; } ret = audioplayer_state; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_state_on(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; int ret = -1; if (!JS_IsFunction(ctx, argv[0])) { amp_warn(MOD_STR, "parameter must be (function)"); goto out; } JSValue state_cb = argv[0]; if (!JS_IsFunction(ctx, state_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } audioplayer->js_cb_ref = JS_DupValue(ctx, state_cb); if (uvoice_event_register(UVOICE_EV_PLAYER, audioplayer_state_cb, audioplayer)) { amp_error(MOD_STR, "register event fail"); goto out; } ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_volume_set(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; int ret = -1; int volume; if (!audioplayer) goto out; player = audioplayer->player; if (!JS_IsNumber(argv[0])) { amp_error(MOD_STR, "parameter must be (number)"); goto out; } JS_ToInt32(ctx, &volume, argv[0]); if (volume < 0) { amp_error(MOD_STR, "volume %d invalid", volume); goto out; } if (player->set_volume(volume)) { amp_error(MOD_STR, "set volume fail"); goto out; } ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_volume_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; int ret = -1; int volume = -1; if (!audioplayer) goto out; player = audioplayer->player; if (player->get_volume(&volume)) { amp_error(MOD_STR, "get volume fail"); goto out; } ret = volume; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_play_list(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_player_param_t *param; char *source; int arr_idx; int arr_cnt; int i, ret = -1; int error = 0; struct aos_stat stat; comb_source_info_t *info; if (!JS_IsArray(ctx, argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_error(MOD_STR, "parameter must be (array, function)"); goto out; } param = aos_malloc(sizeof(audio_player_param_t)); if (!param) { amp_error(MOD_STR, "alloc param fail"); goto out; } info = aos_malloc(sizeof(comb_source_info_t)); if (!info) { amp_error(MOD_STR, "alloc info fail"); aos_free(param); goto out; } memset(info, 0, sizeof(comb_source_info_t)); js_get_length32(ctx, &arr_cnt, argv[0]); if (arr_cnt > COMB_SOURCE_LIST_MAX) { amp_error(MOD_STR, "list count out of limit"); aos_free(param); aos_free(info); goto out; } JSValue play_cb = argv[1]; if (!JS_IsFunction(ctx, play_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } param->js_cb_ref = JS_DupValue(ctx, play_cb); for (i = 0; i < arr_cnt; i++) { JSValue str_val = JS_GetPropertyUint32(ctx, argv[0], i); if (!JS_IsString(str_val)) { amp_error(MOD_STR, "array element %d is not string", i); JS_FreeValue(ctx, param->js_cb_ref); aos_free(param); aos_free(info); goto out; } source = JS_ToCString(ctx, str_val); if (strlen(source) >= COMB_SOURCE_PATH_LEN) { amp_error(MOD_STR, "source %s path too long", source); JS_FreeValue(ctx, param->js_cb_ref); aos_free(param); aos_free(info); JS_FreeCString(ctx, source); goto out; } memset(&stat, 0, sizeof(aos_stat)); ret = aos_stat(source, &stat); if (ret < 0 || !S_ISREG(stat.st_mode)) { amp_error(MOD_STR, "source %s not exist", source); JS_FreeValue(ctx, param->js_cb_ref); aos_free(param); aos_free(info); ret = -1; JS_FreeCString(ctx, source); goto out; } info->count++; snprintf(info->sources[i], COMB_SOURCE_PATH_LEN, "%s", source); JS_FreeCString(ctx, source); } info->callback = audioplayer_listplay_cplt_cb; info->userdata = param; if (comb_add_file_source_list(info)) { error = -1; } aos_free(info); ret = error; out: return JS_NewInt32(ctx, ret); } static JSValue native_audioplayer_play_list_stop(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { comb_play_stop(); comb_clr_http_source(); return JS_NewInt32(ctx, 0); } static int native_audioplayer_config_parse(uvoice_player_t *player) { item_handle_t item_handle; item_handle.handle = NULL; aos_audio_dev_t *audio_dev; audio_extpa_info_t pa_info; if (board_attach_item(MODULE_AUDIO, "audio", &item_handle)) { player->set_out_device(AOS_SND_DEVICE_OUT_HEADPHONE); #ifdef JSE_ADVANCED_ADDON_TTS aos_tts_set_out_device(AOS_SND_DEVICE_OUT_HEADPHONE); #endif } else { audio_dev = board_get_node_by_handle(MODULE_AUDIO, &item_handle); if (!audio_dev) { amp_warn(MOD_STR, "get audio module fail"); return -1; } else { amp_info(MOD_STR, "out device %d, ext pa %s, pin %d, delay %d, active %d", audio_dev->out_device, audio_dev->external_pa ? "enable" : "disable", audio_dev->external_pa_pin, audio_dev->external_pa_delay_ms, audio_dev->external_pa_active_high); } if (audio_dev->out_device >= AOS_SND_DEVICE_OUT_SPEAKER && audio_dev->out_device < AOS_SND_DEVICE_MAX) { player->set_out_device(audio_dev->out_device); #ifdef JSE_ADVANCED_ADDON_TTS aos_tts_set_out_device(audio_dev->out_device); #endif } else { player->set_out_device(AOS_SND_DEVICE_OUT_HEADPHONE); #ifdef JSE_ADVANCED_ADDON_TTS aos_tts_set_out_device(AOS_SND_DEVICE_OUT_HEADPHONE); #endif } if (audio_dev->external_pa) { pa_info.used = audio_dev->external_pa; pa_info.active_high = audio_dev->external_pa_active_high; pa_info.pin = audio_dev->external_pa_pin; pa_info.delay_ms = audio_dev->external_pa_delay_ms; player->set_external_pa(&pa_info); } } return 0; } static void module_audioplayer_source_clean(void) { audio_player_t *audioplayer = g_audioplayer; uvoice_player_t *player; if (!audioplayer) return; player = audioplayer->player; if (!player) { return; } comb_play_stop(); comb_clr_http_source(); player->stop(); player->clr_source(); uvoice_player_release(player); aos_free(audioplayer); g_audioplayer = NULL; comb_deinit(); uvoice_free(); } static JSClassDef js_audioplayer_class = { "AUDIOPLAYER", }; static const JSCFunctionListEntry js_audioplayer_funcs[] = { JS_CFUNC_DEF("listPlay", 2, native_audioplayer_play_list), JS_CFUNC_DEF("listPlayStop",0, native_audioplayer_play_list_stop), JS_CFUNC_DEF("play", 2, native_audioplayer_play), JS_CFUNC_DEF("stop", 0, native_audioplayer_stop), JS_CFUNC_DEF("pause", 0, native_audioplayer_pause), JS_CFUNC_DEF("resume", 0, native_audioplayer_resume), JS_CFUNC_DEF("seekto", 1, native_audioplayer_seekto), JS_CFUNC_DEF("getPosition", 0, native_audioplayer_position_get), JS_CFUNC_DEF("getDuration", 0, native_audioplayer_duration_get), JS_CFUNC_DEF("getState", 0, native_audioplayer_state_get), JS_CFUNC_DEF("onState", 1, native_audioplayer_state_on), JS_CFUNC_DEF("setVolume", 1, native_audioplayer_volume_set), JS_CFUNC_DEF("getVolume", 0, native_audioplayer_volume_get) }; static int js_audioplayer_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_audioplayer_class_id); JS_NewClass(JS_GetRuntime(ctx), js_audioplayer_class_id, &js_audioplayer_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_audioplayer_funcs, countof(js_audioplayer_funcs)); JS_SetClassProto(ctx, js_audioplayer_class_id, proto); return JS_SetModuleExportList(ctx, m, js_audioplayer_funcs, countof(js_audioplayer_funcs)); } JSModuleDef *js_init_module_audio(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_audioplayer_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_audioplayer_funcs, countof(js_audioplayer_funcs)); return m; } void module_audioplayer_register(void) { audio_player_t *audioplayer; uvoice_init(); // init audio codec extern int audio_install_codec_driver(); audio_install_codec_driver(); comb_init(); audioplayer = aos_malloc(sizeof(audio_player_t)); if (!audioplayer) { amp_error(MOD_STR, "alloc audio player fail"); return; } audioplayer->player = uvoice_player_create(); if (!audioplayer->player) { amp_error(MOD_STR, "create uvoice player fail"); aos_free(audioplayer); return; } native_audioplayer_config_parse(audioplayer->player); audioplayer->state = -1; g_audioplayer = audioplayer; amp_module_free_register(module_audioplayer_source_clean); amp_debug(MOD_STR, "module_audioplayer_register"); JSContext *ctx = js_get_context(); js_init_module_audio(ctx, "AUDIOPLAYER"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/audio/module_audioplayer.c
C
apache-2.0
20,847
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" #include "aos_fs.h" #include "board_mgr.h" #include "aos/vfs.h" #include "uvoice_types.h" #include "uvoice_event.h" #include "uvoice_recorder.h" #include "aos_pcm.h" #include "aos_tts.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "audiorecorder" typedef struct { uvoice_recorder_t *recorder; int state; } audio_recorder_t; enum { AUDIORECORDER_STAT_STOP = 0, AUDIORECORDER_STAT_PAUSED = 1, AUDIORECORDER_STAT_RECORDING = 2, AUDIORECORDER_STAT_ERROR = 5, }; static audio_recorder_t *g_audiorecorder; static JSClassID js_audiorecorder_class_id; static JSValue native_audiorecorder_record(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_recorder_t *audiorecorder = g_audiorecorder; uvoice_recorder_t *recorder; media_format_t format = MEDIA_FMT_UNKNOWN; const char *sink; char *sink_path = NULL; int samplerate, channels, sbits, frames; int ret = -1; if (!audiorecorder) goto out; recorder = audiorecorder->recorder; if (!JS_IsNumber(argv[0]) || !JS_IsNumber(argv[1]) || !JS_IsNumber(argv[2]) || !JS_IsNumber(argv[3]) || !JS_IsString(argv[4])) { amp_error(MOD_STR, "parameter must be (number, number, number, number, string)"); goto out; } JS_ToInt32(ctx, &samplerate, argv[0]); JS_ToInt32(ctx, &channels, argv[1]); JS_ToInt32(ctx, &sbits, argv[2]); JS_ToInt32(ctx, &frames, argv[3]); sink = (char *)JS_ToCString(ctx, argv[4]); if (!sink) { amp_error(MOD_STR, "audio sink null"); goto out; } sink_path = aos_malloc(strlen(sink) + 4); if (!sink_path) { amp_error(MOD_STR, "alloc sink buffer fail"); goto out; } snprintf(sink_path, strlen(sink) + 4, "fs:%s", sink); ret = recorder->set_sink(MEDIA_FMT_UNKNOWN, samplerate, channels, sbits, frames, 0, sink_path); if (ret) { amp_error(MOD_STR, "set sink %s fail", sink_path); ret = -1; goto out; } ret = recorder->start(); if (ret) { amp_error(MOD_STR, "recorder start fail"); recorder->clr_sink(); ret = -1; goto out; } ret = 0; out: if (sink_path) { aos_free(sink_path); } return JS_NewInt32(ctx, ret); } static JSValue native_audiorecorder_stop(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_recorder_t *audiorecorder = g_audiorecorder; uvoice_recorder_t *recorder; int ret = -1; if (!audiorecorder) goto out; recorder = audiorecorder->recorder; if (recorder->stop()) { amp_error(MOD_STR, "recorder stop fail"); goto out; } recorder->clr_sink(); ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_audiorecorder_pause(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_recorder_t *audiorecorder = g_audiorecorder; uvoice_recorder_t *recorder; int ret = -1; if (!audiorecorder) goto out; recorder = audiorecorder->recorder; if (recorder->stop()) { amp_error(MOD_STR, "recorder pause fail"); goto out; } ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_audiorecorder_resume(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_recorder_t *audiorecorder = g_audiorecorder; uvoice_recorder_t *recorder; int ret = -1; if (!audiorecorder) goto out; recorder = audiorecorder->recorder; if (recorder->start()) { amp_error(MOD_STR, "recorder resume fail"); goto out; } ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_audiorecorder_position_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_recorder_t *audiorecorder = g_audiorecorder; uvoice_recorder_t *recorder; int position = 0; int ret = -1; if (!audiorecorder) goto out; recorder = audiorecorder->recorder; if (recorder->get_position(&position)) { amp_error(MOD_STR, "get position fail"); goto out; } ret = position; out: return JS_NewInt32(ctx, ret); } static JSValue native_audiorecorder_state_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { audio_recorder_t *audiorecorder = g_audiorecorder; uvoice_recorder_t *recorder; recorder_state_t state = RECORDER_STAT_IDLE; int audiorecorder_state; int ret = -1; if (!audiorecorder) goto out; recorder = audiorecorder->recorder; if (recorder->get_state(&state)) { amp_error(MOD_STR, "get recorder state fail"); goto out; } switch (state) { case RECORDER_STAT_RUNNING: audiorecorder_state = AUDIORECORDER_STAT_RECORDING; break; case RECORDER_STAT_STOP: audiorecorder_state = AUDIORECORDER_STAT_PAUSED; break; case RECORDER_STAT_IDLE: case RECORDER_STAT_READY: audiorecorder_state = AUDIORECORDER_STAT_STOP; break; case RECORDER_STAT_ERROR: audiorecorder_state = AUDIORECORDER_STAT_ERROR; break; default: audiorecorder_state = AUDIORECORDER_STAT_STOP; break; } ret = audiorecorder_state; out: return JS_NewInt32(ctx, ret); } static void module_audiorecorder_source_clean(void) { audio_recorder_t *audiorecorder = g_audiorecorder; uvoice_recorder_t *recorder; if (!audiorecorder) return; recorder = audiorecorder->recorder; if (!recorder) { return; } recorder->stop(); recorder->clr_sink(); uvoice_recorder_release(recorder); amp_free(audiorecorder); g_audiorecorder = NULL; uvoice_free(); } static JSClassDef js_audiorecorder_class = { "AUDIORECORDER", }; static const JSCFunctionListEntry js_audiorecorder_funcs[] = { JS_CFUNC_DEF("record", 5, native_audiorecorder_record), JS_CFUNC_DEF("stop", 0, native_audiorecorder_stop), JS_CFUNC_DEF("pause", 0, native_audiorecorder_pause), JS_CFUNC_DEF("resume", 0, native_audiorecorder_resume), JS_CFUNC_DEF("getPosition", 0, native_audiorecorder_position_get), JS_CFUNC_DEF("getState", 0, native_audiorecorder_state_get) }; static int js_audiorecorder_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_audiorecorder_class_id); JS_NewClass(JS_GetRuntime(ctx), js_audiorecorder_class_id, &js_audiorecorder_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_audiorecorder_funcs, countof(js_audiorecorder_funcs)); JS_SetClassProto(ctx, js_audiorecorder_class_id, proto); return JS_SetModuleExportList(ctx, m, js_audiorecorder_funcs, countof(js_audiorecorder_funcs)); } JSModuleDef *js_init_module_audiorecorder(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_audiorecorder_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_audiorecorder_funcs, countof(js_audiorecorder_funcs)); return m; } void module_audiorecorder_register(void) { audio_recorder_t *audiorecorder; uvoice_init(); audiorecorder = aos_malloc(sizeof(audio_recorder_t)); if (!audiorecorder) { amp_error(MOD_STR, "alloc audio recorder fail"); return; } audiorecorder->recorder = uvoice_recorder_create(); if (!audiorecorder->recorder) { amp_error(MOD_STR, "create uvoice recorder fail"); aos_free(audiorecorder); return; } audiorecorder->state = -1; g_audiorecorder = audiorecorder; amp_module_free_register(module_audiorecorder_source_clean); amp_debug(MOD_STR, "module_audiorecorder_register"); JSContext *ctx = js_get_context(); js_init_module_audiorecorder(ctx, "AUDIORECORDER"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/audio/module_audiorecorder.c
C
apache-2.0
8,134
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "aos_system.h" #include "amp_defines.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "BLECFGNET" static JSClassID js_blecfgnet_class_id; static JSValue native_blecfgnet_start(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; ret = BleCfg_run(); if (ret != 0) { amp_warn(MOD_STR, "ble config net start failed"); } out: return JS_NewInt32(ctx, ret); } static JSValue native_blecfgnet_recovery_wifi(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; ret = BleCfg_recovery_wifi(); if (ret != 0) { amp_warn(MOD_STR, "ble config net recovery wifi failed"); } out: return JS_NewInt32(ctx, ret); } static JSValue native_blecfgnet_recovery_devinfo(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; ret = BleCfg_recovery_devinfo(); if (ret != 0) { amp_warn(MOD_STR, "ble config net recovery device info failed"); } out: return JS_NewInt32(ctx, ret); } static JSClassDef js_blecfgnet_class = { "blecfgnet", }; static const JSCFunctionListEntry js_blecfgnet_funcs[] = { JS_CFUNC_DEF("start", 0, native_blecfgnet_start), JS_CFUNC_DEF("recoveryWifi", 0, native_blecfgnet_recovery_wifi), JS_CFUNC_DEF("recoveryDevInfo", 0, native_blecfgnet_recovery_devinfo) }; static int js_blecfgnet_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_blecfgnet_class_id); JS_NewClass(JS_GetRuntime(ctx), js_blecfgnet_class_id, &js_blecfgnet_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_blecfgnet_funcs, countof(js_blecfgnet_funcs)); JS_SetClassProto(ctx, js_blecfgnet_class_id, proto); return JS_SetModuleExportList(ctx, m, js_blecfgnet_funcs, countof(js_blecfgnet_funcs)); } JSModuleDef *js_init_module_blecfgnet(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_blecfgnet_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_blecfgnet_funcs, countof(js_blecfgnet_funcs)); return m; } void module_blecfgnet_register(void) { amp_debug(MOD_STR, "module_blecfgnet_register"); JSContext *ctx = js_get_context(); js_init_module_blecfgnet(ctx, "BLECFGNET"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/blenetcfg/module_blecfgnet.c
C
apache-2.0
2,503
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "amp_config.h" #include "aos_system.h" #include "amp_defines.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "ulog/ulog.h" #include "oss_app.h" #define MOD_STR "MOD_OSS" #define MAX_URL_LENGTH 256 static aos_sem_t g_oss_task_sem = NULL; static JSClassID js_oss_class_id; static char oss_resp_url[MAX_URL_LENGTH]; typedef struct { int flag; //0: upload; 1: download; char *key; char *secret; char *endPoint; char *bucketName; char *objectName; char *filePath; } oss_task_param; static void oss_task_handler(void *arg) { char *url = NULL; oss_task_param *task_param = (oss_task_param *)arg; if(task_param->flag == 0) { url = oss_upload_file(task_param->key, task_param->secret, task_param->endPoint, task_param->bucketName, task_param->objectName, task_param->filePath); memset(oss_resp_url, 0, MAX_URL_LENGTH); strncpy(oss_resp_url, url, MAX_URL_LENGTH); } else { oss_download_file(task_param->key, task_param->secret, task_param->endPoint, task_param->bucketName, task_param->objectName, task_param->filePath); } aos_printf("oss task finished! \n"); aos_sem_signal(&g_oss_task_sem); } static JSValue native_oss_upload_file(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; aos_task_t oss_task; oss_task_param task_param; if (argc < 6) { amp_error(MOD_STR, "%s: args num is illegal :n_args = %d;\n", __func__, argc); return JS_NewInt32(ctx, 0); } task_param.flag = 0; task_param.key = (char *)JS_ToCString(ctx, argv[0]); task_param.secret = (char *)JS_ToCString(ctx, argv[1]); task_param.endPoint = (char *)JS_ToCString(ctx, argv[2]); task_param.bucketName = (char *)JS_ToCString(ctx, argv[3]); task_param.objectName = (char *)JS_ToCString(ctx, argv[4]); task_param.filePath = (char *)JS_ToCString(ctx, argv[5]); // amp_debug(MOD_STR, "key = %s;\n", task_param.key); // amp_debug(MOD_STR, "secret = %s;\n", task_param.secret); amp_debug(MOD_STR, "endPoint = %s;\n", task_param.endPoint); amp_debug(MOD_STR, "bucketName = %s;\n", task_param.bucketName); amp_debug(MOD_STR, "objectName = %s;\n", task_param.objectName); amp_debug(MOD_STR, "filePath = %s;\n", task_param.filePath); aos_task_new_ext(&oss_task, "amp oss task", oss_task_handler, &task_param, 1024 * 10, AOS_DEFAULT_APP_PRI); aos_sem_wait(&g_oss_task_sem, AOS_WAIT_FOREVER); JS_FreeCString(ctx, task_param.key); JS_FreeCString(ctx, task_param.secret); JS_FreeCString(ctx, task_param.endPoint); JS_FreeCString(ctx, task_param.bucketName); JS_FreeCString(ctx, task_param.objectName); JS_FreeCString(ctx, task_param.filePath); aos_printf("oss upload finished! %s\n", oss_resp_url); return JS_NewString(ctx, oss_resp_url); } static JSValue native_oss_download_file(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; char * url = NULL; aos_task_t oss_task; oss_task_param task_param; if (argc < 5) { amp_error(MOD_STR, "%s: args num is illegal :n_args = %d;\n", __func__, argc); return JS_NewInt32(ctx, 0); } task_param.flag = 1; task_param.key = (char *)JS_ToCString(ctx, argv[0]); task_param.secret = (char *)JS_ToCString(ctx, argv[1]); task_param.endPoint = (char *)JS_ToCString(ctx, argv[2]); task_param.bucketName = (char *)JS_ToCString(ctx, argv[3]); task_param.objectName = (char *)JS_ToCString(ctx, argv[4]); task_param.filePath = (char *)JS_ToCString(ctx, argv[5]); // amp_debug(MOD_STR, "key = %s;\n", task_param.key); // amp_debug(MOD_STR, "secret = %s;\n", task_param.secret); amp_debug(MOD_STR, "endPoint = %s;\n", task_param.endPoint); amp_debug(MOD_STR, "bucketName = %s;\n", task_param.bucketName); amp_debug(MOD_STR, "objectName = %s;\n", task_param.objectName); amp_debug(MOD_STR, "filePath = %s;\n", task_param.filePath); aos_task_new_ext(&oss_task, "amp oss task", oss_task_handler, &task_param, 1024 * 10, AOS_DEFAULT_APP_PRI); aos_sem_wait(&g_oss_task_sem, AOS_WAIT_FOREVER); JS_FreeCString(ctx, task_param.key); JS_FreeCString(ctx, task_param.secret); JS_FreeCString(ctx, task_param.endPoint); JS_FreeCString(ctx, task_param.bucketName); JS_FreeCString(ctx, task_param.objectName); JS_FreeCString(ctx, task_param.filePath); aos_printf("oss download finished!\n"); return JS_NewInt32(ctx, 0); } static JSClassDef js_oss_class = { "oss", }; static const JSCFunctionListEntry js_oss_funcs[] = { JS_CFUNC_DEF("uploadFile", 5, native_oss_upload_file ), JS_CFUNC_DEF("downloadFile", 5, native_oss_download_file ), }; static int js_oss_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_oss_class_id); JS_NewClass(JS_GetRuntime(ctx), js_oss_class_id, &js_oss_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_oss_funcs, countof(js_oss_funcs)); JS_SetClassProto(ctx, js_oss_class_id, proto); return JS_SetModuleExportList(ctx, m, js_oss_funcs, countof(js_oss_funcs)); } JSModuleDef *js_init_module_oss(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_oss_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_oss_funcs, countof(js_oss_funcs)); return m; } void module_oss_register(void) { amp_debug(MOD_STR, "module_oss_register"); if (!g_oss_task_sem) { if (aos_sem_new(&g_oss_task_sem, 0) != 0) { amp_error(MOD_STR, "create amp oss sem fail"); } } JSContext *ctx = js_get_context(); js_init_module_oss(ctx, "oss"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/oss/module_oss.c
C
apache-2.0
5,993
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "aos_system.h" #include "amp_defines.h" #include "ota_agent.h" #include "ota_import.h" #include "module_aiot.h" #include "app_upgrade.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "amp_task.h" #define MOD_STR "APP_OTA" static ota_service_t customer_ota_ctx = {0}; static ota_store_module_info_t customer_module_info[3]; static aos_task_t user_module_ota_task = NULL; typedef struct ota_package_info { int res; JSValue js_cb_ref; unsigned int length; char version[64]; char module_name[64]; int hash_type; char hash[64]; char store_path[64]; char install_path[64]; char url[256]; } ota_package_info_t; static JSClassID js_appota_class_id; #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif static void ota_release_notify(void *pdata) { ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata; if (!ota_package_info) { return; } JSContext *ctx = js_get_context(); if (ctx) { JS_FreeValue(ctx, ota_package_info->js_cb_ref); } aos_free(ota_package_info); } static void ota_install_notify(void *pdata) { ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata; if (!ota_package_info) { amp_error(MOD_STR, "ota_package_info null!"); return; } JSContext *ctx = js_get_context(); if (!ctx) { amp_error(MOD_STR, "JSContext null!"); return; } JSValue ret = JS_NewInt32(ctx, ota_package_info->res); JSValue v = JS_Call(ctx, ota_package_info->js_cb_ref, JS_UNDEFINED, 1, &ret); if (JS_IsException(v)) { amp_error(MOD_STR, "ota_install_notify callback error!"); } JS_FreeValue(ctx, ret); JS_FreeValue(ctx, v); JS_FreeValue(ctx, ota_package_info->js_cb_ref); aos_free(ota_package_info); } static void ota_install_handler(void *pdata) { amp_warn(MOD_STR, "ota_install_handler!"); int res = -1; ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata; /* clear jsengine timer, distory js app*/ amp_module_free(); app_js_stop(); res = ota_install_jsapp(&customer_ota_ctx, ota_package_info->store_path, ota_package_info->length, ota_package_info->install_path); if (res < 0) { amp_error(MOD_STR, "module install failed!"); } else { /*启动app.js*/ res = ota_load_jsapp(&customer_ota_ctx); if(res < 0) { amp_error(MOD_STR, "module load failed!"); } } ota_package_info->res = res; amp_task_schedule_call(ota_install_notify, ota_package_info); aos_task_exit(0); } static JSValue native_ota_upgrade(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; aos_task_t ota_install_task; ota_package_info_t *ota_package_info = NULL; if (argc < 2 || !JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be (object and function)"); goto out; } ota_package_info = aos_malloc(sizeof(ota_package_info_t)); if (!ota_package_info) { amp_error(MOD_STR, "alloc device notify param fail"); goto out; } JSValue l = JS_GetPropertyStr(ctx, argv[0], "length"); JSValue sp = JS_GetPropertyStr(ctx, argv[0], "store_path"); JSValue ip = JS_GetPropertyStr(ctx, argv[0], "install_path"); unsigned int length = 0; JS_ToUint32(ctx, &length, l); const char* store_path = JS_ToCString(ctx, sp); const char* install_path = JS_ToCString(ctx, ip); ota_package_info->length = length; ota_package_info->js_cb_ref = JS_DupValue(ctx, argv[1]); strncpy(ota_package_info->store_path, store_path, sizeof(ota_package_info->store_path)); strncpy(ota_package_info->install_path, install_path, sizeof(ota_package_info->install_path)); res = aos_task_new_ext(&ota_install_task, "amp ota install task", ota_install_handler, ota_package_info, 1024 * 10, AOS_DEFAULT_APP_PRI); if (res != 0) { amp_warn(MOD_STR, "iot create task failed"); JS_FreeValue(ctx, ota_package_info->js_cb_ref); aos_free(ota_package_info); } JS_FreeValue(ctx, l); JS_FreeValue(ctx, sp); JS_FreeValue(ctx, ip); JS_FreeCString(ctx, store_path); JS_FreeCString(ctx, install_path); out: return JS_NewInt32(ctx, res); } static void ota_verify_notify(void *pdata) { ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata; if (!ota_package_info) { amp_error(MOD_STR, "ota_package_info null!"); return; } JSContext *ctx = js_get_context(); if (!ctx) { amp_error(MOD_STR, "JSContext null!"); return; } JSValue ret = JS_NewInt32(ctx, ota_package_info->res); JSValue v = JS_Call(ctx, ota_package_info->js_cb_ref, JS_UNDEFINED, 1, &ret); if (JS_IsException(v)) { amp_error(MOD_STR, "ota_verify_notify callback error!"); } JS_FreeValue(ctx, ret); JS_FreeValue(ctx, v); JS_FreeValue(ctx, ota_package_info->js_cb_ref); aos_free(ota_package_info); } static void ota_verify_handler(void *pdata) { int res = -1; ota_boot_param_t ota_param = {0}; ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata; memset(&ota_param, 0, sizeof(ota_boot_param_t)); ota_param.len = ota_package_info->length; ota_param.hash_type = ota_package_info->hash_type; strncpy(ota_param.hash, ota_package_info->hash, strlen(ota_package_info->hash)); res = ota_verify_fsfile(&ota_param, ota_package_info->store_path); if (res < 0) { amp_error(MOD_STR, "amp jsota report ver failed!"); } ota_package_info->res = res; amp_task_schedule_call(ota_verify_notify, ota_package_info); aos_task_exit(0); } static JSValue native_ota_verify(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; aos_task_t ota_verify_task; ota_package_info_t *ota_package_info = NULL; if (argc < 2 || !JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be (object and function)"); goto out; } ota_package_info = aos_malloc(sizeof(ota_package_info_t)); if (!ota_package_info) { amp_error(MOD_STR, "alloc device notify param fail"); goto out; } JSValue l = JS_GetPropertyStr(ctx, argv[0], "length"); JSValue ht = JS_GetPropertyStr(ctx, argv[0], "hash_type"); JSValue h = JS_GetPropertyStr(ctx, argv[0], "hash"); JSValue sp = JS_GetPropertyStr(ctx, argv[0], "store_path"); unsigned int length = 0; const char *hash_type_string = JS_ToCString(ctx, ht); const char *hash = JS_ToCString(ctx, h); const char *store_path = JS_ToCString(ctx, sp); JS_ToUint32(ctx, &length, l); ota_package_info->length = length; if (strcmp(hash_type_string, "null") == 0) { ota_package_info->hash_type = 0; } else if(strcmp(hash_type_string, "md5") == 0) { ota_package_info->hash_type = 2; } else if(strcmp(hash_type_string, "sha256") == 0) { ota_package_info->hash_type = 1; } else { ota_package_info->hash_type = 3; } ota_package_info->js_cb_ref = JS_DupValue(ctx, argv[1]); strncpy(ota_package_info->hash, hash, sizeof(ota_package_info->hash)); strncpy(ota_package_info->store_path, store_path, sizeof(ota_package_info->store_path)); res = aos_task_new_ext(&ota_verify_task, "amp ota verify task", ota_verify_handler, ota_package_info, 1024 * 10, AOS_DEFAULT_APP_PRI); if (res != 0) { amp_warn(MOD_STR, "iot create task failed"); JS_FreeValue(ctx, ota_package_info->js_cb_ref); aos_free(ota_package_info); } JS_FreeValue(ctx, l); JS_FreeValue(ctx, ht); JS_FreeValue(ctx, h); JS_FreeValue(ctx, sp); JS_FreeCString(ctx, hash); JS_FreeCString(ctx, store_path); JS_FreeCString(ctx, hash_type_string); out: return JS_NewInt32(ctx, res); } static void ota_download_notify(void *pdata) { ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata; if (!ota_package_info) { amp_error(MOD_STR, "ota_package_info null!"); return; } JSContext *ctx = js_get_context(); if (!ctx) { amp_error(MOD_STR, "JSContext null!"); return; } JSValue ret = JS_NewInt32(ctx, ota_package_info->res); JSValue v = JS_Call(ctx, ota_package_info->js_cb_ref, JS_UNDEFINED, 1, &ret); if (JS_IsException(v)) { amp_error(MOD_STR, "ota_download_notify callback error!"); } JS_FreeValue(ctx, ret); JS_FreeValue(ctx, v); JS_FreeValue(ctx, ota_package_info->js_cb_ref); aos_free(ota_package_info); } static void ota_download_handler(void *pdata) { int res = -1; int js_cb_ref; ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata; res = ota_download_store_fs_start(ota_package_info->url, strlen(ota_package_info->url), ota_package_info->store_path, customer_ota_ctx.report_func.report_status_cb, customer_ota_ctx.report_func.param); if (res < 0) { amp_error(MOD_STR, "amp jsota report ver failed!"); } ota_package_info->res = res; amp_task_schedule_call(ota_download_notify, ota_package_info); aos_task_exit(0); } static JSValue native_ota_download(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; aos_task_t ota_download_task; ota_package_info_t *ota_package_info = NULL; if (argc < 2 || !JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be (object and function)"); goto out; } ota_package_info = aos_malloc(sizeof(ota_package_info_t)); if (!ota_package_info) { amp_error(MOD_STR, "alloc device notify param fail"); goto out; } /* get report info */ JSValue u = JS_GetPropertyStr(ctx, argv[0], "url"); JSValue sp = JS_GetPropertyStr(ctx, argv[0], "store_path"); const char* url = JS_ToCString(ctx, u); const char* store_path = JS_ToCString(ctx, sp); ota_package_info->js_cb_ref = JS_DupValue(ctx, argv[1]); strncpy(ota_package_info->url, url, sizeof(ota_package_info->url)); strncpy(ota_package_info->store_path, store_path, sizeof(ota_package_info->store_path)); res = aos_task_new_ext(&ota_download_task, "amp ota download task", ota_download_handler, ota_package_info, 1024 * 10, AOS_DEFAULT_APP_PRI); if (res != 0) { amp_warn(MOD_STR, "iot create task failed"); JS_FreeValue(ctx, ota_package_info->js_cb_ref); aos_free(ota_package_info); } JS_FreeValue(ctx, u); JS_FreeValue(ctx, sp); JS_FreeCString(ctx, url); JS_FreeCString(ctx, store_path); out: return JS_NewInt32(ctx, res); } static JSValue native_ota_report(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; iot_device_handle_t* dev_handle = NULL; if (argc < 1 || !JS_IsObject(argv[0])) { amp_warn(MOD_STR, "parameter must be (pointer and function)"); goto out; } /* get report info */ JSValue jd_handle = JS_GetPropertyStr(ctx, argv[0], "device_handle"); JSValue jpk = JS_GetPropertyStr(ctx, argv[0], "product_key"); JSValue jdn = JS_GetPropertyStr(ctx, argv[0], "device_name"); JSValue jmn = JS_GetPropertyStr(ctx, argv[0], "module_name"); JSValue jver = JS_GetPropertyStr(ctx, argv[0], "version"); unsigned int tmp_ptr_addr = 0; tmp_ptr_addr = JS_GetOpaque(jd_handle, js_aiot_device_class_id); if (!tmp_ptr_addr) { amp_error(MOD_STR, "no iot_device_handle"); goto out; } dev_handle = (iot_device_handle_t *)tmp_ptr_addr; amp_error(MOD_STR, "%s: handle 0x%x", __func__, (unsigned int)dev_handle); amp_error(MOD_STR, "%s: mqtthandle 0x%x", __func__, (unsigned int)dev_handle->mqtt_handle); const char* productkey = JS_ToCString(ctx, jpk); const char* devicename = JS_ToCString(ctx, jdn); const char* modulename = JS_ToCString(ctx, jmn); const char* version = JS_ToCString(ctx, jver); res = ota_transport_inform(dev_handle->mqtt_handle, productkey, devicename, modulename, version); if (res < 0) { amp_error(MOD_STR, "amp jsota report ver failed!"); } JS_FreeCString(ctx, productkey); JS_FreeCString(ctx, devicename); JS_FreeCString(ctx, modulename); JS_FreeCString(ctx, version); JS_FreeValue(ctx, jd_handle); JS_FreeValue(ctx, jpk); JS_FreeValue(ctx, jdn); JS_FreeValue(ctx, jmn); JS_FreeValue(ctx, jver); out: return JS_NewInt32(ctx, res); } static void ota_trigger_notify(void *pdata) { ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata; if (!ota_package_info) { amp_error(MOD_STR, "ota_package_info null!"); return; } JSContext *ctx = js_get_context(); if (!ctx) { amp_error(MOD_STR, "JSContext null!"); return; } JSValue ret = JS_NewObject(ctx); JS_SetPropertyStr(ctx, ret, "length", JS_NewUint32(ctx, (unsigned int)ota_package_info->length)); JS_SetPropertyStr(ctx, ret, "module_name", JS_NewString(ctx, ota_package_info->module_name)); JS_SetPropertyStr(ctx, ret, "version", JS_NewString(ctx, ota_package_info->version)); JS_SetPropertyStr(ctx, ret, "url", JS_NewString(ctx, ota_package_info->url)); JS_SetPropertyStr(ctx, ret, "hash", JS_NewString(ctx, ota_package_info->hash)); if (ota_package_info->hash_type == 0) { JS_SetPropertyStr(ctx, ret, "hash_type", JS_NewString(ctx, "null")); } else if (ota_package_info->hash_type == 1) { JS_SetPropertyStr(ctx, ret, "hash_type", JS_NewString(ctx, "sha256")); } else if (ota_package_info->hash_type == 2) { JS_SetPropertyStr(ctx, ret, "hash_type", JS_NewString(ctx, "md5")); } else { JS_SetPropertyStr(ctx, ret, "hash_type", JS_NewString(ctx, "sha512")); } JSValue v = JS_Call(ctx, ota_package_info->js_cb_ref, JS_UNDEFINED, 1, &ret); if (JS_IsException(v)) { amp_error(MOD_STR, "ota_trigger_notify callback error!"); } JS_FreeValue(ctx, ret); JS_FreeValue(ctx, v); JS_FreeValue(ctx, ota_package_info->js_cb_ref); aos_free(ota_package_info); } /* system image upgrade */ static int32_t customer_upgrade_cb(void *pctx, char *ver, char *module_name, void *args) { int32_t ret = OTA_TRANSPORT_PAR_FAIL; ota_package_info_t *ota_package_info = (ota_package_info_t *) args; ota_boot_param_t ota_param = {0}; aos_task_t customer_ota_task; if ((pctx == NULL) || (ver == NULL) || (module_name == NULL) || (args == NULL)) { amp_error(MOD_STR, "amp:ota triggered param err!"); return ret; } if (strncmp(module_name, "system", strlen(module_name)) == 0) { ret = 0; const char *current_ver = aos_app_version_get(); if (strncmp(ver, current_ver, strlen(ver)) <= 0) { ret = OTA_TRANSPORT_VER_FAIL; amp_error(MOD_STR, "amp ota version too old!"); } else { amp_debug(MOD_STR, "ota version:%s is coming, begin to upgrade\n", ver); /* clear jsengine timer, distory js app*/ if (aos_task_new_ext(&customer_ota_task, "amp_customer_ota", internal_sys_upgrade_start, (void *)pctx, 1024 * 8, AOS_DEFAULT_APP_PRI) != 0) { amp_debug(MOD_STR, "internal ota task create failed!"); ret = OTA_TRANSPORT_PAR_FAIL; } amp_debug(MOD_STR, "app management center start"); } amp_task_schedule_call(ota_release_notify, ota_package_info); } else { /*读取ota 触发时云端下发的文件信息*/ ret = ota_read_parameter(&ota_param); if (ret < 0) { amp_error(MOD_STR, "get store ota param info failed\n"); amp_task_schedule_call(ota_release_notify, ota_package_info); } else { ret = 0; ota_package_info->length = ota_param.len; ota_package_info->hash_type = ota_param.hash_type; strncpy(ota_package_info->url, ota_param.url, sizeof(ota_package_info->url)); strncpy(ota_package_info->version, ver, strlen(ver)); strncpy(ota_package_info->module_name, module_name, strlen(module_name)); strncpy(ota_package_info->hash, ota_param.hash, sizeof(ota_package_info->hash)); amp_task_schedule_call(ota_trigger_notify, ota_package_info); } } return ret; } static JSValue native_ota_init(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; int productkey_len = IOTX_PRODUCT_KEY_LEN; int productsecret_len = IOTX_PRODUCT_SECRET_LEN; int devicename_len = IOTX_DEVICE_NAME_LEN; int devicesecret_len = IOTX_DEVICE_SECRET_LEN; iot_device_handle_t *iot_device_handle = NULL; ota_package_info_t *ota_package_info = NULL; if (argc < 2 || !JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be (object and function)"); goto out; } ota_service_param_reset(&customer_ota_ctx); /* get device info */ aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, customer_ota_ctx.pk, &productkey_len); aos_kv_get(AMP_CUSTOMER_PRODUCTSECRET, customer_ota_ctx.ps, &productsecret_len); aos_kv_get(AMP_CUSTOMER_DEVICENAME, customer_ota_ctx.dn, &devicename_len); aos_kv_get(AMP_CUSTOMER_DEVICESECRET, customer_ota_ctx.ds, &devicesecret_len); memset(customer_module_info, 0x00, sizeof(customer_module_info)); iot_device_handle = JS_GetOpaque(argv[0], js_aiot_device_class_id); if (!iot_device_handle) { amp_error(MOD_STR, "no iot_device_handle"); goto out; } amp_error(MOD_STR, "%s: handle 0x%x", __func__, (unsigned int)iot_device_handle); amp_error(MOD_STR, "%s: mqtthandle 0x%x", __func__, (unsigned int)iot_device_handle->mqtt_handle); customer_ota_ctx.mqtt_client = (void *)iot_device_handle->mqtt_handle; ota_package_info = aos_malloc(sizeof(ota_package_info_t)); if (!ota_package_info) { amp_error(MOD_STR, "alloc device notify param fail"); goto out; } memset(ota_package_info, 0, sizeof(ota_package_info_t)); ota_package_info->js_cb_ref = JS_DupValue(ctx, argv[1]); ota_register_module_store(&customer_ota_ctx, customer_module_info, 3); ota_register_trigger_msg_cb(&customer_ota_ctx, (void *)customer_upgrade_cb, ota_package_info); ota_set_module_information(&customer_ota_ctx, "system", OS_APP_PATH, OTA_UPGRADE_ALL); /* init ota service */ res = ota_service_init(&customer_ota_ctx); if (res < 0) { amp_error(MOD_STR, "customer ota init failed!"); } else { amp_warn(MOD_STR, "customer ota init success!"); } const char *current_ver = aos_app_version_get(); res = ota_report_module_version(&customer_ota_ctx, "system", current_ver); if (res < 0) { amp_error(MOD_STR, "amp ota report ver failed!"); } out: if (res < 0) { // todo:ota_package_info->js_cb_ref 是否需要free? if (ota_package_info != NULL) { aos_free(ota_package_info); } return JS_EXCEPTION; } return JS_NewInt32(ctx, res); } static JSClassDef js_appota_class = { "APPOTA", }; static const JSCFunctionListEntry js_appota_funcs[] = { JS_CFUNC_DEF("otaInit", 1, native_ota_init ), JS_CFUNC_DEF("otaDownload", 1, native_ota_download ), JS_CFUNC_DEF("otaVerify", 1, native_ota_verify ), JS_CFUNC_DEF("otaReport", 1, native_ota_report ), JS_CFUNC_DEF("otaUpgrade", 1, native_ota_upgrade ), }; static int js_appota_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_appota_class_id); JS_NewClass(JS_GetRuntime(ctx), js_appota_class_id, &js_appota_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_appota_funcs, countof(js_appota_funcs)); JS_SetClassProto(ctx, js_appota_class_id, proto); return JS_SetModuleExportList(ctx, m, js_appota_funcs, countof(js_appota_funcs)); } JSModuleDef *js_init_module_appota(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_appota_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_appota_funcs, countof(js_appota_funcs)); return m; } void module_app_ota_register(void) { amp_debug(MOD_STR, "module_ota_register"); JSContext *ctx = js_get_context(); amp_debug(MOD_STR, "module appota register"); js_init_module_appota(ctx, "APPOTA"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/advanced/ota/module_appota.c
C
apache-2.0
20,988
/*! * @file quickjs_addon_common.h * * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef _AMP_QUICKJS_ADDON_COMMON_H_ #define _AMP_QUICKJS_ADDON_COMMON_H_ #include "stdint.h" #include "stdbool.h" #include "quickjs.h" #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif extern JSContext *js_get_context(void); #ifdef JSE_ADVANCED_ADDON_AIOT_DEVICE extern JSClassID js_aiot_device_class_id; #endif #define QUICKJS_GLOBAL_FUNC(name, func) \ do { \ JSValue global_func; \ global_func = JS_GetGlobalObject(ctx); \ JS_SetPropertyStr(ctx, global_func, name, \ JS_NewCFunction(ctx, func, name, 1)); \ JS_FreeValue(ctx, global_func); \ } while (0); static inline char *QUICKJS_GET_PROPERTY_STR(JSContext *ctx, JSValueConst argv, char *name) { JSValue js_value = JS_GetPropertyStr(ctx, argv, name); char *str = NULL; if(!JS_IsString(js_value)){ amp_error("QUCIJS", "request %s is invalid", name); JS_FreeValue(ctx, js_value); return NULL; } str = (char *)JS_ToCString(ctx, js_value); JS_FreeValue(ctx, js_value); return str; } static inline int QUICKJS_GET_PROPERTY_INT32(JSContext *ctx, JSValueConst argv, char *name) { JSValue js_value = JS_GetPropertyStr(ctx, argv, name); int32_t val = 0; if(!JS_IsNumber(js_value)){ amp_error("QUCIJS", "request %s is invalid", name); JS_FreeValue(ctx, js_value); return 0; } JS_ToInt32(ctx, &val, js_value); JS_FreeValue(ctx, js_value); return val; } static inline bool QUICKJS_GET_PROPERTY_BOOL(JSContext *ctx, JSValueConst argv, char *name) { JSValue js_value = JS_GetPropertyStr(ctx, argv, name); bool val = false; if(!JS_IsBool(js_value)){ amp_error("QUCIJS", "request %s is invalid", name); JS_FreeValue(ctx, js_value); return 0; } val = JS_ToBool(ctx, js_value); JS_FreeValue(ctx, js_value); return val; } #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/common/quickjs_addon_common.h
C
apache-2.0
2,079
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ /* #define LOG_NDEBUG 0 */ #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_adc.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "aos_system.h" #define MOD_STR "ADC" static JSClassID js_adc_class_id; static JSValue native_adc_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t adc_handle; adc_handle.handle = NULL; adc_dev_t *adc_device = NULL; const char *id = JS_ToCString(ctx, argv[0]); if (id == NULL) { amp_error(MOD_STR, "get adc id fail!"); goto out; } ret = board_attach_item(MODULE_ADC, id, &adc_handle); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!, id %s", id); goto out; } amp_debug(MOD_STR, "adc handle:%u\n", adc_handle.handle); adc_device = board_get_node_by_handle(MODULE_ADC, &adc_handle); if (NULL == adc_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_adc_init(adc_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_adc_init fail!"); goto out; } out: if (id != NULL) { JS_FreeCString(ctx, id); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_ADC, &adc_handle); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_adc_class_id); JS_SetOpaque(obj, (void *)adc_handle.handle); return obj; } return JS_NewInt32(ctx, ret); } static JSValue native_adc_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t adc_handle; adc_dev_t *adc_device = NULL; adc_handle.handle = JS_GetOpaque2(ctx, this_val, js_adc_class_id); if (!adc_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } adc_device = board_get_node_by_handle(MODULE_ADC, &adc_handle); if (NULL == adc_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_adc_finalize(adc_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_adc_finalize fail!"); goto out; } board_disattach_item(MODULE_ADC, &adc_handle); out: return JS_NewInt32(ctx, ret); } static JSValue native_adc_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint32_t adc_value = 0; item_handle_t adc_handle; adc_dev_t *adc_device = NULL; adc_handle.handle = JS_GetOpaque2(ctx, this_val, js_adc_class_id); if (!adc_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } adc_device = board_get_node_by_handle(MODULE_ADC, &adc_handle); if (NULL == adc_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } (void)aos_hal_adc_raw_value_get(adc_device, &adc_value, 0); out: return JS_NewInt32(ctx, adc_value); } static JSClassDef js_adc_class = { "ADC", }; static const JSCFunctionListEntry js_adc_funcs[] = { JS_CFUNC_DEF("open", 1, native_adc_open), JS_CFUNC_DEF("read", 0, native_adc_read), JS_CFUNC_DEF("close", 0, native_adc_close), }; static int js_adc_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_adc_class_id); JS_NewClass(JS_GetRuntime(ctx), js_adc_class_id, &js_adc_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_adc_funcs, countof(js_adc_funcs)); JS_SetClassProto(ctx, js_adc_class_id, proto); return JS_SetModuleExportList(ctx, m, js_adc_funcs, countof(js_adc_funcs)); } JSModuleDef *js_init_module_adc(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_adc_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_adc_funcs, countof(js_adc_funcs)); return m; } void module_adc_register(void) { amp_debug(MOD_STR, "module_adc_register"); JSContext *ctx = js_get_context(); aos_printf("module adc register\n"); js_init_module_adc(ctx, "ADC"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/adc/module_adc.c
C
apache-2.0
4,412
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_dac.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "aos_system.h" #define MOD_STR "DAC" static JSClassID js_dac_class_id; static JSValue native_dac_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t dac_handle; dac_handle.handle = NULL; dac_dev_t *dac_device = NULL; const char *id = JS_ToCString(ctx, argv[0]); if (id == NULL) { amp_error(MOD_STR, "get dac id fail!"); goto out; } ret = board_attach_item(MODULE_DAC, id, &dac_handle); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!, id %s", id); goto out; } amp_debug(MOD_STR, "dac handle:%u\n", dac_handle.handle); dac_device = board_get_node_by_handle(MODULE_DAC, &dac_handle); if (NULL == dac_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } ret = aos_hal_dac_init(dac_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_dac_init fail!\n"); goto out; } ret = aos_hal_dac_start(dac_device, dac_device->port); if (0 != ret) { amp_error(MOD_STR, "hal_dac_start fail!\n"); } out: if (id != NULL) { JS_FreeCString(ctx, id); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_DAC, &dac_handle); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_dac_class_id); JS_SetOpaque(obj, (void *)dac_handle.handle); return obj; } return JS_NewInt32(ctx, ret); } static JSValue native_dac_setVol(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; int8_t result = -1; uint32_t voltage = 0; item_handle_t dac_handle; dac_dev_t *dac_device = NULL; dac_handle.handle = JS_GetOpaque2(ctx, this_val, js_dac_class_id); if (!dac_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } dac_device = board_get_node_by_handle(MODULE_DAC, &dac_handle); if (NULL == dac_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } JS_ToInt32(ctx, &voltage, argv[0]); ret = aos_hal_dac_set_value(dac_device, dac_device->port, voltage); if (-1 == ret) { amp_error(MOD_STR, "dac set val fail!"); goto out; } result = 0; out: return JS_NewInt32(ctx, result); } static JSValue native_dac_getVol(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint32_t voltage = 0; item_handle_t dac_handle; dac_dev_t *dac_device = NULL; dac_handle.handle = JS_GetOpaque2(ctx, this_val, js_dac_class_id); if (!dac_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } dac_device = board_get_node_by_handle(MODULE_DAC, &dac_handle); if (NULL == dac_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } voltage = (uint32_t)aos_hal_dac_get_value(dac_device, dac_device->port); out: JS_NewInt32(ctx, voltage); } static JSValue native_dac_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t dac_handle; dac_dev_t *dac_device = NULL; dac_handle.handle = JS_GetOpaque2(ctx, this_val, js_dac_class_id); if (!dac_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } dac_device = board_get_node_by_handle(MODULE_DAC, &dac_handle); if (NULL == dac_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } aos_hal_dac_stop(dac_device, dac_device->port); ret = aos_hal_dac_finalize(dac_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_dac_finalize fail!"); goto out; } board_disattach_item(MODULE_DAC, &dac_handle); out: return JS_NewInt32(ctx, ret); } static JSClassDef js_dac_class = { "DAC", }; static const JSCFunctionListEntry js_dac_funcs[] = { JS_CFUNC_DEF("open", 1, native_dac_open), JS_CFUNC_DEF("getVol", 0, native_dac_getVol), JS_CFUNC_DEF("setVol", 1, native_dac_setVol), JS_CFUNC_DEF("close", 0, native_dac_close), }; static int js_dac_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_dac_class_id); JS_NewClass(JS_GetRuntime(ctx), js_dac_class_id, &js_dac_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_dac_funcs, countof(js_dac_funcs)); JS_SetClassProto(ctx, js_dac_class_id, proto); return JS_SetModuleExportList(ctx, m, js_dac_funcs, countof(js_dac_funcs)); } JSModuleDef *js_init_module_dac(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_dac_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_dac_funcs, countof(js_dac_funcs)); return m; } void module_dac_register(void) { amp_debug(MOD_STR, "module_dac_register"); JSContext *ctx = js_get_context(); aos_printf("module dac register\n"); js_init_module_dac(ctx, "DAC"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/dac/module_dac.c
C
apache-2.0
5,577
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_gpio.h" #include "aos_system.h" #include "amp_task.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "GPIO" #define GPIO_IRQ_RISING_EDGE "rising" #define GPIO_IRQ_FALLING_EDGE "falling" #define GPIO_IRQ_BOTH_EDGE "both" static uint16_t gpio_init_flag = 0; static JSClassID js_gpio_class_id; static JSValue native_gpio_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t gpio_handle; gpio_handle.handle = NULL; gpio_dev_t *gpio_device = NULL; const char *id = JS_ToCString(ctx, argv[0]); if (id == NULL) { amp_error(MOD_STR, "get gpio id fail!"); goto out; } ret = board_attach_item(MODULE_GPIO, id, &gpio_handle); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!, id %s", id); goto out; } amp_debug(MOD_STR, "gpio handle:%p\n", gpio_handle.handle); gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } if (gpio_init_flag & (1 << gpio_device->port)) { amp_debug(MOD_STR, "gpio port [%d] is already inited", gpio_device->port); goto out; } ret = aos_hal_gpio_init(gpio_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_gpio_init fail!"); goto out; } gpio_init_flag |= (1 << gpio_device->port); out: if (id != NULL) { JS_FreeCString(ctx, id); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_GPIO, &gpio_handle); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_gpio_class_id); JS_SetOpaque(obj, (void *)gpio_handle.handle); return obj; } return JS_NewInt32(ctx, ret); } static JSValue native_gpio_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; item_handle_t gpio_handle; gpio_dev_t *gpio_device = NULL; gpio_params_t *priv = NULL; gpio_handle.handle = JS_GetOpaque2(ctx, this_val, js_gpio_class_id); if (!gpio_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } priv = (gpio_params_t *)gpio_device->priv; if(priv->reserved != NULL) { aos_printf("func %p free memory %p \n", __func__, priv->reserved); aos_free(priv->reserved); priv->reserved = NULL; } ret = aos_hal_gpio_finalize(gpio_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_gpio_finalize fail!"); goto out; } board_disattach_item(MODULE_GPIO, &gpio_handle); out: return JS_NewInt32(ctx, ret); } static JSValue native_gpio_toggle(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; item_handle_t gpio_handle; gpio_dev_t *gpio_device = NULL; gpio_handle.handle = JS_GetOpaque2(ctx, this_val, js_gpio_class_id); if (!gpio_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_gpio_output_toggle(gpio_device); out: return JS_NewInt32(ctx, ret); } static JSValue native_gpio_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; int8_t result = -1; int8_t level = 0; item_handle_t gpio_handle; gpio_dev_t *gpio_device = NULL; gpio_handle.handle = JS_GetOpaque2(ctx, this_val, js_gpio_class_id); if (!gpio_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } JS_ToInt32(ctx, &level, argv[0]); if (level) { ret = aos_hal_gpio_output_high(gpio_device); } else { ret = aos_hal_gpio_output_low(gpio_device); } if (-1 == ret) { amp_error(MOD_STR, "gpio output set fail!"); goto out; } result = 0; out: return JS_NewInt32(ctx, result); } static JSValue native_gpio_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { item_handle_t gpio_handle; uint32_t level = 0; gpio_dev_t *gpio_device = NULL; gpio_handle.handle = JS_GetOpaque2(ctx, this_val, js_gpio_class_id); if (!gpio_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } aos_hal_gpio_input_get(gpio_device, &level); out: return JS_NewInt32(ctx, level); } typedef struct { JSValue js_cb_ref; gpio_dev_t *dev; }gpio_irq_notify_param_t; static void gpio_irq_notify(void *arg) { gpio_irq_notify_param_t *param = (gpio_irq_notify_param_t *)arg; JSContext *ctx = js_get_context(); uint32_t value = 0; aos_hal_gpio_input_get(param->dev, &value); JSValue v = JS_NewInt32(ctx, value); JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &v); JS_FreeValue(ctx, v); JS_FreeValue(ctx, val); aos_free(param); } /* avoid stdout in irq function */ static void gpio_irq(int polarity, void *arg) { static uint64_t irq_lasttime = 0; uint64_t irq_nowtime = aos_now_ms(); gpio_irq_notify_param_t *notify = aos_malloc(sizeof(gpio_irq_notify_param_t)); if ((NULL == notify) || (NULL == arg)) { /* amp_error(MOD_STR, "param error!\n"); */ return; } memcpy(notify, (gpio_irq_notify_param_t *)arg, sizeof(gpio_irq_notify_param_t)); if(irq_nowtime - irq_lasttime < 200) { // demounce in 200ms return; } irq_lasttime = irq_nowtime; if (amp_task_schedule_call(gpio_irq_notify, notify) < 0) { /* amp_warn(MOD_STR, "amp_task_schedule_call failed\n"); */ } } static JSValue native_gpio_on(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; int8_t result = -1; int8_t irq_edge = 0; item_handle_t gpio_handle; gpio_handle.handle = NULL; gpio_dev_t *gpio_device = NULL; gpio_params_t *priv = NULL; const char *edge; gpio_irq_notify_param_t *notify = NULL; notify = aos_malloc(sizeof(gpio_irq_notify_param_t)); aos_printf("func %p alloc memory %p \n", __func__, notify); if (!notify) goto out; gpio_handle.handle = JS_GetOpaque2(ctx, this_val, js_gpio_class_id); if (!gpio_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); aos_free(notify); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); aos_free(notify); goto out; } priv = (gpio_params_t *)gpio_device->priv; priv->reserved = (void *)notify; // 停止中断时,释放该内存 irq_edge = priv->irq_mode; JSValue irq_cb = argv[0]; if (!JS_IsFunction(ctx, irq_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } notify->js_cb_ref = JS_DupValue(ctx, irq_cb); notify->dev = gpio_device; // amp_debug(MOD_STR, "%p, irq_edge:%04x port:%d", gpio_device, irq_edge, gpio_device->port); ret = aos_hal_gpio_enable_irq(gpio_device, irq_edge, gpio_irq, notify); if (ret < 0) { amp_error(MOD_STR, "aos_hal_gpio_enable_irq fail!"); goto out; } result = 0; out: return JS_NewInt32(ctx, result); } static JSClassDef js_gpio_class = { "GPIO", }; static const JSCFunctionListEntry js_gpio_funcs[] = { JS_CFUNC_DEF("open", 1, native_gpio_open ), JS_CFUNC_DEF("read", 0, native_gpio_read ), JS_CFUNC_DEF("write", 1, native_gpio_write ), JS_CFUNC_DEF("toggle", 0, native_gpio_toggle), JS_CFUNC_DEF("on", 0, native_gpio_on), JS_CFUNC_DEF("close", 0, native_gpio_close ), }; static int js_gpio_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_gpio_class_id); JS_NewClass(JS_GetRuntime(ctx), js_gpio_class_id, &js_gpio_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_gpio_funcs, countof(js_gpio_funcs)); JS_SetClassProto(ctx, js_gpio_class_id, proto); return JS_SetModuleExportList(ctx, m, js_gpio_funcs, countof(js_gpio_funcs)); } JSModuleDef *js_init_module_gpio(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_gpio_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_gpio_funcs, countof(js_gpio_funcs)); return m; } void module_gpio_register(void) { amp_debug(MOD_STR, "module_gpio_register"); JSContext *ctx = js_get_context(); aos_printf("module gpio register\n"); js_init_module_gpio(ctx, "GPIO"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/gpio/module_gpio.c
C
apache-2.0
9,868
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_i2c.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "aos_system.h" #define MOD_STR "I2C" static JSClassID js_i2c_class_id; #define I2C_TIMEOUT (0xFFFFFF) static JSValue native_i2c_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t i2c_handle; i2c_handle.handle = NULL; i2c_dev_t *i2c_device = NULL; const char *id = JS_ToCString(ctx, argv[0]); if (id == NULL) { amp_error(MOD_STR, "get i2c id fail!"); goto out; } ret = board_attach_item(MODULE_I2C, id, &i2c_handle); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!, id %s", id); goto out; } amp_debug(MOD_STR, "i2c handle:%u", i2c_handle.handle); i2c_device = board_get_node_by_handle(MODULE_I2C, &i2c_handle); if (NULL == i2c_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_i2c_init(i2c_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_i2c_init fail!"); goto out; } out: if (id != NULL) { JS_FreeCString(ctx, id); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_I2C, &i2c_handle); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_i2c_class_id); JS_SetOpaque(obj, (void *)i2c_handle.handle); return obj; } return JS_NewInt32(ctx, ret); } static JSValue native_i2c_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t i2c_handle; i2c_dev_t *i2c_device = NULL; i2c_handle.handle = JS_GetOpaque2(ctx, this_val, js_i2c_class_id); if (!i2c_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } i2c_device = board_get_node_by_handle(MODULE_I2C, &i2c_handle); if (NULL == i2c_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_i2c_finalize(i2c_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_i2c_finalize fail!"); goto out; } board_disattach_item(MODULE_I2C, &i2c_handle); out: return JS_NewInt32(ctx, ret); } static JSValue native_i2c_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; uint8_t *data = NULL; uint32_t len = 0; item_handle_t i2c_handle; i2c_dev_t *i2c_device = NULL; i2c_handle.handle = JS_GetOpaque2(ctx, this_val, js_i2c_class_id); if (!i2c_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } i2c_device = board_get_node_by_handle(MODULE_I2C, &i2c_handle); if (NULL == i2c_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } data = JS_GetArrayBuffer(ctx, &len, argv[0]); if(!data) { amp_error(MOD_STR, "parameter buffer is invalid, size: %d", len); goto out; } if (NULL == data) { amp_error(MOD_STR, "JS_GetArrayBuffer fail!"); goto out; } ret = aos_hal_i2c_master_send(i2c_device, i2c_device->config.dev_addr, data, len, I2C_TIMEOUT); if (-1 == ret) { amp_error(MOD_STR, "aos_hal_i2c_master_send fail!"); goto out; } out: return JS_NewInt32(ctx, ret); } static JSValue native_i2c_write_reg(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; uint8_t *data = NULL; uint32_t len = 0; item_handle_t i2c_handle; i2c_dev_t *i2c_device = NULL; uint32_t mem_addr; i2c_handle.handle = JS_GetOpaque2(ctx, this_val, js_i2c_class_id); if (!i2c_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } i2c_device = board_get_node_by_handle(MODULE_I2C, &i2c_handle); if (NULL == i2c_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } JS_ToInt32(ctx, &mem_addr, argv[0]); data = JS_GetArrayBuffer(ctx, &len, argv[1]); if (NULL == data) { amp_error(MOD_STR, "JS_GetArrayBuffer fail!"); goto out; } ret = aos_hal_i2c_mem_write(i2c_device, i2c_device->config.dev_addr, (uint16_t)mem_addr, 1, data, len, I2C_TIMEOUT); if (-1 == ret) { amp_error(MOD_STR, "aos_hal_i2c_master_send fail!"); goto out; } out: return JS_NewInt32(ctx, ret); } static JSValue native_i2c_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; uint8_t *data = NULL; uint32_t len = 0; item_handle_t i2c_handle; i2c_dev_t *i2c_device = NULL; JSValue response = JS_UNDEFINED; i2c_handle.handle = JS_GetOpaque2(ctx, this_val, js_i2c_class_id); if (!i2c_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } i2c_device = board_get_node_by_handle(MODULE_I2C, &i2c_handle); if (NULL == i2c_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } JS_ToInt32(ctx, &len, argv[0]); data = (uint8_t *)aos_malloc(sizeof(uint8_t) * len); if (NULL == data) { amp_error(MOD_STR, "allocate memory failed"); goto out; } ret = aos_hal_i2c_master_recv(i2c_device, i2c_device->config.dev_addr, data, len, I2C_TIMEOUT); if (-1 == ret) { amp_error(MOD_STR, "aos_hal_i2c_master_recv fail!"); aos_free(data); goto out; } response = JS_NewArrayBufferCopy(ctx, data, len); aos_free(data); out: return response; } static JSValue native_i2c_read_reg(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; uint8_t *data = NULL; uint32_t len = 0; item_handle_t i2c_handle; i2c_dev_t *i2c_device = NULL; uint32_t mem_addr; JSValue response = JS_UNDEFINED; i2c_handle.handle = JS_GetOpaque2(ctx, this_val, js_i2c_class_id); if (!i2c_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } i2c_device = board_get_node_by_handle(MODULE_I2C, &i2c_handle); if (NULL == i2c_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } JS_ToInt32(ctx, &mem_addr, argv[0]); JS_ToInt32(ctx, &len, argv[1]); data = (uint8_t *)aos_malloc(sizeof(uint8_t) * len); if (NULL == data) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } ret = aos_hal_i2c_mem_read(i2c_device, i2c_device->config.dev_addr, (uint16_t)mem_addr, 1, data, len, I2C_TIMEOUT); if (-1 == ret) { amp_error(MOD_STR, "aos_hal_i2c_mem_read fail!"); aos_free(data); goto out; } response = JS_NewArrayBufferCopy(ctx, data, len); aos_free(data); out: return response; } static JSClassDef js_i2c_class = { "I2C", }; static const JSCFunctionListEntry js_i2c_funcs[] = { JS_CFUNC_DEF("open", 1, native_i2c_open), JS_CFUNC_DEF("read", 1, native_i2c_read), JS_CFUNC_DEF("write", 1, native_i2c_write), JS_CFUNC_DEF("readReg", 2, native_i2c_read_reg), JS_CFUNC_DEF("writeReg", 2, native_i2c_write_reg), JS_CFUNC_DEF("close", 0, native_i2c_close), }; static int js_i2c_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_i2c_class_id); JS_NewClass(JS_GetRuntime(ctx), js_i2c_class_id, &js_i2c_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_i2c_funcs, countof(js_i2c_funcs)); JS_SetClassProto(ctx, js_i2c_class_id, proto); return JS_SetModuleExportList(ctx, m, js_i2c_funcs, countof(js_i2c_funcs)); } JSModuleDef *js_init_module_i2c(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_i2c_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_i2c_funcs, countof(js_i2c_funcs)); return m; } void module_i2c_register(void) { amp_debug(MOD_STR, "module_i2c_register"); JSContext *ctx = js_get_context(); aos_printf("module i2c register\n"); js_init_module_i2c(ctx, "I2C"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/i2c/module_i2c.c
C
apache-2.0
8,793
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_gpio.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "IR" static JSClassID js_ir_class_id; typedef struct ir_module { item_handle_t sda_handle; item_handle_t scl_handle; item_handle_t busy_handle; } ir_module_t; static void ir_learn_mode(uint32_t scl_pin, uint32_t sda_pin) { gpio_i2c_reset(scl_pin, sda_pin); gpio_i2c_delay_10us(4); gpio_i2c_set_low(scl_pin); gpio_i2c_delay_10us(8); gpio_i2c_set_high(scl_pin); jse_osal_delay(20); gpio_i2c_start(scl_pin, sda_pin); gpio_i2c_delay_10us(4); gpio_i2c_write_byte(scl_pin, sda_pin, 0x30); gpio_i2c_delay_10us(4); gpio_i2c_write_byte(scl_pin, sda_pin, 0x20); gpio_i2c_delay_10us(4); gpio_i2c_write_byte(scl_pin, sda_pin, 0x50); gpio_i2c_delay_10us(8); gpio_i2c_stop(scl_pin, sda_pin); gpio_i2c_delay_10us(4); gpio_i2c_reset(scl_pin, sda_pin); gpio_i2c_delay_10us(4); } static int8_t ir_learn_read(uint32_t scl_pin, uint32_t sda_pin, uint8_t *buff) { uint8_t value = 0; uint8_t i = 0; uint8_t checksum = 0; gpio_i2c_reset(scl_pin, sda_pin); gpio_i2c_delay_10us(4); gpio_i2c_set_low(scl_pin); gpio_i2c_delay_10us(8); gpio_i2c_set_high(scl_pin); jse_osal_delay(20); gpio_i2c_start(scl_pin, sda_pin); gpio_i2c_delay_10us(4); gpio_i2c_write_byte(scl_pin, sda_pin, 0x30); gpio_i2c_delay_10us(4); gpio_i2c_write_byte(scl_pin, sda_pin, 0x62); gpio_i2c_delay_10us(4); gpio_i2c_start(scl_pin, sda_pin); gpio_i2c_delay_10us(4); gpio_i2c_write_byte(scl_pin, sda_pin, 0x31); gpio_i2c_delay_10us(4); value = gpio_i2c_read_byte(scl_pin, sda_pin); gpio_i2c_delay_10us(4); if (0x00 != value) { gpio_i2c_stop(scl_pin, sda_pin); gpio_i2c_delay_10us(4); gpio_i2c_reset(scl_pin, sda_pin); gpio_i2c_delay_10us(4); return -1; } buff[i] = value; checksum = 0xc3; for (i = 1; i < 230; i++) { value = gpio_i2c_read_byte(scl_pin, sda_pin); gpio_i2c_delay_10us(4); buff[i] = value; checksum += value; } value = gpio_i2c_read_byte(scl_pin, sda_pin); gpio_i2c_delay_10us(4); gpio_i2c_stop(scl_pin, sda_pin); gpio_i2c_delay_10us(4); gpio_i2c_reset(scl_pin, sda_pin); gpio_i2c_delay_10us(4); return 0; } static int32_t ir_learn_start(uint32_t scl_pin, uint32_t sda_pin, uint32_t busy_bin, uint8_t buff[232]) { uint8_t sumValue = 0; int32_t count = 0; int8_t ret = -1; uint8_t i = 0; uint8_t tmp[512] = {0x00}; gpio_i2c_init(scl_pin, sda_pin); gpio_i2c_set_in(busy_bin); ir_learn_mode(scl_pin, sda_pin); jse_osal_delay(50); while (!gpio_i2c_read_pin(busy_bin)) gpio_i2c_delay_10us(10); ret = ir_learn_read(scl_pin, sda_pin, tmp); if (0 != ret) { return -1; } buff[0] = 0x30; sumValue += buff[0]; buff[1] = 0x03; sumValue += buff[1]; for (i = 1; i < 231; i++) { buff[i + 1] = tmp[i]; sumValue += tmp[i]; } buff[231] = sumValue; return 232; } static uint32_t ir_counts(gpio_dev_t *gpio, uint8_t level) { int8_t ret = 0; uint32_t value = 0; uint32_t counts = 0; do { ret = aos_hal_gpio_input_get(gpio, &value); counts += 1; jse_osal_delay10us(); } while ((0 == ret) && (value == level)); return counts; } static uint32_t ir_nec(gpio_dev_t *gpio) { uint32_t counts = 0; uint32_t value = 0; uint8_t i = 0; uint8_t j = 0; /*9ms*/ counts = ir_counts(gpio, 0); if (counts < 850 || counts > 950) { return 0; } /*4.5ms*/ counts = ir_counts(gpio, 1); if (counts < 400 || counts > 500) { return 0; } for (i = 0; i < 4; ++i) { for (j = 0; j < 8; ++j) { value <<= 1; counts = ir_counts(gpio, 0); if (counts < 30 || counts > 100) { return 0; } counts = ir_counts(gpio, 1); if (counts > 130 && counts < 200) { value |= 1; } else if (counts < 30 || counts > 100) { return 0; } } } return value; } static JSValue native_ir_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; ir_module_t *ir_handle; gpio_dev_t *gpio_device = NULL; const char *id_sda = NULL; const char *id_scl = NULL; const char *id_busy = NULL; if((argc < 3) || (!JS_IsString(argv[0])) || (!JS_IsString(argv[1])) || (!JS_IsString(argv[2]))) { amp_warn(MOD_STR, "parameter is invalid, argc = %d\n", argc); goto out; } /* init sda port*/ id_sda = JS_ToCString(ctx, argv[0]); ir_handle = (uint8_t *)aos_malloc(sizeof(ir_handle)); if (NULL == ir_handle) { amp_error(MOD_STR, "allocate memory failed"); goto out; } ret = board_attach_item(MODULE_GPIO, id_sda, &(ir_handle->sda_handle)); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!\n"); goto out; } amp_debug(MOD_STR, "ir handle:%u\n", ir_handle->sda_handle.handle); gpio_device = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->sda_handle)); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } ret = aos_hal_gpio_init(gpio_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_gpio_init fail!\n"); goto out; } gpio_device->priv = NULL; /* init scl port*/ id_scl = JS_ToCString(ctx, argv[1]); ret = board_attach_item(MODULE_GPIO, id_scl, &(ir_handle->scl_handle)); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!\n"); goto out; } amp_debug(MOD_STR, "ir handle:%u\n", ir_handle->scl_handle); gpio_device = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->scl_handle)); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } ret = aos_hal_gpio_init(gpio_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_gpio_init fail!\n"); goto out; } gpio_device->priv = NULL; /* init busy port*/ id_busy = JS_ToCString(ctx, argv[2]); ret = board_attach_item(MODULE_GPIO, id_busy, &(ir_handle->busy_handle)); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!\n"); goto out; } amp_debug(MOD_STR, "ir handle:%u\n", ir_handle->busy_handle); gpio_device = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->busy_handle)); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } ret = aos_hal_gpio_init(gpio_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_gpio_init fail!\n"); goto out; } gpio_device->priv = NULL; out: if (id_sda != NULL) { JS_FreeCString(ctx, id_sda); } if (id_scl != NULL) { JS_FreeCString(ctx, id_scl); } if (id_busy != NULL) { JS_FreeCString(ctx, id_busy); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_GPIO, &(ir_handle->sda_handle)); board_disattach_item(MODULE_GPIO, &(ir_handle->scl_handle)); board_disattach_item(MODULE_GPIO, &(ir_handle->busy_handle)); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_ir_class_id); JS_SetOpaque(obj, (void *)ir_handle); return obj; } return JS_NewInt32(ctx, 0); } static JSValue native_ir_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t result = -1; item_handle_t gpio_handle; gpio_dev_t *gpio_device = NULL; ir_module_t *ir_handle; ir_handle = JS_GetOpaque2(ctx, this_val, js_ir_class_id); if (!ir_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } /* close sda port*/ gpio_device = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->sda_handle)); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } aos_hal_gpio_disable_irq(gpio_device); gpio_device->priv = NULL; board_disattach_item(MODULE_GPIO, &(ir_handle->sda_handle)); /* close scl port*/ gpio_device = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->scl_handle)); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } aos_hal_gpio_disable_irq(gpio_device); gpio_device->priv = NULL; board_disattach_item(MODULE_GPIO, &(ir_handle->scl_handle)); /* busy scl port*/ gpio_device = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->busy_handle)); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } aos_hal_gpio_disable_irq(gpio_device); gpio_device->priv = NULL; board_disattach_item(MODULE_GPIO, &(ir_handle->busy_handle)); result = 0; out: return JS_NewInt32(ctx, result); } struct gpio_irq_notify_param { int js_cb_ref; int value; }; static void gpio_irq_notify(void *arg) { struct gpio_irq_notify_param *p = (struct gpio_irq_notify_param *)arg; amp_debug(MOD_STR, "value: 0x%x\n", p->value); JSContext *ctx = js_get_context(); JSValue val = JS_Call(ctx, p->js_cb_ref, JS_UNDEFINED, 1, &(p->value)); JS_FreeValue(ctx, val); } /* avoid stdout in irq function */ static void ir_handle(void *arg) { uint32_t value = 0; gpio_dev_t *gpio = (gpio_dev_t *)arg; if (NULL == gpio) { /* amp_error(MOD_STR, "param error!\n"); */ return; } value = ir_nec(gpio); if (0x00 == value) { return; } int js_cb_ref = (int)gpio->priv; if (js_cb_ref <= 0) { /* amp_error(MOD_STR, "js cb ref error, ref: %d\n", js_cb_ref); */ return; } struct gpio_irq_notify_param *p = (struct gpio_irq_notify_param *)aos_malloc(sizeof(*p)); p->js_cb_ref = js_cb_ref; p->value = value & 0xFFFF; if (amp_task_schedule_call(gpio_irq_notify, p) < 0) { /* amp_warn(MOD_STR, "amp_task_schedule_call failed\n"); */ aos_free(p); } } static JSValue native_ir_on(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; gpio_dev_t *gpio_device = NULL; int js_cb_ref; ir_module_t *ir_handle; if((argc < 1) || (JS_IsNull(argv[0]) || JS_IsUndefined(argv[0]))) { amp_warn(MOD_STR, "parameter is invalid, argc = %d\n", argc); goto out; } ir_handle = JS_GetOpaque2(ctx, this_val, js_ir_class_id); if (!ir_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->sda_handle)); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } ret = aos_hal_gpio_enable_irq(gpio_device, IRQ_TRIGGER_FALLING_EDGE, ir_handle, gpio_device); if (ret < 0) { amp_error(MOD_STR, "aos_hal_gpio_enable_irq fail!\n"); goto out; } js_cb_ref = JS_DupValue(ctx, argv[0]); gpio_device->priv = (void *)js_cb_ref; out: return JS_NewInt32(ctx, ret); } static void ir_delay(uint32_t counts) { uint32_t i = 0; for (i = 0; i < counts; i++) jse_osal_delay10us(); } static void ir_byte(gpio_dev_t *sda, gpio_dev_t *scl, unsigned char bData) { int8_t i = 0; uint32_t val = 0; aos_hal_gpio_output_low(scl); ir_delay(4); for (i = 7; i >= 0; i--) { ir_delay(4); if ((bData >> i) & 0x01) { aos_hal_gpio_output_high(sda); } else { aos_hal_gpio_output_low(sda); } ir_delay(4); aos_hal_gpio_output_high(scl); ir_delay(4); aos_hal_gpio_output_low(scl); } aos_hal_gpio_output_high(sda); ir_delay(16); aos_hal_gpio_output_high(scl); ir_delay(16); aos_hal_gpio_input_get(sda, &val); ir_delay(16); aos_hal_gpio_output_low(scl); ir_delay(16); } static void ir_buff(gpio_dev_t *sda, gpio_dev_t *scl, uint8_t *data, uint32_t count) { uint32_t i = 0; aos_hal_gpio_output_high(sda); aos_hal_gpio_output_high(scl); ir_delay(4); aos_hal_gpio_output_low(scl); ir_delay(8); aos_hal_gpio_output_high(scl); jse_osal_delay(20); aos_hal_gpio_output_high(scl); aos_hal_gpio_output_high(sda); ir_delay(8); aos_hal_gpio_output_low(sda); ir_delay(40); aos_hal_gpio_output_low(scl); ir_delay(8); ir_delay(4); for (i = 0; i < count; i++) { ir_byte(sda, scl, data[i]); ir_delay(4); } ir_delay(4); aos_hal_gpio_output_low(scl); aos_hal_gpio_output_low(sda); ir_delay(4); aos_hal_gpio_output_high(scl); ir_delay(4); aos_hal_gpio_output_high(sda); ir_delay(8); aos_hal_gpio_output_low(sda); aos_hal_gpio_output_low(scl); ir_delay(4); aos_hal_gpio_output_high(scl); ir_delay(4); aos_hal_gpio_output_high(sda); ir_delay(8); } static JSValue native_ir_send(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint8_t *data = NULL; uint32_t len = 0; uint32_t i = 0; gpio_dev_t *gpio_scl = NULL; gpio_dev_t *gpio_sda = NULL; int arr_idx; int err = -1; ir_module_t *ir_handle; if(argc < 1) { amp_warn(MOD_STR, "parameter must be array"); goto out; } ir_handle = JS_GetOpaque2(ctx, this_val, js_ir_class_id); if (!ir_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_sda = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->sda_handle)); if (NULL == gpio_sda) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } gpio_scl = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->sda_handle)); if (NULL == gpio_scl) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } data = JS_GetArrayBuffer(ctx, &len, argv[0]); if(!data) { amp_warn(MOD_STR, "parameter buffer is invalid, size: %d", len); goto out; } ir_buff(gpio_sda, gpio_scl, data, len); ir_delay(10); ir_buff(gpio_sda, gpio_scl, data, len); ir_delay(10); /* ir_buff(gpio_sda,gpio_scl,data,len); */ err = 0; out: aos_free(data); return JS_NewInt32(ctx, err); } static JSValue native_ir_learn(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint32_t i = 0; int32_t ret = -1; uint8_t buff[232] = {0x00}; gpio_dev_t *gpio_scl = NULL; gpio_dev_t *gpio_sda = NULL; gpio_dev_t *gpio_busy = NULL; ir_module_t *ir_handle; JSValue response = JS_UNDEFINED; ir_handle = JS_GetOpaque2(ctx, this_val, js_ir_class_id); if (!ir_handle) { amp_warn(MOD_STR, "parameter must be handle"); goto failed; } gpio_sda = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->sda_handle)); if (NULL == gpio_sda) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto failed; } gpio_scl = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->scl_handle)); if (NULL == gpio_scl) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto failed; } gpio_busy = board_get_node_by_handle(MODULE_GPIO, &(ir_handle->busy_handle)); if (NULL == gpio_busy) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto failed; } ret = ir_learn_start(gpio_scl->port, gpio_sda->port, gpio_busy->port, buff); if (ret <= 0) { amp_error(MOD_STR, "ir_learn_start fail!\n"); goto failed; } response = JS_NewArrayBufferCopy(ctx, buff, 232); if (JS_IsException(response)) goto failed; failed: return response; } static JSClassDef js_ir_class = { "IR", }; static const JSCFunctionListEntry js_ir_funcs[] = { JS_CFUNC_DEF("open", 1, native_ir_open), JS_CFUNC_DEF("on", 1, native_ir_on), JS_CFUNC_DEF("send", 2, native_ir_send), JS_CFUNC_DEF("learn", 2, native_ir_learn), JS_CFUNC_DEF("close", 0, native_ir_close), }; static int js_ir_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_ir_class_id); JS_NewClass(JS_GetRuntime(ctx), js_ir_class_id, &js_ir_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_ir_funcs, countof(js_ir_funcs)); JS_SetClassProto(ctx, js_ir_class_id, proto); return JS_SetModuleExportList(ctx, m, js_ir_funcs, countof(js_ir_funcs)); } JSModuleDef *js_init_module_ir(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_ir_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_ir_funcs, countof(js_ir_funcs)); return m; } void module_ir_register(void) { amp_debug(MOD_STR, "module_ir_register"); JSContext *ctx = js_get_context(); aos_printf("module ir register\n"); js_init_module_ir(ctx, "IR"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/ir/module_ir.c
C
apache-2.0
17,784
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_lcd.h" #include "aos_system.h" #include "amp_task.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "LCD" #define GPIO_IRQ_RISING_EDGE "rising" #define GPIO_IRQ_FALLING_EDGE "falling" #define GPIO_IRQ_BOTH_EDGE "both" static uint16_t lcd_init_flag = 0; static JSClassID js_lcd_class_id; static JSValue native_lcd_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; ret = aos_hal_lcd_init(); if (0 != ret) { amp_error(MOD_STR, "aos_hal_lcd_init fail!"); } return JS_NewInt32(ctx, ret); } static JSValue native_lcd_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; ret = aos_hal_lcd_uninit(); if (0 != ret) { amp_error(MOD_STR, "aos_hal_lcd_uninit fail!"); } return JS_NewInt32(ctx, ret); } static JSValue native_lcd_show(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; uint8_t *buf; uint32_t buf_len = 0; int32_t x, y, w, h; bool rotate; if (argc < 6) { amp_warn(MOD_STR, "parameter must be x, y, w, h, color"); goto out; } JS_ToInt32(ctx, &x, argv[0]); JS_ToInt32(ctx, &y, argv[1]); JS_ToInt32(ctx, &w, argv[2]); JS_ToInt32(ctx, &h, argv[3]); buf = JS_GetArrayBuffer(ctx, &buf_len, argv[4]); if (!buf) { amp_warn(MOD_STR, "parameter buffer is invalid, size: %d", buf_len); goto out; } rotate = JS_ToBool(ctx, argv[5]); ret = aos_hal_lcd_show(x, y, w, h, buf, rotate); if (0 != ret) { amp_error(MOD_STR, "aos_hal_lcd_fill fail!"); } out: return JS_NewInt32(ctx, ret); } static JSValue native_lcd_fill(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int32_t x, y, w, h; uint32_t color; if (argc < 5) { amp_warn(MOD_STR, "parameter must be x, y, w, h, color"); goto out; } JS_ToInt32(ctx, &x, argv[0]); JS_ToInt32(ctx, &y, argv[1]); JS_ToInt32(ctx, &w, argv[2]); JS_ToInt32(ctx, &h, argv[3]); JS_ToUint32(ctx, &color, argv[4]); ret = aos_hal_lcd_fill(x, y, w, h, color); if (0 != ret) { amp_error(MOD_STR, "aos_hal_lcd_fill fail!"); } out: return JS_NewInt32(ctx, ret); } static JSClassDef js_lcd_class = { "LCD", }; static const JSCFunctionListEntry js_lcd_funcs[] = { JS_CFUNC_DEF("open", 0, native_lcd_open), JS_CFUNC_DEF("show", 0, native_lcd_show), JS_CFUNC_DEF("fill", 0, native_lcd_fill), JS_CFUNC_DEF("close", 0, native_lcd_close), }; static int js_lcd_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_lcd_class_id); JS_NewClass(JS_GetRuntime(ctx), js_lcd_class_id, &js_lcd_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_lcd_funcs, countof(js_lcd_funcs)); JS_SetClassProto(ctx, js_lcd_class_id, proto); return JS_SetModuleExportList(ctx, m, js_lcd_funcs, countof(js_lcd_funcs)); } JSModuleDef *js_init_module_lcd(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_lcd_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_lcd_funcs, countof(js_lcd_funcs)); return m; } void module_lcd_register(void) { amp_debug(MOD_STR, "module_lcd_register"); JSContext *ctx = js_get_context(); aos_printf("module lcd register\n"); js_init_module_lcd(ctx, "lcd"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/lcd/module_lcd.c
C
apache-2.0
3,928
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_gpio.h" #include "aos_system.h" #include "amp_task.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "ONEWIRE" /* 使用方法:yaml文件中添加JSE_HW_ADDON_ONEWIRE、JSE_HW_ADDON_GPIO、RHINO_CONFIG_HW_COUNT 参考如下: def_config: # 组件的可配置项 CONFIG_ENGINE_DUKTAPE: 1 #CONFIG_ENGINE_QUICKJS: 1 CONFIG_VERSION: '1.0' JSE_HW_ADDON_ONEWIRE: 1 JSE_HW_ADDON_GPIO: 1 RHINO_CONFIG_HW_COUNT: 1 */ static int A,B,C,D,E,F,G,H,I,J; static uint16_t gpio_init_flag = 0; static JSClassID js_onewire_class_id; #define RHINO_CONFIG_HW_COUNT 1 #if (RHINO_CONFIG_HW_COUNT > 0) #define CONFIG_FAST_SYSTICK_HZ (hal_cmu_get_crystal_freq() / 4) #define FAST_TICKS_TO_US(tick) ((uint32_t)(tick) * 10 / (CONFIG_FAST_SYSTICK_HZ / 1000 / 100)) #define RHINO_CPU_INTRPT_DISABLE() do{ cpsr = cpu_intrpt_save(); }while(0) #define RHINO_CPU_INTRPT_ENABLE() do{ cpu_intrpt_restore(cpsr); }while(0) static JSClassID js_onewire_class_id; void oneWireUdelay(unsigned long x) { unsigned long now,t; int cpsr; RHINO_CPU_INTRPT_DISABLE(); t = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); now = t; while ((now - t) < x) { now = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); } RHINO_CPU_INTRPT_ENABLE(); } #endif static void oneWireGpioSet(gpio_dev_t *gpio_device, unsigned char leve) { int ret = 0; if(leve == 1) { ret = aos_hal_gpio_output_high(gpio_device); } else if(leve == 0) { ret = aos_hal_gpio_output_low(gpio_device); } //amp_warn(MOD_STR, "GPIO:%d, output config:0x%x, leve: %d, ret:%d", gpio_device->port, gpio_device->config, leve, ret); } static uint32_t oneWireGpioGet(gpio_dev_t *gpio_device) { int ret = 0; unsigned int value = 0; ret = aos_hal_gpio_input_get(gpio_device, &value); //amp_warn(MOD_STR, "GPIO:%d, input config:0x%x, ret: %d, value:%d\r\n", gpio_device->port, gpio_device->config, ret, value); return (ret == 0)? value: ret; } //----------------------------------------------------------------------------- // Generate a 1-Wire reset, return 1 if no presence detect was found, // return 0 otherwise. // (NOTE: Does not handle alarm presence from DS2404/DS1994) // int oneWireTouchReset(gpio_dev_t *gpio_device) { int result1; int result2; oneWireUdelay(G); oneWireGpioSet(gpio_device, 0x00); // Drives DQ low oneWireUdelay(H); oneWireGpioSet(gpio_device, 0x01); // Releases the bus oneWireUdelay(I); result1 = oneWireGpioGet(gpio_device) ^ 0x01; // Sample for presence pulse from slave oneWireUdelay(J); // Complete the reset sequence recovery result2 = oneWireGpioGet(gpio_device) ^ 0x01; // Sample for presence pulse from slave amp_warn(MOD_STR, "oneWireTouchReset[%d] result1 = %d, result2 = %d", __LINE__, result1, result2); return !((result1 == 1) && (result2 == 0)); // Return sample presence pulse result } //----------------------------------------------------------------------------- // Send a 1-Wire write bit. Provide 10us recovery time. // void OneWireWriteBit(gpio_dev_t *gpio_device, int bit) { //amp_warn(MOD_STR, "OneWireWriteBit[%d] bit = %d", __LINE__, bit); if (bit) { // Write '1' bit oneWireGpioSet(gpio_device, 0x00); // Drives DQ low oneWireUdelay(1); oneWireGpioSet(gpio_device, 0x01); // Releases the bus oneWireUdelay(30); // Complete the time slot and 10us recovery } else { // Write '0' bit oneWireGpioSet(gpio_device, 0x00); // Drives DQ low oneWireUdelay(30); oneWireGpioSet(gpio_device, 0x01); // Releases the bus oneWireUdelay(1); } } //----------------------------------------------------------------------------- // Read a bit from the 1-Wire bus and return it. Provide 10us recovery time. // int OneWireReadBit(gpio_dev_t *gpio_device) { int result; oneWireGpioSet(gpio_device, 0x00); // Drives DQ low oneWireUdelay(1); oneWireGpioSet(gpio_device, 0x01); // Releases the bus oneWireUdelay(2); result = oneWireGpioGet(gpio_device) & 0x01; // Sample the bit value from the slave oneWireUdelay(40); // Complete the time slot and 10us recovery //amp_warn(MOD_STR, "OneWireReadBit[%d] result = %d", __LINE__, result); return result; } //----------------------------------------------------------------------------- // Write 1-Wire data byte // void OneWireWriteByte(gpio_dev_t *gpio_device, int data) { int loop; // Loop to write each bit in the byte, LS-bit first for (loop = 0; loop < 8; loop++) { OneWireWriteBit(gpio_device, data & 0x01); // shift the data byte for the next bit data >>= 1; } } //----------------------------------------------------------------------------- // Read 1-Wire data byte and return it // int OneWireReadByte(gpio_dev_t *gpio_device) { int loop, result=0; for (loop = 0; loop < 8; loop++) { // shift the result to get it ready for the next bit result >>= 1; // if result is one, then set MS bit if (OneWireReadBit(gpio_device)) { result |= 0x80; } } //amp_warn(MOD_STR, "OneWireReadByte[%d] data = 0x%x", __LINE__, result); return result; } void delayus(unsigned int z) { while(z--); } //----------------------------------------------------------------------------- // Set the 1-Wire timing to 'standard' (standard=1) or 'overdrive' (standard=0). // void oneWireSetSpeed(int standard) { unsigned long now,t; // Adjust tick values depending on speed if (standard) { // Standard Speed // A = 6 * 4; // B = 64 * 4; // C = 60 * 4; // D = 10 * 4; // E = 9 * 4; // F = 55 * 4; // G = 0; // H = 480 * 4; // I = 70 * 4; // J = 410 * 4; A = 6; B = 64; C = 60; D = 10; E = 9; F = 55; G = 0; H = 480; I = 70; J = 410; } else { // Overdrive Speed A = 1.5 * 4; B = 7.5 * 4; C = 7.5 * 4; D = 2.5 * 4; E = 0.75 * 4; F = 7 * 4; G = 2.5 * 4; H = 70 * 4; I = 8.5 * 4; J = 40 * 4; } now = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); oneWireUdelay(A); t = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); amp_warn(MOD_STR, "[%d]hal_cmu_get_crystal_freq[%d] delta = %d", A, hal_cmu_get_crystal_freq(), (t-now)); now = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); oneWireUdelay(B); t = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); amp_warn(MOD_STR, "[%d]hal_cmu_get_crystal_freq[%d] delta = %d", B, hal_cmu_get_crystal_freq(), (t-now)); now = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); oneWireUdelay(C); t = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); amp_warn(MOD_STR, "[%d]hal_cmu_get_crystal_freq[%d] delta = %d", C, hal_cmu_get_crystal_freq(), (t-now)); now = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); oneWireUdelay(D); t = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); amp_warn(MOD_STR, "[%d]hal_cmu_get_crystal_freq[%d] delta = %d", D, hal_cmu_get_crystal_freq(), (t-now)); } //----------------------------------------------------------------------------- // Set the 1-Wire timing to 'standard' (standard=1) or 'overdrive' (standard=0). // static JSValue native_onewire_gpio_setspeed(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int standard = 0; int8_t result = -1; if((argc < 1) || (0 != JS_ToInt32(ctx, &standard, argv[0]))) { amp_warn(MOD_STR, "parameter is invalid\n"); goto out; } printf("[%s][%d]standard = %d\n\r", __FUNCTION__, __LINE__, standard); //oneWireSetSpeed(standard); result = 0; out: return JS_NewInt32(ctx, result); } static JSValue native_onewire_gpio_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t gpio_handle; gpio_handle.handle = NULL; gpio_dev_t *gpio_device = NULL; const char *id; if((argc < 1) || (!JS_IsString(argv[0]))) { amp_warn(MOD_STR, "parameter is invalid, argc = %d\n", argc); goto out; } id = JS_ToCString(ctx, argv[0]); ret = board_attach_item(MODULE_GPIO, id, &gpio_handle); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!, id %s", id); goto out; } amp_debug(MOD_STR, "gpio handle:%p\n", gpio_handle.handle); gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_gpio_init(gpio_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_gpio_init fail!"); goto out; } // gpio_device->priv = NULL; gpio_init_flag |= (1 << gpio_device->port); amp_error(MOD_STR, "aos_hal_gpio_init ret = %d!", ret); out: if (id != NULL) { JS_FreeCString(ctx, id); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_GPIO, &gpio_handle); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_onewire_class_id); JS_SetOpaque(obj, (void *)gpio_handle.handle); return obj; } return JS_NewInt32(ctx, 0); } static JSValue native_onewire_gpio_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; item_handle_t gpio_handle; gpio_dev_t *gpio_device = NULL; gpio_handle.handle = JS_GetOpaque2(ctx, this_val, js_onewire_class_id); if (!gpio_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_gpio_finalize(gpio_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_gpio_finalize fail!"); goto out; } board_disattach_item(MODULE_GPIO, &gpio_handle); out: return JS_NewInt32(ctx, ret); } static JSValue native_onewire_gpio_reset(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { item_handle_t gpio_handle; int result = -1; gpio_dev_t *gpio_device = NULL; gpio_handle.handle = JS_GetOpaque2(ctx, this_val, js_onewire_class_id); if (!gpio_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } //result = oneWireTouchReset(gpio_device); result = 0; out: return JS_NewInt32(ctx, result); } static JSValue native_onewire_gpio_readbyte(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { item_handle_t gpio_handle; int result; gpio_dev_t *gpio_device = NULL; gpio_handle.handle = JS_GetOpaque2(ctx, this_val, js_onewire_class_id); if (!gpio_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } //result = OneWireReadByte(gpio_device); result = 0; out: return JS_NewInt32(ctx, result); } static JSValue native_onewire_gpio_writebyte(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { item_handle_t gpio_handle; int result = 0; gpio_dev_t *gpio_device = NULL; int32_t level = 0; if((argc < 1) || (0 != JS_ToInt32(ctx, &level, argv[0]))) { amp_warn(MOD_STR, "parameter is invalid\n"); goto out; } gpio_handle.handle = JS_GetOpaque2(ctx, this_val, js_onewire_class_id); if (!gpio_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } gpio_device = board_get_node_by_handle(MODULE_GPIO, &gpio_handle); if (NULL == gpio_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } //OneWireWriteByte(gpio_device, level); result = 1; out: return JS_NewInt32(ctx, result); } static JSClassDef js_onewire_class = { "ONEWIRE", }; static const JSCFunctionListEntry js_onewire_funcs[] = { JS_CFUNC_DEF("open", 1, native_onewire_gpio_open ), JS_CFUNC_DEF("setspeed", 1, native_onewire_gpio_setspeed ), JS_CFUNC_DEF("reset", 0, native_onewire_gpio_reset ), JS_CFUNC_DEF("readByte", 0, native_onewire_gpio_readbyte), JS_CFUNC_DEF("writeByte", 1, native_onewire_gpio_writebyte), JS_CFUNC_DEF("close", 0, native_onewire_gpio_close), }; static int js_onewire_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_onewire_class_id); JS_NewClass(JS_GetRuntime(ctx), js_onewire_class_id, &js_onewire_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_onewire_funcs, countof(js_onewire_funcs)); JS_SetClassProto(ctx, js_onewire_class_id, proto); return JS_SetModuleExportList(ctx, m, js_onewire_funcs, countof(js_onewire_funcs)); } JSModuleDef *js_init_module_onewire(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_onewire_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_onewire_funcs, countof(js_onewire_funcs)); return m; } void module_onewire_register(void) { amp_debug(MOD_STR, "module_onewire_register"); JSContext *ctx = js_get_context(); aos_printf("module onewire register\n"); js_init_module_onewire(ctx, "ONEWIRE"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/onewire/module_onewire.c
C
apache-2.0
14,728
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ /* #define LOG_NDEBUG 0 */ #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_pwm.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "aos_system.h" #define MOD_STR "PWM" static JSClassID js_pwm_class_id; typedef struct sim_info { int freq; int duty; } pwm_module_t; static JSValue native_pwm_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t pwm_handle; pwm_handle.handle = NULL; pwm_dev_t *pwm_device = NULL; const char *id; if((argc < 1) || (!JS_IsString(argv[0]))) { amp_warn(MOD_STR, "parameter is invalid, argc = %d\n", argc); goto out; } id = JS_ToCString(ctx, argv[0]); printf("open %s\n\r", id); ret = board_attach_item(MODULE_PWM, id, &pwm_handle); if (0 != ret) { amp_error(MOD_STR, "board_attach_item %d fail!\n", ret); goto out; } amp_debug(MOD_STR, "pwm handle:%u\n", pwm_handle.handle); pwm_device = board_get_node_by_handle(MODULE_PWM, &pwm_handle); if (NULL == pwm_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } amp_debug(MOD_STR, "%s:%d:%d:%f\n", id, pwm_device->port, pwm_device->config.freq, pwm_device->config.duty_cycle); ret = aos_hal_pwm_init(pwm_device); out: if (id != NULL) { JS_FreeCString(ctx, id); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_PWM, &pwm_handle); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_pwm_class_id); JS_SetOpaque(obj, (void *)pwm_handle.handle); return obj; } return JS_NewInt32(ctx, 0); } static JSValue native_pwm_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t pwm_handle; pwm_dev_t *pwm_device = NULL; pwm_handle.handle = JS_GetOpaque2(ctx, this_val, js_pwm_class_id); if (!pwm_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } pwm_device = board_get_node_by_handle(MODULE_PWM, &pwm_handle); if (NULL == pwm_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } ret = aos_hal_pwm_stop(pwm_device); ret |= aos_hal_pwm_finalize(pwm_device); ret = board_disattach_item(MODULE_PWM, &pwm_handle); printf("pwm close %d\n\r", ret); amp_debug(MOD_STR, "aos_hal_pwm_finalize ret: %d\n", ret); out: return JS_NewInt32(ctx, ret); } static JSValue native_pwm_getConfig(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; item_handle_t pwm_handle; pwm_module_t pwm_config; pwm_dev_t *pwm_device = NULL; pwm_handle.handle = JS_GetOpaque2(ctx, this_val, js_pwm_class_id); if (!pwm_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } pwm_device = board_get_node_by_handle(MODULE_PWM, &pwm_handle); if (NULL == pwm_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } pwm_config.duty = (int)(pwm_device->config.duty_cycle * 100); pwm_config.freq = (int)(pwm_device->config.freq); JSValue t = JS_NewObject(ctx); JS_SetPropertyStr(ctx, t, "freq", JS_NewInt32(ctx, pwm_config.freq)); JS_SetPropertyStr(ctx, t, "duty", JS_NewInt32(ctx, pwm_config.duty)); return t; out: return JS_NewInt32(ctx, 0); } static JSValue native_pwm_setConfig(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; int32_t freq; int duty = 0; item_handle_t pwm_handle; pwm_dev_t *pwm_device = NULL; JSValue val; if(argc < 1) { amp_warn(MOD_STR, "parameter is invalid, argc = %d\n", argc); goto out; } pwm_handle.handle = JS_GetOpaque2(ctx, this_val, js_pwm_class_id); if (!pwm_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } pwm_device = board_get_node_by_handle(MODULE_PWM, &pwm_handle); if (NULL == pwm_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!\n"); goto out; } /* 获取频率参数*/ val = JS_GetPropertyStr(ctx, argv[0], "freq"); if (JS_IsException(val) || JS_IsUndefined(val)) { amp_warn(MOD_STR, "parameter %s failed!\n", "freq"); goto out; } ret = JS_ToInt32(ctx, &freq, val); if(ret != 0) { amp_warn(MOD_STR, "parameter %s to int32 failed!\n", "freq"); goto out; } /* 获取占空比参数*/ val = JS_GetPropertyStr(ctx, argv[0], "duty"); if (JS_IsException(val) || JS_IsUndefined(val)) { amp_warn(MOD_STR, "parameter %s failed!\n", "duty"); goto out; } ret = JS_ToInt32(ctx, &duty, val); if(ret != 0) { amp_warn(MOD_STR, "parameter %s to int32 failed!\n", "duty"); goto out; } pwm_device->config.duty_cycle = (float)duty / 100.0; pwm_device->config.freq = freq; ret = aos_hal_pwm_stop(pwm_device); if (ret != 0) { amp_warn(MOD_STR, "amp hal pwm stop failed\n"); goto out; } pwm_config_t para; para.duty_cycle = pwm_device->config.duty_cycle; para.freq = pwm_device->config.freq; ret = aos_hal_pwm_para_chg(pwm_device, para); if (ret != 0) { amp_warn(MOD_STR, "amp hal pwm init failed\n"); goto out; } ret = aos_hal_pwm_start(pwm_device); out: return JS_NewInt32(ctx, ret); } static JSClassDef js_pwm_class = { "PWM", }; static const JSCFunctionListEntry js_pwm_funcs[] = { JS_CFUNC_DEF("open", 1, native_pwm_open), JS_CFUNC_DEF("close", 0, native_pwm_close), JS_CFUNC_DEF("getConfig", 0, native_pwm_getConfig), JS_CFUNC_DEF("setConfig", 1, native_pwm_setConfig), }; static int js_pwm_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_pwm_class_id); JS_NewClass(JS_GetRuntime(ctx), js_pwm_class_id, &js_pwm_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_pwm_funcs, countof(js_pwm_funcs)); JS_SetClassProto(ctx, js_pwm_class_id, proto); return JS_SetModuleExportList(ctx, m, js_pwm_funcs, countof(js_pwm_funcs)); } JSModuleDef *js_init_module_pwm(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_pwm_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_pwm_funcs, countof(js_pwm_funcs)); return m; } void module_pwm_register(void) { amp_debug(MOD_STR, "module_pwm_register"); JSContext *ctx = js_get_context(); aos_printf("module pwm register\n"); js_init_module_pwm(ctx, "PWM"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/pwm/module_pwm.c
C
apache-2.0
7,114
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #define LOG_NDEBUG 0 #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_rtc.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "aos_system.h" #define MOD_STR "RTC" #define RTC_YEAR "year" #define RTC_MONTH "month" #define RTC_DAY "day" #define RTC_HOUR "hour" #define RTC_MINUTE "minute" #define RTC_SECOND "second" #define RTC_TIME_FORMAT \ "{\"year\":\"%d\",\"month\":\"%d\",\"day\":\"%d\",\"hour\":\"%d\"," \ "\"minute\":\"%d\",\"second\":\"%d\"}" static rtc_dev_t rtc_dev; static JSClassID js_rtc_class_id; static JSValue native_rtc_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = aos_hal_rtc_init(&rtc_dev); amp_debug(MOD_STR, "port: %d, format: %d\n", rtc_dev.port, rtc_dev.config.format); if (0 != ret) { amp_error(MOD_STR, "aos_hal_rtc_init fail!\n"); } return JS_NewInt32(ctx, ret); } static JSValue native_rtc_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = aos_hal_rtc_finalize(&rtc_dev); if (0 != ret) { amp_error(MOD_STR, "aos_hal_rtc_finalize fail!\n"); } return JS_NewInt32(ctx, ret); } static JSValue native_rtc_get_time(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; rtc_time_t rtcTime; ret = aos_hal_rtc_get_time(&rtc_dev, &rtcTime); if (0 != ret) { amp_error(MOD_STR, "aos_hal_rtc_get_time fail!\n"); JS_SetContextOpaque(ctx, NULL); } else { JSValue t = JS_NewObject(ctx); JS_SetPropertyStr(ctx, t, "year", JS_NewInt32(ctx, ((uint32_t)rtcTime.year))); JS_SetPropertyStr(ctx, t, "month", JS_NewInt32(ctx, rtcTime.month)); JS_SetPropertyStr(ctx, t, "day", JS_NewInt32(ctx, rtcTime.date)); JS_SetPropertyStr(ctx, t, "hour", JS_NewInt32(ctx, rtcTime.hr)); JS_SetPropertyStr(ctx, t, "minute", JS_NewInt32(ctx, rtcTime.min)); JS_SetPropertyStr(ctx, t, "second", JS_NewInt32(ctx, rtcTime.sec)); return t; } return JS_NewInt32(ctx, 0); } static JSValue native_rtc_set_time(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; rtc_time_t *setTime; int data; JSValue val; if(argc < 1) { amp_warn(MOD_STR, "parameter is invalid, argc = %d\n", argc); goto out; } setTime = (rtc_time_t *)aos_malloc(sizeof(rtc_time_t)); if (!setTime) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } ret = aos_hal_rtc_get_time(&rtc_dev, setTime); if (ret < 0) { amp_error(MOD_STR, "aos_hal_rtc_get_time fail!\n"); goto out; } /* 获取年份参数*/ val = JS_GetPropertyStr(ctx, argv[0], RTC_YEAR); if (JS_IsException(val) || JS_IsUndefined(val)) { amp_warn(MOD_STR, "parameter %s failed!\n", RTC_YEAR); goto out; } ret = JS_ToInt32(ctx, &data, val); if(ret != 0) { amp_warn(MOD_STR, "parameter %s to int32 failed!\n", RTC_YEAR); goto out; } setTime->year = data; JS_FreeValue(ctx, val); /* 获取月份参数*/ val = JS_GetPropertyStr(ctx, argv[0], RTC_MONTH); if (JS_IsException(val) || JS_IsUndefined(val)) { amp_warn(MOD_STR, "parameter %s failed!\n", RTC_MONTH); goto out; } ret = JS_ToInt32(ctx, &data, val); if(ret != 0) { amp_warn(MOD_STR, "parameter %s to int32 failed!\n", RTC_MONTH); goto out; } setTime->month = data; JS_FreeValue(ctx, val); /* 获取日期参数*/ val = JS_GetPropertyStr(ctx, argv[0], RTC_DAY); if (JS_IsException(val) || JS_IsUndefined(val)) { amp_warn(MOD_STR, "parameter %s failed!\n", RTC_DAY); goto out; } ret = JS_ToInt32(ctx, &data, val); if(ret != 0) { amp_warn(MOD_STR, "parameter %s to int32 failed!\n", RTC_DAY); goto out; } setTime->date = data; JS_FreeValue(ctx, val); /* 获取小时参数*/ val = JS_GetPropertyStr(ctx, argv[0], RTC_HOUR); if (JS_IsException(val) || JS_IsUndefined(val)) { amp_warn(MOD_STR, "parameter %s failed!\n", RTC_HOUR); goto out; } ret = JS_ToInt32(ctx, &data, val); if(ret != 0) { amp_warn(MOD_STR, "parameter %s to int32 failed!\n", RTC_HOUR); goto out; } setTime->hr = data; JS_FreeValue(ctx, val); /* 获取分钟参数*/ val = JS_GetPropertyStr(ctx, argv[0], RTC_MINUTE); if (JS_IsException(val) || JS_IsUndefined(val)) { amp_warn(MOD_STR, "parameter %s failed!\n", RTC_MINUTE); goto out; } ret = JS_ToInt32(ctx, &data, val); if(ret != 0) { amp_warn(MOD_STR, "parameter %s to int32 failed!\n", RTC_MINUTE); goto out; } setTime->min = data; JS_FreeValue(ctx, val); /* 获取秒参数*/ val = JS_GetPropertyStr(ctx, argv[0], RTC_SECOND); if (JS_IsException(val) || JS_IsUndefined(val)) { amp_warn(MOD_STR, "parameter %s failed!\n", RTC_SECOND); goto out; } ret = JS_ToInt32(ctx, &data, val); if(ret != 0) { amp_warn(MOD_STR, "parameter %s to int32 failed!\n", RTC_SECOND); goto out; } setTime->sec = data; JS_FreeValue(ctx, val); amp_info(MOD_STR, "year: %d, month: %d, day: %d, hour: %d, minute: %d, second: %d\n", setTime->year, setTime->month, setTime->date, setTime->hr, setTime->min, setTime->sec); ret = aos_hal_rtc_set_time(&rtc_dev, setTime); out: return JS_NewInt32(ctx, ret); } static JSClassDef js_rtc_class = { "RTC", }; static const JSCFunctionListEntry js_rtc_funcs[] = { JS_CFUNC_DEF("open", 0, native_rtc_open ), JS_CFUNC_DEF("close", 0, native_rtc_close ), JS_CFUNC_DEF("getTime", 0, native_rtc_get_time ), JS_CFUNC_DEF("setTime", 1, native_rtc_set_time), }; static int js_rtc_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_rtc_class_id); JS_NewClass(JS_GetRuntime(ctx), js_rtc_class_id, &js_rtc_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_rtc_funcs, countof(js_rtc_funcs)); JS_SetClassProto(ctx, js_rtc_class_id, proto); return JS_SetModuleExportList(ctx, m, js_rtc_funcs, countof(js_rtc_funcs)); } JSModuleDef *js_init_module_rtc(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_rtc_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_rtc_funcs, countof(js_rtc_funcs)); return m; } void module_rtc_register(void) { amp_debug(MOD_STR, "module_rtc_register"); JSContext *ctx = js_get_context(); aos_printf("module rtc register\n"); js_init_module_rtc(ctx, "RTC"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/rtc/module_rtc.c
C
apache-2.0
7,190
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_spi.h" #include "aos_system.h" #include "amp_task.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "SPI" #define SPI_TIMEOUT (0xFFFFFF) static JSClassID js_spi_class_id; static JSValue native_spi_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t spi_handle; spi_handle.handle = NULL; spi_dev_t *spi_device = NULL; const char *id = JS_ToCString(ctx, argv[0]); if (id == NULL) { amp_error(MOD_STR, "get spi id fail!"); goto out; } ret = board_attach_item(MODULE_SPI, id, &spi_handle); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!, id %s", id); goto out; } amp_debug(MOD_STR, "spi handle:%p\n", spi_handle.handle); spi_device = board_get_node_by_handle(MODULE_SPI, &spi_handle); if (NULL == spi_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_spi_init(spi_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_spi_init fail!"); goto out; } out: if (id != NULL) { JS_FreeCString(ctx, id); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_SPI, &spi_handle); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_spi_class_id); JS_SetOpaque(obj, (void *)spi_handle.handle); return obj; } return JS_NewInt32(ctx, ret); } static JSValue native_spi_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; item_handle_t spi_handle; spi_dev_t *spi_device = NULL; spi_handle.handle = JS_GetOpaque2(ctx, this_val, js_spi_class_id); if (!spi_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } spi_device = board_get_node_by_handle(MODULE_SPI, &spi_handle); if (NULL == spi_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_spi_finalize(spi_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_spi_finalize fail!"); goto out; } board_disattach_item(MODULE_SPI, &spi_handle); out: return JS_NewInt32(ctx, ret); } static JSValue native_spi_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; char *data = NULL; uint32_t data_len = 0; item_handle_t spi_handle; spi_dev_t *spi_device = NULL; spi_handle.handle = JS_GetOpaque2(ctx, this_val, js_spi_class_id); if (!spi_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } spi_device = board_get_node_by_handle(MODULE_SPI, &spi_handle); if (NULL == spi_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } data = JS_GetArrayBuffer(ctx, &data_len, argv[0]); if (!data) { amp_warn(MOD_STR, "parameter buffer is invalid, size: %d", data_len); goto out; } if (NULL == data) { amp_warn(MOD_STR, "JS_GetArrayBuffer failed"); goto out; } ret = aos_hal_spi_send(spi_device, data, data_len, SPI_TIMEOUT); if (-1 == ret) { amp_error(MOD_STR, "native_spi_write fail!"); goto out; } out: return JS_NewInt32(ctx, ret); } static JSValue native_spi_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; const char *data = NULL; uint32_t len = 0; item_handle_t spi_handle; spi_dev_t *spi_device = NULL; JSValue response = JS_UNDEFINED; spi_handle.handle = JS_GetOpaque2(ctx, this_val, js_spi_class_id); if (!spi_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } spi_device = board_get_node_by_handle(MODULE_SPI, &spi_handle); if (NULL == spi_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } JS_ToInt32(ctx, &len, argv[0]); data = (uint8_t *)aos_malloc(sizeof(uint8_t) * len); if (NULL == data) { amp_error(MOD_STR, "allocate memory failed"); goto out; } ret = aos_hal_spi_recv(spi_device, data, len, SPI_TIMEOUT); if (-1 == ret) { amp_error(MOD_STR, "aos_hal_spi_master_recv fail!"); aos_free(data); goto out; } response = JS_NewArrayBufferCopy(ctx, data, len); aos_free(data); out: return response; } static JSValue native_spi_send_receive(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; uint8_t *send_data = NULL; uint8_t *receive_data = NULL; uint32_t send_len = 0; uint32_t receive_len = 0; item_handle_t spi_handle; spi_dev_t *spi_device = NULL; JSValue response = JS_UNDEFINED; spi_handle.handle = JS_GetOpaque2(ctx, this_val, js_spi_class_id); if (!spi_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } spi_device = board_get_node_by_handle(MODULE_SPI, &spi_handle); if (NULL == spi_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } send_data = JS_GetArrayBuffer(ctx, &send_len, argv[0]); JS_ToInt32(ctx, &receive_len, argv[1]); receive_data = (uint8_t *)aos_malloc(sizeof(uint8_t) * receive_len); if (NULL == receive_data) { amp_error(MOD_STR, "allocate memory failed"); goto out; } ret = aos_hal_spi_send_recv(spi_device, send_data, receive_data, receive_len, SPI_TIMEOUT); if (-1 == ret) { amp_error(MOD_STR, "amp_hal_spi_master_recv fail!"); aos_free(receive_data); goto out; } response = JS_NewArrayBufferCopy(ctx, receive_data, receive_len); aos_free(receive_data); out: return response; } static JSClassDef js_spi_class = { "SPI", }; static const JSCFunctionListEntry js_spi_funcs[] = { JS_CFUNC_DEF("open", 1, native_spi_open), JS_CFUNC_DEF("read", 2, native_spi_read), JS_CFUNC_DEF("write", 1, native_spi_write), JS_CFUNC_DEF("sendRecv", 2, native_spi_send_receive), JS_CFUNC_DEF("close", 0, native_spi_close)}; static int js_spi_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_spi_class_id); JS_NewClass(JS_GetRuntime(ctx), js_spi_class_id, &js_spi_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_spi_funcs, countof(js_spi_funcs)); JS_SetClassProto(ctx, js_spi_class_id, proto); return JS_SetModuleExportList(ctx, m, js_spi_funcs, countof(js_spi_funcs)); } JSModuleDef *js_init_module_spi(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_spi_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_spi_funcs, countof(js_spi_funcs)); return m; } void module_spi_register(void) { amp_debug(MOD_STR, "module_spi_register"); JSContext *ctx = js_get_context(); aos_printf("module spi register\n"); js_init_module_spi(ctx, "SPI"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/spi/module_spi.c
C
apache-2.0
7,425
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "amp_config.h" #include "amp_defines.h" #include "amp_task.h" #include "board_mgr.h" #include "amp_task.h" #include "aos_hal_timer.h" #include "aos/list.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "HW_TIMER" typedef struct { JSValue js_cb_ref; timer_dev_t *dev; }timer_irq_notify_param_t; typedef struct { timer_dev_t *dev; timer_irq_notify_param_t *notify; dlist_t node; } timer_info_t; static dlist_t g_timer_list = AOS_DLIST_HEAD_INIT(g_timer_list); static JSClassID js_timer_class_id; static void hw_timer_delete(timer_dev_t *dev) { timer_info_t *timer_info; if (!dev) return; dlist_for_each_entry(&g_timer_list, timer_info, timer_info_t, node) { if (timer_info->dev == dev) { aos_hal_timer_stop(timer_info->dev); aos_hal_timer_finalize(timer_info->dev); dlist_del(&timer_info->node); aos_free(timer_info->notify); aos_free(timer_info); break; } } } static JSValue native_timer_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; item_handle_t timer_handle; timer_handle.handle = NULL; timer_dev_t *timer_device = NULL; JSValue js_id = JS_GetPropertyStr(ctx, argv[0], "id"); const char *id = JS_ToCString(ctx, js_id); if (id == NULL) { amp_error(MOD_STR, "get timer id fail!"); goto out; } ret = board_attach_item(MODULE_TIMER, id, &timer_handle); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!"); goto out; } amp_debug(MOD_STR, "timer handle:%u", timer_handle.handle); timer_device = board_get_node_by_handle(MODULE_TIMER, &timer_handle); if (NULL == timer_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_timer_init(timer_device); if (0 != ret) { amp_error(MOD_STR, "aos_hal_timer_init fail!"); goto out; } out: if (id != NULL) { JS_FreeCString(ctx, id); JS_FreeValue(ctx, js_id); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_TIMER, &timer_handle); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_timer_class_id); JS_SetOpaque(obj, (void *)timer_handle.handle); return obj; } return JS_NewInt32(ctx, 0); } static void native_timer_timeout_handler(void *args) { timer_irq_notify_param_t *param = (timer_irq_notify_param_t *)args; JSContext *ctx = js_get_context(); JSValue v = JS_NewInt32(ctx, 0); JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &v); JS_FreeValue(ctx, v); JS_FreeValue(ctx, val); } static void native_timer_timeout_cb(void *args) { amp_task_schedule_call(native_timer_timeout_handler, args); } static JSValue native_timer_setTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; uint32_t timeout = 0; item_handle_t timer_handle; timer_dev_t *timer_device = NULL; timer_info_t *timer_info; timer_irq_notify_param_t *notify; notify = aos_malloc(sizeof(timer_irq_notify_param_t)); if (!notify) { goto out; } timer_info = aos_malloc(sizeof(timer_info_t)); if (!timer_info) { amp_error(MOD_STR, "alloc timer info fail!"); aos_free(notify); goto out; } timer_handle.handle = JS_GetOpaque2(ctx, this_val, js_timer_class_id); timer_device = board_get_node_by_handle(MODULE_TIMER, &timer_handle); if (NULL == timer_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); aos_free(notify); aos_free(timer_info); goto out; } JSValue irq_cb = argv[0]; if (!JS_IsFunction(ctx, irq_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } JS_ToInt32(ctx, &timeout, argv[1]); notify->js_cb_ref = JS_DupValue(ctx, irq_cb); notify->dev = timer_device; timer_device->config.reload_mode = TIMER_RELOAD_MANU; timer_device->config.period = timeout; timer_device->config.cb = native_timer_timeout_cb; timer_device->config.arg = notify; aos_hal_timer_stop(timer_device); ret = aos_hal_timer_start(timer_device); if (ret != 0) { amp_error(MOD_STR, "amp_hal_set_timeout fail!"); aos_free(timer_info); goto out; } timer_info->dev = timer_device; timer_info->notify = notify; dlist_add_tail(&timer_info->node, &g_timer_list); out: return JS_NewInt32(ctx, ret); } static JSValue native_timer_clearTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; uint32_t timeout = 0; item_handle_t timer_handle; timer_dev_t *timer_device = NULL; timer_handle.handle = JS_GetOpaque2(ctx, this_val, js_timer_class_id); if (!timer_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } timer_device = board_get_node_by_handle(MODULE_TIMER, &timer_handle); if (NULL == timer_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } timer_device->config.reload_mode = TIMER_RELOAD_MANU; aos_hal_timer_stop(timer_device); ret = 0; out: return JS_NewInt32(ctx, ret); } static void native_timer_interval_handler(void *arg) { timer_irq_notify_param_t *param = (timer_irq_notify_param_t *)arg; JSContext *ctx = js_get_context(); JSValue value = JS_NewInt32(ctx, 0); JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &value); JS_FreeValue(ctx, value); JS_FreeValue(ctx, val); } static void native_timer_interval_cb(void *args) { amp_task_schedule_call(native_timer_interval_handler, args); } static JSValue native_timer_setInterval(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; uint32_t timeout = 0; item_handle_t timer_handle; timer_dev_t *timer_device = NULL; timer_info_t *timer_info; timer_irq_notify_param_t *notify; notify = aos_malloc(sizeof(timer_irq_notify_param_t)); if (!notify) { goto out; } timer_info = aos_malloc(sizeof(timer_info_t)); if (!timer_info) { amp_error(MOD_STR, "alloc timer info fail!"); aos_free(notify); goto out; } timer_handle.handle = JS_GetOpaque2(ctx, this_val, js_timer_class_id); if (!timer_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); aos_free(notify); aos_free(timer_info); goto out; } timer_device = board_get_node_by_handle(MODULE_TIMER, &timer_handle); if (NULL == timer_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); aos_free(notify); aos_free(timer_info); goto out; } JSValue irq_cb = argv[0]; if (!JS_IsFunction(ctx, irq_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } JS_ToInt32(ctx, &timeout, argv[1]); notify->js_cb_ref = JS_DupValue(ctx, irq_cb); notify->dev = timer_device; timer_device->config.reload_mode = TIMER_RELOAD_AUTO; timer_device->config.period = timeout; timer_device->config.cb = native_timer_interval_cb; timer_device->config.arg = notify; ret = aos_hal_timer_start(timer_device); if (ret != 0) { amp_error(MOD_STR, "aos_hal_timer_start fail!"); aos_free(notify); aos_free(timer_info); goto out; } timer_info->dev = timer_device; timer_info->notify = notify; dlist_add_tail(&timer_info->node, &g_timer_list); out: return JS_NewInt32(ctx, ret); } static JSValue native_timer_clearInterval(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; uint32_t timeout = 0; item_handle_t timer_handle; timer_dev_t *timer_device = NULL; timer_handle.handle = JS_GetOpaque2(ctx, this_val, js_timer_class_id); if (!timer_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } timer_device = board_get_node_by_handle(MODULE_TIMER, &timer_handle); if (NULL == timer_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } timer_device->config.reload_mode = TIMER_RELOAD_AUTO; aos_hal_timer_stop(timer_device); ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_timer_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; uint32_t timeout = 0; item_handle_t timer_handle; timer_dev_t *timer_device = NULL; timer_handle.handle = JS_GetOpaque2(ctx, this_val, js_timer_class_id); if (!timer_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } timer_device = board_get_node_by_handle(MODULE_TIMER, &timer_handle); if (NULL == timer_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } hw_timer_delete(timer_device); out: return JS_NewInt32(ctx, ret); } static void native_timer_source_free(void) { dlist_t *temp; timer_info_t *timer_node; dlist_for_each_entry_safe(&g_timer_list, temp, timer_node, timer_info_t, node) { aos_hal_timer_stop(timer_node->dev); aos_hal_timer_finalize(timer_node->dev); dlist_del(&timer_node->node); aos_free(timer_node); } } static JSClassDef js_timer_class = { "TIMER", }; static const JSCFunctionListEntry js_timer_funcs[] = { JS_CFUNC_DEF("open", 0, native_timer_open), JS_CFUNC_DEF("setTimeout", 2, native_timer_setTimeout), JS_CFUNC_DEF("clearTimeout", 0, native_timer_clearTimeout), JS_CFUNC_DEF("setInterval", 2, native_timer_setInterval), JS_CFUNC_DEF("clearInterval", 0, native_timer_clearInterval), JS_CFUNC_DEF("close", 0, native_timer_close), }; static int js_timer_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_timer_class_id); JS_NewClass(JS_GetRuntime(ctx), js_timer_class_id, &js_timer_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_timer_funcs, countof(js_timer_funcs)); JS_SetClassProto(ctx, js_timer_class_id, proto); return JS_SetModuleExportList(ctx, m, js_timer_funcs, countof(js_timer_funcs)); } JSModuleDef *js_init_module_timer(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_timer_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_timer_funcs, countof(js_timer_funcs)); return m; } void module_timer_register(void) { amp_debug(MOD_STR, "module_timer_register"); JSContext *ctx = js_get_context(); amp_module_free_register(native_timer_source_free); js_init_module_timer(ctx, "timer"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/timer/module_timer.c
C
apache-2.0
11,467
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ /* #define LOG_NDEBUG 0 * generate: * ./qjsc -c -m src/uart.js -N jslib_uart -M UART -M events -o bytecode/jslib_uart.c * linux sim: * ./test/qjsc -c ./test/testapp.js -M uart -M events -o ./test/app.c * python ./test/gen_jsb.py ./test/app.c ./test/app.jsb */ #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "amp_task.h" #include "aos_hal_uart.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "MODULE_UART" #define UART_BUFF_SIZE 1024 #define MAX_UART_PORT 6 static JSClassID js_uart_class_id; typedef struct uart_module { uart_dev_t *uart; uint32_t item_handle; uint32_t recv_index; uint8_t recv_buff[UART_BUFF_SIZE]; JSValue js_cb_ref; } uart_module_t; typedef struct { uint8_t recv_buff[UART_BUFF_SIZE]; int recv_len; JSValue js_cb_ref; } uart_notify_t; extern JSContext *js_get_context(void); /* * open -- item_handle * on -- uart_module_t -- item_handle */ static uart_module_t *g_uart_modules[MAX_UART_PORT]; static uart_dev_t *g_uart_devices[MAX_UART_PORT]; static int uart_module_is_on(uint32_t item_handle) { int i; for (i = 0; i < MAX_UART_PORT; i++) { uart_module_t *m = g_uart_modules[i]; if (m && m->item_handle == item_handle) { return 1; } } return 0; } static void uart_recv_notify(void *pdata) { int i = 0; uart_notify_t *notify = (uart_notify_t *)pdata; JSContext *ctx = js_get_context(); JSValue args[2]; args[0] = JS_NewArrayBufferCopy(ctx, notify->recv_buff, notify->recv_len); args[1] = JS_NewInt32(ctx, notify->recv_len); JSValue val = JS_Call(ctx, notify->js_cb_ref, JS_UNDEFINED, 2, args); JS_FreeValue(ctx, args[0]); JS_FreeValue(ctx, args[1]); if (JS_IsException(val)) { js_std_dump_error(ctx); amp_error(MOD_STR, "uart_recv_notify, call error"); } JS_FreeValue(ctx, val); aos_free(notify); } void uart_recv_callback(int port, void *data, uint16_t len, void *arg) { uart_module_t *module = g_uart_modules[port]; uint32_t recvsize = 0; uart_dev_t *dev = (uart_dev_t *)module->uart; uart_notify_t *notify; int ret = 0; if (!module) return; notify = aos_malloc(sizeof(uart_notify_t)); if (!notify) { amp_error(MOD_STR, "alloc uart notify fail"); return; } if (data != NULL) { recvsize = len <= UART_BUFF_SIZE ? len : UART_BUFF_SIZE; memcpy(notify->recv_buff, data, recvsize); } else { aos_hal_uart_recv_II(dev, notify->recv_buff, UART_BUFF_SIZE, &recvsize, 0); if (recvsize <= 0) { aos_free(notify); return; } } notify->recv_len = recvsize; notify->js_cb_ref = module->js_cb_ref; ret = amp_task_schedule_call(uart_recv_notify, notify); if (ret != 0) { amp_error(MOD_STR, "Uart data is too large to be processed. Discard it !!!\n"); aos_free(notify); } } static int uart_add_recv(uart_dev_t *uart, uint32_t item_handle, JSValue js_cb_ref) { uart_module_t *module = aos_calloc(1, sizeof(uart_module_t)); if (!module) { amp_error(MOD_STR, "uart_start_recv fail!"); return -1; } module->js_cb_ref = js_cb_ref; module->item_handle = item_handle; module->recv_index = 0; module->uart = uart; if (aos_hal_uart_callback(uart, uart_recv_callback, module) != 0) { JSContext *ctx = js_get_context(); JS_FreeValue(ctx, module->js_cb_ref); aos_free(module); return -1; } g_uart_modules[uart->port] = module; return 0; } static void uart_del_recv(uint32_t item_handle) { int i; for (i = 0; i < MAX_UART_PORT; i++) { uart_module_t *m = g_uart_modules[i]; if (m && m->item_handle == item_handle) { JSContext *ctx = js_get_context(); JS_FreeValue(ctx, m->js_cb_ref); aos_free(m); g_uart_modules[i] = NULL; break; } } } static uint16_t uart_init_flag = 0; static JSValue native_uart_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { amp_warn(MOD_STR, "native uart open"); int8_t ret = -1; item_handle_t uart_handle; uart_handle.handle = NULL; uart_dev_t *uart_device = NULL; const char *id; if((argc < 1) || (!JS_IsString(argv[0]))) { amp_warn(MOD_STR, "parameter is invalid, argc = %d\n", argc); goto out; } id = JS_ToCString(ctx, argv[0]); ret = board_attach_item(MODULE_UART, id, &uart_handle); if (0 != ret) { amp_error(MOD_STR, "board_attach_item fail!"); goto out; } uart_device = board_get_node_by_handle(MODULE_UART, &uart_handle); if (NULL == uart_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } if (uart_init_flag & (1 << uart_device->port)) { amp_debug(MOD_STR, "uart port [%d] is already inited\n", uart_device->port); goto out; } // amp_info(MOD_STR, "uart uart_device->config.baud_rate:%d\n", uart_device->config.baud_rate); // amp_info(MOD_STR, "uart uart_device->config.parity:%d\n", uart_device->config.parity); // amp_info(MOD_STR, "uart uart_device->config.data_width:%d\n", uart_device->config.data_width); // amp_info(MOD_STR, "uart uart_device->config.stop_bits:%d\n", uart_device->config.stop_bits); // amp_info(MOD_STR, "uart uart_device->port:%d\n", uart_device->port); ret = aos_hal_uart_init(uart_device); if (0 != ret) { amp_error(MOD_STR, "native_uart_open fail!"); goto out; } uart_init_flag |= (1 << uart_device->port); g_uart_devices[uart_device->port] = uart_device; out: if (id != NULL) { JS_FreeCString(ctx, id); } if (0 != ret) { JS_SetContextOpaque(ctx, NULL); board_disattach_item(MODULE_UART, &uart_handle); } else { JSValue obj; obj = JS_NewObjectClass(ctx, js_uart_class_id); JS_SetOpaque(obj, (void *)uart_handle.handle); return obj; } return JS_NewInt32(ctx, 0); } static JSValue native_uart_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t ret = -1; item_handle_t uart_handle; uart_dev_t *uart_device = NULL; uart_handle.handle = JS_GetOpaque2(ctx, this_val, js_uart_class_id); if (!uart_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } uart_device = board_get_node_by_handle(MODULE_UART, &uart_handle); if (NULL == uart_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } ret = aos_hal_uart_finalize(uart_device); if (0 != ret) { amp_error(MOD_STR, "native_uart_close fail!"); goto out; } uart_init_flag -= (1 << uart_device->port); g_uart_devices[uart_device->port] = NULL; board_disattach_item(MODULE_UART, &uart_handle); uart_del_recv((uint32_t)(uart_handle.handle)); out: return JS_NewInt32(ctx, ret); } static JSValue native_uart_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int i; char *msg = NULL; size_t msg_len = 0; item_handle_t uart_handle; uart_dev_t *uart_device = NULL; JSValue val; const char *buf; if(argc < 1) { amp_warn(MOD_STR, "parameter must be array"); goto out; } if(JS_IsString(argv[0])) { buf = JS_ToCString(ctx, argv[0]); msg_len = strlen(buf); } else { buf = JS_GetArrayBuffer(ctx, &msg_len, argv[0]); if(!buf) { amp_warn(MOD_STR, "parameter buffer is invalid, size: %d", msg_len); goto out; } } uart_handle.handle = JS_GetOpaque2(ctx, this_val, js_uart_class_id); if (!uart_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } uart_device = board_get_node_by_handle(MODULE_UART, &uart_handle); if (NULL == uart_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } msg = (char *)aos_malloc(msg_len + 1); if (!msg) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } memcpy(msg, buf, msg_len); msg[msg_len] = 0; //amp_info(MOD_STR, "uart write:%s\n", msg); ret = aos_hal_uart_send(uart_device, msg, msg_len, osWaitForever); if (-1 == ret) { amp_error(MOD_STR, "native_uart_write fail!"); } aos_free(msg); if ((JS_IsString(argv[0])) && (buf)) { JS_FreeCString(ctx, buf); } out: return JS_NewInt32(ctx, ret); } static JSValue native_uart_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; char *data = NULL; uint32_t max_len = 1024; uint32_t recvsize = 0; item_handle_t uart_handle; uart_dev_t *uart_device = NULL; JSValue obj; uart_handle.handle = JS_GetOpaque2(ctx, this_val, js_uart_class_id); if (!uart_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } uart_device = board_get_node_by_handle(MODULE_UART, &uart_handle); if (NULL == uart_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } data = (uint8_t *)aos_malloc(sizeof(uint8_t) * max_len); if (NULL == data) { amp_error(MOD_STR, "allocate memory failed"); goto out; } ret = aos_hal_uart_recv_II(uart_device, data, 1, &recvsize, 0); if (recvsize <= 0) { //amp_error(MOD_STR, "native_uart_read error! ret = %d, recvsize= %d", ret, recvsize); goto out; } if (ret >= 0) { //amp_info(MOD_STR, "uart recvsize:%d\n", recvsize); obj = JS_NewArrayBufferCopy(ctx, data, recvsize); if(NULL != data) { aos_free((void *)data); } return obj; } out: if(NULL != data) { aos_free(data); } return JS_NewInt32(ctx, 0); } static JSValue native_uart_on(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; item_handle_t uart_handle; uart_handle.handle = NULL; uart_dev_t *uart_device = NULL; uint8_t *start = NULL; uint8_t *end = NULL; if((argc < 1) || (JS_IsNull(argv[0]) || JS_IsUndefined(argv[0])) || ((!JS_IsFunction(ctx, argv[0])))) { amp_warn(MOD_STR, "parameter is invalid, argc = %d\n", argc); goto out; } uart_handle.handle = JS_GetOpaque2(ctx, this_val, js_uart_class_id); if (!uart_handle.handle) { amp_warn(MOD_STR, "parameter must be handle"); goto out; } uart_device = board_get_node_by_handle(MODULE_UART, &uart_handle); if (NULL == uart_device) { amp_error(MOD_STR, "board_get_node_by_handle fail!"); goto out; } if (uart_module_is_on((uint32_t)(uart_handle.handle))) { amp_error(MOD_STR, "The uart module has set the listener"); goto out; } JSValue irq_cb = argv[0]; if (!JS_IsFunction(ctx, irq_cb)) { JS_ThrowTypeError(ctx, "not a function"); goto out; } JSValue js_cb_ref = JS_DupValue(ctx, irq_cb); uart_module_t *module = aos_calloc(1, sizeof(uart_module_t)); if (!module) { amp_error(MOD_STR, "uart_start_recv fail!"); goto out; } if (!JS_IsFunction(ctx, js_cb_ref)) { JS_ThrowTypeError(ctx, "not a function"); goto out; } module->js_cb_ref = js_cb_ref; module->item_handle = (uint32_t)(uart_handle.handle); module->recv_index = 0; module->uart = uart_device; if (aos_hal_uart_callback(uart_device, uart_recv_callback, module) != 0) { JSContext *ctx = js_get_context(); JS_FreeValue(ctx, module->js_cb_ref); aos_free(module); goto out; } g_uart_modules[uart_device->port] = module; ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_uart_clean() { uart_module_t *mod; uart_dev_t *dev; int i, ret; JSContext *ctx = js_get_context(); item_handle_t uart_handle; for (i = 0; i < MAX_UART_PORT; i++) { mod = g_uart_modules[i]; if (mod) { JS_FreeValue(ctx, mod->js_cb_ref); uart_handle.handle = mod->item_handle; aos_free(mod); g_uart_modules[i] = NULL; } dev = g_uart_devices[i]; if (dev) { ret = aos_hal_uart_finalize(dev); if (ret) { amp_error(MOD_STR, "finalize uart %d fail %d", i, ret); continue; } uart_init_flag -= (1 << dev->port); g_uart_devices[i] = NULL; board_disattach_item(MODULE_UART, &uart_handle); uart_del_recv((uint32_t)(uart_handle.handle)); } } return JS_NewInt32(ctx, 0); } static JSClassDef js_uart_class = { "UART", }; static const JSCFunctionListEntry js_uart_funcs[] = { JS_CFUNC_DEF("open", 1, native_uart_open), JS_CFUNC_DEF("read", 0, native_uart_read ), JS_CFUNC_DEF("write", 1, native_uart_write ), JS_CFUNC_DEF("on", 1, native_uart_on ), JS_CFUNC_DEF("close", 0, native_uart_close ), }; static int js_uart_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_uart_class_id); JS_NewClass(JS_GetRuntime(ctx), js_uart_class_id, &js_uart_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_uart_funcs, countof(js_uart_funcs)); JS_SetClassProto(ctx, js_uart_class_id, proto); return JS_SetModuleExportList(ctx, m, js_uart_funcs, countof(js_uart_funcs)); } JSModuleDef *js_init_module_uart(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_uart_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_uart_funcs, countof(js_uart_funcs)); return m; } void module_uart_register(void) { amp_debug(MOD_STR, "module_uart_register"); JSContext *ctx = js_get_context(); amp_module_free_register(native_uart_clean); js_init_module_uart(ctx, "UART"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/uart/module_uart.c
C
apache-2.0
14,608
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ /* #define LOG_NDEBUG 0 */ #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_hal_wdg.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "aos_system.h" #define MOD_STR "WDG" #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif static wdg_dev_t wdg_dev = {0}; static JSClassID js_wdg_class_id; static JSValue native_wdg_start(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int32_t timeout = 0; int8_t result = -1; wdg_dev_t *handle = (wdg_dev_t *)&wdg_dev; if((argc < 1) || (0 != JS_ToInt32(ctx, &timeout, argv[0]))) { amp_warn(MOD_STR, "parameter is invalid\n"); goto out; } handle->config.timeout = timeout; ret = aos_hal_wdg_init(handle); handle->config.timeout = (ret == 0) ? timeout : 0; out: return JS_NewInt32(ctx, result); } static JSValue native_wdg_feed(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t result = -1; wdg_dev_t *handle = (wdg_dev_t *)&wdg_dev; aos_hal_wdg_reload(handle); result = 0; out: return JS_NewInt32(ctx, result); } static JSValue native_wdg_stop(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int8_t result = -1; wdg_dev_t *handle = (wdg_dev_t *)&wdg_dev; aos_hal_wdg_finalize(handle); handle->config.timeout = 0; result = 0; out: return JS_NewInt32(ctx, result); } static JSClassDef js_wdg_class = { "WDG", }; static const JSCFunctionListEntry js_wdg_funcs[] = { JS_CFUNC_DEF("start", 1, native_wdg_start), JS_CFUNC_DEF("stop", 0, native_wdg_stop ), JS_CFUNC_DEF("feed", 0, native_wdg_feed ), }; static int js_wdg_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_wdg_class_id); JS_NewClass(JS_GetRuntime(ctx), js_wdg_class_id, &js_wdg_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_wdg_funcs, countof(js_wdg_funcs)); JS_SetClassProto(ctx, js_wdg_class_id, proto); return JS_SetModuleExportList(ctx, m, js_wdg_funcs, countof(js_wdg_funcs)); } JSModuleDef *js_init_module_wdg(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_wdg_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_wdg_funcs, countof(js_wdg_funcs)); return m; } void module_wdg_register(void) { amp_debug(MOD_STR, "module_wdg_register"); JSContext *ctx = js_get_context(); aos_printf("module wdg register\n"); js_init_module_wdg(ctx, "WDG"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/hardware/wdg/module_wdg.c
C
apache-2.0
2,889
/* * QuickJS C library * * Copyright (c) 2017-2020 Fabrice Bellard * Copyright (c) 2017-2020 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <inttypes.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/time.h> #include <time.h> #include <signal.h> #include <limits.h> #include <sys/stat.h> #if !defined(__AOS_AMP__) || defined(CONFIG_KERNEL_RHINO) || defined(CONFIG_KERNEL_LINUX) #include <dirent.h> #endif #include "aos/kernel.h" #include "aos/vfs.h" #include "aos_fs.h" #include "aos_amp_port.h" #if !defined(_WIN32) && !defined(__AOS_AMP__) /* enable the os.Worker API. IT relies on POSIX threads */ #define USE_WORKER #endif #ifdef USE_WORKER #include <pthread.h> #include <stdatomic.h> #endif #include "cutils.h" #include "list.h" #include "quickjs-libc.h" /* TODO: - add socket calls */ typedef struct { struct list_head link; int fd; JSValue rw_func[2]; } JSOSRWHandler; typedef struct { struct list_head link; int sig_num; JSValue func; } JSOSSignalHandler; typedef struct { struct list_head link; BOOL has_object; int64_t timeout; JSValue func; } JSOSTimer; typedef struct { struct list_head link; uint8_t *data; size_t data_len; /* list of SharedArrayBuffers, necessary to free the message */ uint8_t **sab_tab; size_t sab_tab_len; } JSWorkerMessage; typedef struct { int ref_count; #ifdef USE_WORKER pthread_mutex_t mutex; #endif struct list_head msg_queue; /* list of JSWorkerMessage.link */ int read_fd; int write_fd; } JSWorkerMessagePipe; typedef struct { struct list_head link; JSWorkerMessagePipe *recv_pipe; JSValue on_message_func; } JSWorkerMessageHandler; typedef struct JSThreadState { struct list_head os_rw_handlers; /* list of JSOSRWHandler.link */ struct list_head os_signal_handlers; /* list JSOSSignalHandler.link */ struct list_head os_timers; /* list of JSOSTimer.link */ struct list_head port_list; /* list of JSWorkerMessageHandler.link */ int eval_script_recurse; /* only used in the main thread */ /* not used in the main thread */ JSWorkerMessagePipe *recv_pipe, *send_pipe; } JSThreadState; static uint64_t os_pending_signals; static int (*os_poll_func)(JSContext *ctx); static void js_std_dbuf_init(JSContext *ctx, DynBuf *s) { dbuf_init2(s, JS_GetRuntime(ctx), (DynBufReallocFunc *)js_realloc_rt); } static BOOL my_isdigit(int c) { return (c >= '0' && c <= '9'); } static JSValue js_printf_internal(JSContext *ctx, int argc, JSValueConst *argv, FILE *fp) { char fmtbuf[32]; uint8_t cbuf[UTF8_CHAR_LEN_MAX + 1]; JSValue res; DynBuf dbuf; const char *fmt_str; const uint8_t *fmt, *fmt_end; const uint8_t *p; char *q; int i, c, len, mod; size_t fmt_len; int32_t int32_arg; int64_t int64_arg; double double_arg; const char *string_arg; /* Use indirect call to dbuf_printf to prevent gcc warning */ int (*dbuf_printf_fun)(DynBuf * s, const char *fmt, ...) = (void *)dbuf_printf; js_std_dbuf_init(ctx, &dbuf); if (argc > 0) { fmt_str = JS_ToCStringLen(ctx, &fmt_len, argv[0]); if (!fmt_str) { goto fail; } i = 1; fmt = (const uint8_t *)fmt_str; fmt_end = fmt + fmt_len; while (fmt < fmt_end) { for (p = fmt; fmt < fmt_end && *fmt != '%'; fmt++) { continue; } dbuf_put(&dbuf, p, fmt - p); if (fmt >= fmt_end) { break; } q = fmtbuf; *q++ = *fmt++; /* copy '%' */ /* flags */ for (;;) { c = *fmt; if (c == '0' || c == '#' || c == '+' || c == '-' || c == ' ' || c == '\'') { if (q >= fmtbuf + sizeof(fmtbuf) - 1) { goto invalid; } *q++ = c; fmt++; } else { break; } } /* width */ if (*fmt == '*') { if (i >= argc) { goto missing; } if (JS_ToInt32(ctx, &int32_arg, argv[i++])) { goto fail; } q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg); fmt++; } else { while (my_isdigit(*fmt)) { if (q >= fmtbuf + sizeof(fmtbuf) - 1) { goto invalid; } *q++ = *fmt++; } } if (*fmt == '.') { if (q >= fmtbuf + sizeof(fmtbuf) - 1) { goto invalid; } *q++ = *fmt++; if (*fmt == '*') { if (i >= argc) { goto missing; } if (JS_ToInt32(ctx, &int32_arg, argv[i++])) { goto fail; } q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg); fmt++; } else { while (my_isdigit(*fmt)) { if (q >= fmtbuf + sizeof(fmtbuf) - 1) { goto invalid; } *q++ = *fmt++; } } } /* we only support the "l" modifier for 64 bit numbers */ mod = ' '; if (*fmt == 'l') { mod = *fmt++; } /* type */ c = *fmt++; if (q >= fmtbuf + sizeof(fmtbuf) - 1) { goto invalid; } *q++ = c; *q = '\0'; switch (c) { case 'c': if (i >= argc) { goto missing; } if (JS_IsString(argv[i])) { string_arg = JS_ToCString(ctx, argv[i++]); if (!string_arg) { goto fail; } int32_arg = unicode_from_utf8((uint8_t *)string_arg, UTF8_CHAR_LEN_MAX, &p); JS_FreeCString(ctx, string_arg); } else { if (JS_ToInt32(ctx, &int32_arg, argv[i++])) { goto fail; } } /* handle utf-8 encoding explicitly */ if ((unsigned)int32_arg > 0x10FFFF) { int32_arg = 0xFFFD; } /* ignore conversion flags, width and precision */ len = unicode_to_utf8(cbuf, int32_arg); dbuf_put(&dbuf, cbuf, len); break; case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': if (i >= argc) { goto missing; } if (JS_ToInt64Ext(ctx, &int64_arg, argv[i++])) { goto fail; } if (mod == 'l') { /* 64 bit number */ #if defined(_WIN32) if (q >= fmtbuf + sizeof(fmtbuf) - 3) { goto invalid; } q[2] = q[-1]; q[-1] = 'I'; q[0] = '6'; q[1] = '4'; q[3] = '\0'; dbuf_printf_fun(&dbuf, fmtbuf, (int64_t)int64_arg); #else if (q >= fmtbuf + sizeof(fmtbuf) - 2) { goto invalid; } q[1] = q[-1]; q[-1] = q[0] = 'l'; q[2] = '\0'; dbuf_printf_fun(&dbuf, fmtbuf, (long long)int64_arg); #endif } else { dbuf_printf_fun(&dbuf, fmtbuf, (int)int64_arg); } break; case 's': if (i >= argc) { goto missing; } /* XXX: handle strings containing null characters */ string_arg = JS_ToCString(ctx, argv[i++]); if (!string_arg) { goto fail; } dbuf_printf_fun(&dbuf, fmtbuf, string_arg); JS_FreeCString(ctx, string_arg); break; case 'e': case 'f': case 'g': case 'a': case 'E': case 'F': case 'G': case 'A': if (i >= argc) { goto missing; } if (JS_ToFloat64(ctx, &double_arg, argv[i++])) { goto fail; } dbuf_printf_fun(&dbuf, fmtbuf, double_arg); break; case '%': dbuf_putc(&dbuf, '%'); break; default: /* XXX: should support an extension mechanism */ invalid: JS_ThrowTypeError(ctx, "invalid conversion specifier in format string"); goto fail; missing: JS_ThrowReferenceError(ctx, "missing argument for conversion specifier"); goto fail; } } JS_FreeCString(ctx, fmt_str); } if (dbuf.error) { res = JS_ThrowOutOfMemory(ctx); } else { if (fp) { len = fwrite(dbuf.buf, 1, dbuf.size, fp); res = JS_NewInt32(ctx, len); } else { res = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size); } } dbuf_free(&dbuf); return res; fail: dbuf_free(&dbuf); return JS_EXCEPTION; } uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename) { int f; uint8_t *buf; size_t buf_len; long lret; struct aos_stat sb; *pbuf_len = 0; if (aos_stat(filename, &sb) || !aos_fs_type(sb.st_mode)) { aos_printf("%s %s", "file not exist", filename); return NULL; } f = aos_open(filename, O_RDONLY); if (!f) { return NULL; } /* XXX: on Linux, ftell() return LONG_MAX for directories */ buf_len = sb.st_size; if (ctx) { buf = js_malloc(ctx, buf_len + 1); } else { buf = amp_malloc(buf_len + 1); } if (!buf) { goto fail; } if (aos_read(f, buf, buf_len) != buf_len) { errno = EIO; if (ctx) { js_free(ctx, buf); } else { amp_free(buf); } fail: aos_close(f); return NULL; } buf[buf_len] = '\0'; aos_close(f); *pbuf_len = buf_len; return buf; } /* load and evaluate a file */ static JSValue js_loadScript(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint8_t *buf; const char *filename; JSValue ret; size_t buf_len; filename = JS_ToCString(ctx, argv[0]); if (!filename) { return JS_EXCEPTION; } buf = js_load_file(ctx, &buf_len, filename); if (!buf) { JS_ThrowReferenceError(ctx, "could not load '%s'", filename); JS_FreeCString(ctx, filename); return JS_EXCEPTION; } ret = JS_Eval(ctx, (char *)buf, buf_len, filename, JS_EVAL_TYPE_GLOBAL); js_free(ctx, buf); JS_FreeCString(ctx, filename); return ret; } /* load a file as a UTF-8 encoded string */ static JSValue js_std_loadFile(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint8_t *buf; const char *filename; JSValue ret; size_t buf_len; filename = JS_ToCString(ctx, argv[0]); if (!filename) { return JS_EXCEPTION; } buf = js_load_file(ctx, &buf_len, filename); JS_FreeCString(ctx, filename); if (!buf) { return JS_NULL; } ret = JS_NewStringLen(ctx, (char *)buf, buf_len); js_free(ctx, buf); return ret; } typedef JSModuleDef *(JSInitModuleFunc)(JSContext *ctx, const char *module_name); #if defined(_WIN32) static JSModuleDef *js_module_loader_so(JSContext *ctx, const char *module_name) { JS_ThrowReferenceError(ctx, "shared library modules are not supported yet"); return NULL; } #elif defined(__AOS_AMP__) static JSModuleDef *js_module_loader_so(JSContext *ctx, const char *module_name) { JS_ThrowReferenceError(ctx, "shared library modules are not supported yet"); aos_printf("%s: func:%s not supported yet\n", __FILE__, __func__); return NULL; } #else static JSModuleDef *js_module_loader_so(JSContext *ctx, const char *module_name) { JSModuleDef *m; void *hd; JSInitModuleFunc *init; char *filename; if (!strchr(module_name, '/')) { /* must add a '/' so that the DLL is not searched in the system library paths */ filename = js_malloc(ctx, strlen(module_name) + 2 + 1); if (!filename) { return NULL; } strcpy(filename, "./"); strcpy(filename + 2, module_name); } else { filename = (char *)module_name; } /* C module */ hd = dlopen(filename, RTLD_NOW | RTLD_LOCAL); if (filename != module_name) { js_free(ctx, filename); } if (!hd) { JS_ThrowReferenceError(ctx, "could not load module filename '%s' as shared library", module_name); goto fail; } init = dlsym(hd, "js_init_module"); if (!init) { JS_ThrowReferenceError(ctx, "could not load module filename '%s': js_init_module not found", module_name); goto fail; } m = init(ctx, module_name); if (!m) { JS_ThrowReferenceError(ctx, "could not load module filename '%s': initialization error", module_name); fail: if (hd) { dlclose(hd); } return NULL; } return m; } #endif /* !_WIN32 */ int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val, JS_BOOL use_realpath, JS_BOOL is_main) { JSModuleDef *m; char buf[PATH_MAX + 16]; JSValue meta_obj; JSAtom module_name_atom; const char *module_name; assert(JS_VALUE_GET_TAG(func_val) == JS_TAG_MODULE); m = JS_VALUE_GET_PTR(func_val); module_name_atom = JS_GetModuleName(ctx, m); module_name = JS_AtomToCString(ctx, module_name_atom); JS_FreeAtom(ctx, module_name_atom); if (!module_name) { return -1; } if (!strchr(module_name, ':')) { strcpy(buf, "file://"); #if !defined(_WIN32) && !defined(__AOS_AMP__) /* realpath() cannot be used with modules compiled with qjsc because the corresponding module source code is not necessarily present */ if (use_realpath) { char *res = realpath(module_name, buf + strlen(buf)); if (!res) { JS_ThrowTypeError(ctx, "realpath failure"); JS_FreeCString(ctx, module_name); return -1; } } else #endif { pstrcat(buf, sizeof(buf), module_name); } } else { pstrcpy(buf, sizeof(buf), module_name); } JS_FreeCString(ctx, module_name); meta_obj = JS_GetImportMeta(ctx, m); if (JS_IsException(meta_obj)) { return -1; } JS_DefinePropertyValueStr(ctx, meta_obj, "url", JS_NewString(ctx, buf), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, meta_obj, "main", JS_NewBool(ctx, is_main), JS_PROP_C_W_E); JS_FreeValue(ctx, meta_obj); return 0; } JSModuleDef *js_module_loader(JSContext *ctx, const char *module_name, void *opaque) { JSModuleDef *m; if (has_suffix(module_name, ".so")) { m = js_module_loader_so(ctx, module_name); } else { size_t buf_len; uint8_t *buf; JSValue func_val; buf = js_load_file(ctx, &buf_len, module_name); if (!buf) { JS_ThrowReferenceError(ctx, "could not load module filename '%s'", module_name); return NULL; } /* compile the module */ func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); js_free(ctx, buf); if (JS_IsException(func_val)) { return NULL; } /* XXX: could propagate the exception */ js_module_set_import_meta(ctx, func_val, TRUE, FALSE); /* the module is already referenced, so we must free it */ m = JS_VALUE_GET_PTR(func_val); JS_FreeValue(ctx, func_val); } return m; } static JSValue js_std_exit(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int status; if (JS_ToInt32(ctx, &status, argv[0])) { status = -1; } exit(status); return JS_UNDEFINED; } static JSValue js_std_getenv(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *name, *str; name = JS_ToCString(ctx, argv[0]); if (!name) { return JS_EXCEPTION; } str = getenv(name); JS_FreeCString(ctx, name); if (!str) { return JS_UNDEFINED; } else { return JS_NewString(ctx, str); } } static JSValue js_std_gc(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JS_RunGC(JS_GetRuntime(ctx)); return JS_UNDEFINED; } static int interrupt_handler(JSRuntime *rt, void *opaque) { #if !defined(__AOS_AMP__) return (os_pending_signals >> SIGINT) & 1; #else #endif } static int get_bool_option(JSContext *ctx, BOOL *pbool, JSValueConst obj, const char *option) { JSValue val; val = JS_GetPropertyStr(ctx, obj, option); if (JS_IsException(val)) { return -1; } if (!JS_IsUndefined(val)) { *pbool = JS_ToBool(ctx, val); } JS_FreeValue(ctx, val); return 0; } static JSValue js_evalScript(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); const char *str; size_t len; JSValue ret; JSValueConst options_obj; BOOL backtrace_barrier = FALSE; int flags; if (argc >= 2) { options_obj = argv[1]; if (get_bool_option(ctx, &backtrace_barrier, options_obj, "backtrace_barrier")) { return JS_EXCEPTION; } } str = JS_ToCStringLen(ctx, &len, argv[0]); if (!str) { return JS_EXCEPTION; } if (!ts->recv_pipe && ++ts->eval_script_recurse == 1) { /* install the interrupt handler */ JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL); } flags = JS_EVAL_TYPE_GLOBAL; if (backtrace_barrier) { flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER; } ret = JS_Eval(ctx, str, len, "<evalScript>", flags); JS_FreeCString(ctx, str); if (!ts->recv_pipe && --ts->eval_script_recurse == 0) { /* remove the interrupt handler */ JS_SetInterruptHandler(JS_GetRuntime(ctx), NULL, NULL); #if !defined(__AOS_AMP__) os_pending_signals &= ~((uint64_t)1 << SIGINT); #endif /* convert the uncatchable "interrupted" error into a normal error so that it can be caught by the REPL */ if (JS_IsException(ret)) { JS_ResetUncatchableError(ctx); } } return ret; } static JSValue js_evalScript_m(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); const char *str; size_t len; JSValue ret; JSValueConst options_obj; BOOL backtrace_barrier = FALSE; int flags; if (argc >= 2) { options_obj = argv[1]; if (get_bool_option(ctx, &backtrace_barrier, options_obj, "backtrace_barrier")) { return JS_EXCEPTION; } } str = JS_ToCStringLen(ctx, &len, argv[0]); if (!str) { return JS_EXCEPTION; } if (!ts->recv_pipe && ++ts->eval_script_recurse == 1) { /* install the interrupt handler */ JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL); } flags = JS_EVAL_TYPE_MODULE; if (backtrace_barrier) { flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER; } ret = JS_Eval(ctx, str, len, "<input>", flags); JS_FreeCString(ctx, str); if (!ts->recv_pipe && --ts->eval_script_recurse == 0) { /* remove the interrupt handler */ JS_SetInterruptHandler(JS_GetRuntime(ctx), NULL, NULL); #if !defined(__AOS_AMP__) os_pending_signals &= ~((uint64_t)1 << SIGINT); #endif /* convert the uncatchable "interrupted" error into a normal error so that it can be caught by the REPL */ if (JS_IsException(ret)) { JS_ResetUncatchableError(ctx); } } return ret; } static JSClassID js_std_file_class_id; typedef struct { FILE *f; BOOL close_in_finalizer; BOOL is_popen; } JSSTDFile; static void js_std_file_finalizer(JSRuntime *rt, JSValue val) { JSSTDFile *s = JS_GetOpaque(val, js_std_file_class_id); if (s) { if (s->f && s->close_in_finalizer) { if (s->is_popen) { #if !defined(__AOS_AMP__) pclose(s->f); #endif } else { fclose(s->f); } } js_free_rt(rt, s); } } static ssize_t js_get_errno(ssize_t ret) { if (ret == -1) { ret = -errno; } return ret; } static JSValue js_std_strerror(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int err; if (JS_ToInt32(ctx, &err, argv[0])) { return JS_EXCEPTION; } return JS_NewString(ctx, strerror(err)); } static JSValue js_std_parseExtJSON(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSValue obj; const char *str; size_t len; str = JS_ToCStringLen(ctx, &len, argv[0]); if (!str) { return JS_EXCEPTION; } obj = JS_ParseJSON2(ctx, str, len, "<input>", JS_PARSE_JSON_EXT); JS_FreeCString(ctx, str); return obj; } static JSValue js_new_std_file(JSContext *ctx, FILE *f, BOOL close_in_finalizer, BOOL is_popen) { JSSTDFile *s; JSValue obj; obj = JS_NewObjectClass(ctx, js_std_file_class_id); if (JS_IsException(obj)) { return obj; } s = js_mallocz(ctx, sizeof(*s)); if (!s) { JS_FreeValue(ctx, obj); return JS_EXCEPTION; } s->close_in_finalizer = close_in_finalizer; s->is_popen = is_popen; s->f = f; JS_SetOpaque(obj, s); return obj; } static void js_set_error_object(JSContext *ctx, JSValue obj, int err) { if (!JS_IsUndefined(obj)) { JS_SetPropertyStr(ctx, obj, "errno", JS_NewInt32(ctx, err)); } } static JSValue js_std_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename, *mode = NULL; FILE *f; int err; filename = JS_ToCString(ctx, argv[0]); if (!filename) { goto fail; } mode = JS_ToCString(ctx, argv[1]); if (!mode) { goto fail; } if (mode[strspn(mode, "rwa+b")] != '\0') { JS_ThrowTypeError(ctx, "invalid file mode"); goto fail; } f = fopen(filename, mode); if (!f) { err = errno; } else { err = 0; } if (argc >= 3) { js_set_error_object(ctx, argv[2], err); } JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); if (!f) { return JS_NULL; } return js_new_std_file(ctx, f, TRUE, FALSE); fail: JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); return JS_EXCEPTION; } #if !defined(__AOS_AMP__) static JSValue js_std_popen(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename, *mode = NULL; FILE *f; int err; filename = JS_ToCString(ctx, argv[0]); if (!filename) { goto fail; } mode = JS_ToCString(ctx, argv[1]); if (!mode) { goto fail; } if (mode[strspn(mode, "rw")] != '\0') { JS_ThrowTypeError(ctx, "invalid file mode"); goto fail; } f = popen(filename, mode); if (!f) { err = errno; } else { err = 0; } if (argc >= 3) { js_set_error_object(ctx, argv[2], err); } JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); if (!f) { return JS_NULL; } return js_new_std_file(ctx, f, TRUE, TRUE); fail: JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); return JS_EXCEPTION; } #endif static JSValue js_std_fdopen(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *mode; FILE *f; int fd, err; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } mode = JS_ToCString(ctx, argv[1]); if (!mode) { goto fail; } if (mode[strspn(mode, "rwa+")] != '\0') { JS_ThrowTypeError(ctx, "invalid file mode"); goto fail; } f = fdopen(fd, mode); if (!f) { err = errno; } else { err = 0; } if (argc >= 3) { js_set_error_object(ctx, argv[2], err); } JS_FreeCString(ctx, mode); if (!f) { return JS_NULL; } return js_new_std_file(ctx, f, TRUE, FALSE); fail: JS_FreeCString(ctx, mode); return JS_EXCEPTION; } static JSValue js_std_tmpfile(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f; f = tmpfile(); if (argc >= 1) { js_set_error_object(ctx, argv[0], f ? 0 : errno); } if (!f) { return JS_NULL; } return js_new_std_file(ctx, f, TRUE, FALSE); } static JSValue js_std_sprintf(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return js_printf_internal(ctx, argc, argv, NULL); } static JSValue js_std_printf(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return js_printf_internal(ctx, argc, argv, stdout); } static FILE *js_std_file_get(JSContext *ctx, JSValueConst obj) { JSSTDFile *s = JS_GetOpaque2(ctx, obj, js_std_file_class_id); if (!s) { return NULL; } if (!s->f) { JS_ThrowTypeError(ctx, "invalid file handle"); return NULL; } return s->f; } static JSValue js_std_file_puts(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { FILE *f; int i; const char *str; size_t len; if (magic == 0) { f = stdout; } else { f = js_std_file_get(ctx, this_val); if (!f) { return JS_EXCEPTION; } } for (i = 0; i < argc; i++) { str = JS_ToCStringLen(ctx, &len, argv[i]); if (!str) { return JS_EXCEPTION; } if (magic == 0) { char *out = aos_malloc(len + 1); memcpy(out, str, len); out[len] = '\0'; printf("%s", out); aos_free(out); } else { fwrite(str, 1, len, f); } JS_FreeCString(ctx, str); } return JS_UNDEFINED; } static JSValue js_std_file_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSSTDFile *s = JS_GetOpaque2(ctx, this_val, js_std_file_class_id); int err; if (!s) { return JS_EXCEPTION; } if (!s->f) { return JS_ThrowTypeError(ctx, "invalid file handle"); } if (s->is_popen) #if !defined(__AOS_AMP__) err = js_get_errno(pclose(s->f)); #else err = 0; #endif else { err = js_get_errno(fclose(s->f)); } s->f = NULL; return JS_NewInt32(ctx, err); } static JSValue js_std_file_printf(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) { return JS_EXCEPTION; } return js_printf_internal(ctx, argc, argv, f); } static JSValue js_std_file_flush(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) { return JS_EXCEPTION; } fflush(f); return JS_UNDEFINED; } static JSValue js_std_file_tell(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int is_bigint) { FILE *f = js_std_file_get(ctx, this_val); int64_t pos; if (!f) { return JS_EXCEPTION; } #if defined(__linux__) pos = ftello(f); #else pos = ftell(f); #endif if (is_bigint) { return JS_NewBigInt64(ctx, pos); } else { return JS_NewInt64(ctx, pos); } } static JSValue js_std_file_seek(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int64_t pos; int whence, ret; if (!f) { return JS_EXCEPTION; } if (JS_ToInt64Ext(ctx, &pos, argv[0])) { return JS_EXCEPTION; } if (JS_ToInt32(ctx, &whence, argv[1])) { return JS_EXCEPTION; } #if defined(__linux__) ret = fseeko(f, pos, whence); #else ret = fseek(f, pos, whence); #endif if (ret < 0) { ret = -errno; } return JS_NewInt32(ctx, ret); } static JSValue js_std_file_eof(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) { return JS_EXCEPTION; } return JS_NewBool(ctx, feof(f)); } static JSValue js_std_file_error(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) { return JS_EXCEPTION; } return JS_NewBool(ctx, ferror(f)); } static JSValue js_std_file_clearerr(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) { return JS_EXCEPTION; } clearerr(f); return JS_UNDEFINED; } static JSValue js_std_file_fileno(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) { return JS_EXCEPTION; } return JS_NewInt32(ctx, fileno(f)); } static JSValue js_std_file_read_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { FILE *f = js_std_file_get(ctx, this_val); uint64_t pos, len; size_t size, ret; uint8_t *buf; if (!f) { return JS_EXCEPTION; } if (JS_ToIndex(ctx, &pos, argv[1])) { return JS_EXCEPTION; } if (JS_ToIndex(ctx, &len, argv[2])) { return JS_EXCEPTION; } buf = JS_GetArrayBuffer(ctx, &size, argv[0]); if (!buf) { return JS_EXCEPTION; } if (pos + len > size) { return JS_ThrowRangeError(ctx, "read/write array buffer overflow"); } if (magic) { ret = fwrite(buf + pos, 1, len, f); } else { ret = fread(buf + pos, 1, len, f); } return JS_NewInt64(ctx, ret); } /* XXX: could use less memory and go faster */ static JSValue js_std_file_getline(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int c; DynBuf dbuf; JSValue obj; if (!f) { return JS_EXCEPTION; } js_std_dbuf_init(ctx, &dbuf); for (;;) { c = fgetc(f); if (c == EOF) { if (dbuf.size == 0) { /* EOF */ dbuf_free(&dbuf); return JS_NULL; } else { break; } } if (c == '\n') { break; } if (dbuf_putc(&dbuf, c)) { dbuf_free(&dbuf); return JS_ThrowOutOfMemory(ctx); } } obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size); dbuf_free(&dbuf); return obj; } /* XXX: could use less memory and go faster */ static JSValue js_std_file_readAsString(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int c; DynBuf dbuf; JSValue obj; uint64_t max_size64; size_t max_size; JSValueConst max_size_val; if (!f) { return JS_EXCEPTION; } if (argc >= 1) { max_size_val = argv[0]; } else { max_size_val = JS_UNDEFINED; } max_size = (size_t) -1; if (!JS_IsUndefined(max_size_val)) { if (JS_ToIndex(ctx, &max_size64, max_size_val)) { return JS_EXCEPTION; } if (max_size64 < max_size) { max_size = max_size64; } } js_std_dbuf_init(ctx, &dbuf); while (max_size != 0) { c = fgetc(f); if (c == EOF) { break; } if (dbuf_putc(&dbuf, c)) { dbuf_free(&dbuf); return JS_EXCEPTION; } max_size--; } obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size); dbuf_free(&dbuf); return obj; } static JSValue js_std_file_getByte(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) { return JS_EXCEPTION; } return JS_NewInt32(ctx, fgetc(f)); } static JSValue js_std_file_putByte(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int c; if (!f) { return JS_EXCEPTION; } if (JS_ToInt32(ctx, &c, argv[0])) { return JS_EXCEPTION; } c = fputc(c, f); return JS_NewInt32(ctx, c); } /* urlGet */ #define URL_GET_PROGRAM "curl -s -i" #define URL_GET_BUF_SIZE 4096 static int http_get_header_line(FILE *f, char *buf, size_t buf_size, DynBuf *dbuf) { int c; char *p; p = buf; for (;;) { c = fgetc(f); if (c < 0) { return -1; } if ((p - buf) < buf_size - 1) { *p++ = c; } if (dbuf) { dbuf_putc(dbuf, c); } if (c == '\n') { break; } } *p = '\0'; return 0; } static int http_get_status(const char *buf) { const char *p = buf; while (*p != ' ' && *p != '\0') { p++; } if (*p != ' ') { return 0; } while (*p == ' ') { p++; } return atoi(p); } #if !defined(__AOS_AMP__) static JSValue js_std_urlGet(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *url; DynBuf cmd_buf; DynBuf data_buf_s, *data_buf = &data_buf_s; DynBuf header_buf_s, *header_buf = &header_buf_s; char *buf; size_t i, len; int c, status; JSValue response = JS_UNDEFINED, ret_obj; JSValueConst options_obj; FILE *f; BOOL binary_flag, full_flag; url = JS_ToCString(ctx, argv[0]); if (!url) { return JS_EXCEPTION; } binary_flag = FALSE; full_flag = FALSE; if (argc >= 2) { options_obj = argv[1]; if (get_bool_option(ctx, &binary_flag, options_obj, "binary")) { goto fail_obj; } if (get_bool_option(ctx, &full_flag, options_obj, "full")) { fail_obj: JS_FreeCString(ctx, url); return JS_EXCEPTION; } } js_std_dbuf_init(ctx, &cmd_buf); dbuf_printf(&cmd_buf, "%s ''", URL_GET_PROGRAM); len = strlen(url); for (i = 0; i < len; i++) { c = url[i]; if (c == '\'' || c == '\\') { dbuf_putc(&cmd_buf, '\\'); } dbuf_putc(&cmd_buf, c); } JS_FreeCString(ctx, url); dbuf_putstr(&cmd_buf, "''"); dbuf_putc(&cmd_buf, '\0'); if (dbuf_error(&cmd_buf)) { dbuf_free(&cmd_buf); return JS_EXCEPTION; } // printf("%s\n", (char *)cmd_buf.buf); f = popen((char *)cmd_buf.buf, "r"); dbuf_free(&cmd_buf); if (!f) { return JS_ThrowTypeError(ctx, "could not start curl"); } js_std_dbuf_init(ctx, data_buf); js_std_dbuf_init(ctx, header_buf); buf = js_malloc(ctx, URL_GET_BUF_SIZE); if (!buf) { goto fail; } /* get the HTTP status */ if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, NULL) < 0) { status = 0; goto bad_header; } status = http_get_status(buf); if (!full_flag && !(status >= 200 && status <= 299)) { goto bad_header; } /* wait until there is an empty line */ for (;;) { if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, header_buf) < 0) { bad_header: response = JS_NULL; goto done; } if (!strcmp(buf, "\r\n")) { break; } } if (dbuf_error(header_buf)) { goto fail; } header_buf->size -= 2; /* remove the trailing CRLF */ /* download the data */ for (;;) { len = fread(buf, 1, URL_GET_BUF_SIZE, f); if (len == 0) { break; } dbuf_put(data_buf, (uint8_t *)buf, len); } if (dbuf_error(data_buf)) { goto fail; } if (binary_flag) { response = JS_NewArrayBufferCopy(ctx, data_buf->buf, data_buf->size); } else { response = JS_NewStringLen(ctx, (char *)data_buf->buf, data_buf->size); } if (JS_IsException(response)) { goto fail; } done: js_free(ctx, buf); buf = NULL; pclose(f); f = NULL; dbuf_free(data_buf); data_buf = NULL; if (full_flag) { ret_obj = JS_NewObject(ctx); if (JS_IsException(ret_obj)) { goto fail; } JS_DefinePropertyValueStr(ctx, ret_obj, "response", response, JS_PROP_C_W_E); if (!JS_IsNull(response)) { JS_DefinePropertyValueStr(ctx, ret_obj, "responseHeaders", JS_NewStringLen(ctx, (char *)header_buf->buf, header_buf->size), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, ret_obj, "status", JS_NewInt32(ctx, status), JS_PROP_C_W_E); } } else { ret_obj = response; } dbuf_free(header_buf); return ret_obj; fail: if (f) { pclose(f); } js_free(ctx, buf); if (data_buf) { dbuf_free(data_buf); } if (header_buf) { dbuf_free(header_buf); } JS_FreeValue(ctx, response); return JS_EXCEPTION; } #endif static JSClassDef js_std_file_class = { "FILE", .finalizer = js_std_file_finalizer, }; static const JSCFunctionListEntry js_std_error_props[] = { /* various errno values */ #define DEF(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE ) DEF(EINVAL), DEF(EIO), DEF(EACCES), DEF(EEXIST), DEF(ENOSPC), DEF(ENOSYS), DEF(EBUSY), DEF(ENOENT), DEF(EPERM), DEF(EPIPE), DEF(EBADF), #undef DEF }; static const JSCFunctionListEntry js_std_funcs[] = { JS_CFUNC_DEF("exit", 1, js_std_exit), JS_CFUNC_DEF("gc", 0, js_std_gc), JS_CFUNC_DEF("evalScript", 1, js_evalScript), JS_CFUNC_DEF("eval", 1, js_evalScript_m), JS_CFUNC_DEF("loadScript", 1, js_loadScript), JS_CFUNC_DEF("getenv", 1, js_std_getenv), #if !defined(__AOS_AMP__) JS_CFUNC_DEF("urlGet", 1, js_std_urlGet), #endif JS_CFUNC_DEF("loadFile", 1, js_std_loadFile), JS_CFUNC_DEF("strerror", 1, js_std_strerror), JS_CFUNC_DEF("parseExtJSON", 1, js_std_parseExtJSON), /* FILE I/O */ JS_CFUNC_DEF("open", 2, js_std_open), #if !defined(__AOS_AMP__) JS_CFUNC_DEF("popen", 2, js_std_popen), #endif JS_CFUNC_DEF("fdopen", 2, js_std_fdopen), JS_CFUNC_DEF("tmpfile", 0, js_std_tmpfile), JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 0), JS_CFUNC_DEF("printf", 1, js_std_printf), JS_CFUNC_DEF("sprintf", 1, js_std_sprintf), JS_PROP_INT32_DEF("SEEK_SET", SEEK_SET, JS_PROP_CONFIGURABLE), JS_PROP_INT32_DEF("SEEK_CUR", SEEK_CUR, JS_PROP_CONFIGURABLE), JS_PROP_INT32_DEF("SEEK_END", SEEK_END, JS_PROP_CONFIGURABLE), JS_OBJECT_DEF("Error", js_std_error_props, countof(js_std_error_props), JS_PROP_CONFIGURABLE), /* setenv, ... */ }; static const JSCFunctionListEntry js_std_file_proto_funcs[] = { JS_CFUNC_DEF("close", 0, js_std_file_close), JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 1), JS_CFUNC_DEF("printf", 1, js_std_file_printf), JS_CFUNC_DEF("flush", 0, js_std_file_flush), JS_CFUNC_MAGIC_DEF("tell", 0, js_std_file_tell, 0), JS_CFUNC_MAGIC_DEF("tello", 0, js_std_file_tell, 1), JS_CFUNC_DEF("seek", 2, js_std_file_seek), JS_CFUNC_DEF("eof", 0, js_std_file_eof), JS_CFUNC_DEF("fileno", 0, js_std_file_fileno), JS_CFUNC_DEF("error", 0, js_std_file_error), JS_CFUNC_DEF("clearerr", 0, js_std_file_clearerr), JS_CFUNC_MAGIC_DEF("read", 3, js_std_file_read_write, 0), JS_CFUNC_MAGIC_DEF("write", 3, js_std_file_read_write, 1), JS_CFUNC_DEF("getline", 0, js_std_file_getline), JS_CFUNC_DEF("readAsString", 0, js_std_file_readAsString), JS_CFUNC_DEF("getByte", 0, js_std_file_getByte), JS_CFUNC_DEF("putByte", 1, js_std_file_putByte), /* setvbuf, ... */ }; static int js_std_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; /* FILE class */ /* the class ID is created once */ JS_NewClassID(&js_std_file_class_id); /* the class is created once per runtime */ JS_NewClass(JS_GetRuntime(ctx), js_std_file_class_id, &js_std_file_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_std_file_proto_funcs, countof(js_std_file_proto_funcs)); JS_SetClassProto(ctx, js_std_file_class_id, proto); JS_SetModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs)); JS_SetModuleExport(ctx, m, "in", js_new_std_file(ctx, stdin, FALSE, FALSE)); JS_SetModuleExport(ctx, m, "out", js_new_std_file(ctx, stdout, FALSE, FALSE)); JS_SetModuleExport(ctx, m, "err", js_new_std_file(ctx, stderr, FALSE, FALSE)); return 0; } JSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_std_init); if (!m) { return NULL; } JS_AddModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs)); JS_AddModuleExport(ctx, m, "in"); JS_AddModuleExport(ctx, m, "out"); JS_AddModuleExport(ctx, m, "err"); return m; } /**********************************************************/ /* 'os' object */ static JSValue js_os_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename; int flags, mode, ret; filename = JS_ToCString(ctx, argv[0]); if (!filename) { return JS_EXCEPTION; } if (JS_ToInt32(ctx, &flags, argv[1])) { goto fail; } if (argc >= 3 && !JS_IsUndefined(argv[2])) { if (JS_ToInt32(ctx, &mode, argv[2])) { fail: JS_FreeCString(ctx, filename); return JS_EXCEPTION; } } else { mode = 0666; } #if defined(_WIN32) /* force binary mode by default */ if (!(flags & O_TEXT)) { flags |= O_BINARY; } #endif ret = js_get_errno(open(filename, flags, mode)); JS_FreeCString(ctx, filename); return JS_NewInt32(ctx, ret); } static JSValue js_os_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, ret; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } ret = js_get_errno(close(fd)); return JS_NewInt32(ctx, ret); } static JSValue js_os_seek(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, whence; int64_t pos, ret; BOOL is_bigint; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } is_bigint = JS_IsBigInt(ctx, argv[1]); if (JS_ToInt64Ext(ctx, &pos, argv[1])) { return JS_EXCEPTION; } if (JS_ToInt32(ctx, &whence, argv[2])) { return JS_EXCEPTION; } ret = lseek(fd, pos, whence); if (ret == -1) { ret = -errno; } if (is_bigint) { return JS_NewBigInt64(ctx, ret); } else { return JS_NewInt64(ctx, ret); } } static JSValue js_os_read_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { int fd; uint64_t pos, len; size_t size; ssize_t ret; uint8_t *buf; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } if (JS_ToIndex(ctx, &pos, argv[2])) { return JS_EXCEPTION; } if (JS_ToIndex(ctx, &len, argv[3])) { return JS_EXCEPTION; } buf = JS_GetArrayBuffer(ctx, &size, argv[1]); if (!buf) { return JS_EXCEPTION; } if (pos + len > size) { return JS_ThrowRangeError(ctx, "read/write array buffer overflow"); } if (magic) { ret = js_get_errno(write(fd, buf + pos, len)); } else { ret = js_get_errno(read(fd, buf + pos, len)); } return JS_NewInt64(ctx, ret); } static JSValue js_os_isatty(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } return JS_NewBool(ctx, isatty(fd) == 1); } #if defined(_WIN32) static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; HANDLE handle; CONSOLE_SCREEN_BUFFER_INFO info; JSValue obj; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } handle = (HANDLE)_get_osfhandle(fd); if (!GetConsoleScreenBufferInfo(handle, &info)) { return JS_NULL; } obj = JS_NewArray(ctx); if (JS_IsException(obj)) { return obj; } JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, info.dwSize.X), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, info.dwSize.Y), JS_PROP_C_W_E); return obj; } static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; HANDLE handle; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } handle = (HANDLE)_get_osfhandle(fd); SetConsoleMode(handle, ENABLE_WINDOW_INPUT); return JS_UNDEFINED; } #elif defined(__AOS_AMP__) static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JS_ThrowReferenceError(ctx, "func:%s not supported yet", __func__); printf("%s: func:%s not supported yet\n", __FILE__, __func__); return JS_EXCEPTION; } static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JS_ThrowReferenceError(ctx, "func:%s not supported yet", __func__); printf("%s: func:%s not supported yet\n", __FILE__, __func__); return JS_EXCEPTION; } #else static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; struct winsize ws; JSValue obj; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } if (ioctl(fd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 4 && ws.ws_row >= 4) { obj = JS_NewArray(ctx); if (JS_IsException(obj)) { return obj; } JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ws.ws_col), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, ws.ws_row), JS_PROP_C_W_E); return obj; } else { return JS_NULL; } } static struct termios oldtty; static void term_exit(void) { tcsetattr(0, TCSANOW, &oldtty); } /* XXX: should add a way to go back to normal mode */ static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { struct termios tty; int fd; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } memset(&tty, 0, sizeof(tty)); tcgetattr(fd, &tty); oldtty = tty; tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); tty.c_oflag |= OPOST; tty.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN); tty.c_cflag &= ~(CSIZE | PARENB); tty.c_cflag |= CS8; tty.c_cc[VMIN] = 1; tty.c_cc[VTIME] = 0; tcsetattr(fd, TCSANOW, &tty); atexit(term_exit); return JS_UNDEFINED; } #endif /* !_WIN32 */ static JSValue js_os_remove(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename; int ret; filename = JS_ToCString(ctx, argv[0]); if (!filename) { return JS_EXCEPTION; } ret = js_get_errno(remove(filename)); JS_FreeCString(ctx, filename); return JS_NewInt32(ctx, ret); } static JSValue js_os_rename(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *oldpath, *newpath; int ret; oldpath = JS_ToCString(ctx, argv[0]); if (!oldpath) { return JS_EXCEPTION; } newpath = JS_ToCString(ctx, argv[1]); if (!newpath) { JS_FreeCString(ctx, oldpath); return JS_EXCEPTION; } ret = js_get_errno(rename(oldpath, newpath)); JS_FreeCString(ctx, oldpath); JS_FreeCString(ctx, newpath); return JS_NewInt32(ctx, ret); } static BOOL is_main_thread(JSRuntime *rt) { JSThreadState *ts = JS_GetRuntimeOpaque(rt); return !ts->recv_pipe; } static JSOSRWHandler *find_rh(JSThreadState *ts, int fd) { JSOSRWHandler *rh; struct list_head *el; list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (rh->fd == fd) { return rh; } } return NULL; } static void free_rw_handler(JSRuntime *rt, JSOSRWHandler *rh) { int i; list_del(&rh->link); for (i = 0; i < 2; i++) { JS_FreeValueRT(rt, rh->rw_func[i]); } js_free_rt(rt, rh); } static JSValue js_os_setReadHandler(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); JSOSRWHandler *rh; int fd; JSValueConst func; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } func = argv[1]; if (JS_IsNull(func)) { rh = find_rh(ts, fd); if (rh) { JS_FreeValue(ctx, rh->rw_func[magic]); rh->rw_func[magic] = JS_NULL; if (JS_IsNull(rh->rw_func[0]) && JS_IsNull(rh->rw_func[1])) { /* remove the entry */ free_rw_handler(JS_GetRuntime(ctx), rh); } } } else { if (!JS_IsFunction(ctx, func)) { return JS_ThrowTypeError(ctx, "not a function"); } rh = find_rh(ts, fd); if (!rh) { rh = js_mallocz(ctx, sizeof(*rh)); if (!rh) { return JS_EXCEPTION; } rh->fd = fd; rh->rw_func[0] = JS_NULL; rh->rw_func[1] = JS_NULL; list_add_tail(&rh->link, &ts->os_rw_handlers); } JS_FreeValue(ctx, rh->rw_func[magic]); rh->rw_func[magic] = JS_DupValue(ctx, func); } return JS_UNDEFINED; } static JSOSSignalHandler *find_sh(JSThreadState *ts, int sig_num) { JSOSSignalHandler *sh; struct list_head *el; list_for_each(el, &ts->os_signal_handlers) { sh = list_entry(el, JSOSSignalHandler, link); if (sh->sig_num == sig_num) { return sh; } } return NULL; } static void free_sh(JSRuntime *rt, JSOSSignalHandler *sh) { list_del(&sh->link); JS_FreeValueRT(rt, sh->func); js_free_rt(rt, sh); } static void os_signal_handler(int sig_num) { os_pending_signals |= ((uint64_t)1 << sig_num); } #if defined(_WIN32) typedef void (*sighandler_t)(int sig_num); #endif #if defined(__AOS_AMP__) static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { printf("%s: func:%s not supported yet\n", __FILE__, __func__); return JS_UNDEFINED; } #else static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); JSOSSignalHandler *sh; uint32_t sig_num; JSValueConst func; sighandler_t handler; if (!is_main_thread(rt)) { return JS_ThrowTypeError(ctx, "signal handler can only be set in the main thread"); } if (JS_ToUint32(ctx, &sig_num, argv[0])) { return JS_EXCEPTION; } if (sig_num >= 64) { return JS_ThrowRangeError(ctx, "invalid signal number"); } func = argv[1]; /* func = null: SIG_DFL, func = undefined, SIG_IGN */ if (JS_IsNull(func) || JS_IsUndefined(func)) { sh = find_sh(ts, sig_num); if (sh) { free_sh(JS_GetRuntime(ctx), sh); } if (JS_IsNull(func)) { handler = SIG_DFL; } else { handler = SIG_IGN; } signal(sig_num, handler); } else { if (!JS_IsFunction(ctx, func)) { return JS_ThrowTypeError(ctx, "not a function"); } sh = find_sh(ts, sig_num); if (!sh) { sh = js_mallocz(ctx, sizeof(*sh)); if (!sh) { return JS_EXCEPTION; } sh->sig_num = sig_num; list_add_tail(&sh->link, &ts->os_signal_handlers); } JS_FreeValue(ctx, sh->func); sh->func = JS_DupValue(ctx, func); signal(sig_num, os_signal_handler); } return JS_UNDEFINED; } #endif /* __AOS_AMP__ */ #if defined(__linux__) || defined(__APPLE__) static int64_t get_time_ms(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000); } #else /* more portable, but does not work if the date is updated */ static int64_t get_time_ms(void) { struct timeval tv; gettimeofday(&tv, NULL); return (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000); } #endif static void unlink_timer(JSRuntime *rt, JSOSTimer *th) { if (th->link.prev) { list_del(&th->link); th->link.prev = th->link.next = NULL; } } static void free_timer(JSRuntime *rt, JSOSTimer *th) { JS_FreeValueRT(rt, th->func); js_free_rt(rt, th); } static JSClassID js_os_timer_class_id; static void js_os_timer_finalizer(JSRuntime *rt, JSValue val) { JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id); if (th) { th->has_object = FALSE; if (!th->link.prev) { free_timer(rt, th); } } } static void js_os_timer_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id); if (th) { JS_MarkValue(rt, th->func, mark_func); } } static JSValue js_os_setTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); int64_t delay; JSValueConst func; JSOSTimer *th; JSValue obj; func = argv[0]; if (!JS_IsFunction(ctx, func)) { return JS_ThrowTypeError(ctx, "not a function"); } if (JS_ToInt64(ctx, &delay, argv[1])) { return JS_EXCEPTION; } obj = JS_NewObjectClass(ctx, js_os_timer_class_id); if (JS_IsException(obj)) { return obj; } th = js_mallocz(ctx, sizeof(*th)); if (!th) { JS_FreeValue(ctx, obj); return JS_EXCEPTION; } th->has_object = TRUE; th->timeout = get_time_ms() + delay; th->func = JS_DupValue(ctx, func); list_add_tail(&th->link, &ts->os_timers); JS_SetOpaque(obj, th); return obj; } static JSValue js_os_clearTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSOSTimer *th = JS_GetOpaque2(ctx, argv[0], js_os_timer_class_id); if (!th) { return JS_EXCEPTION; } unlink_timer(JS_GetRuntime(ctx), th); return JS_UNDEFINED; } static JSClassDef js_os_timer_class = { "OSTimer", .finalizer = js_os_timer_finalizer, .gc_mark = js_os_timer_mark, }; static void call_handler(JSContext *ctx, JSValueConst func) { JSValue ret, func1; /* 'func' might be destroyed when calling itself (if it frees the handler), so must take extra care */ func1 = JS_DupValue(ctx, func); ret = JS_Call(ctx, func1, JS_UNDEFINED, 0, NULL); JS_FreeValue(ctx, func1); if (JS_IsException(ret)) { js_std_dump_error(ctx); } JS_FreeValue(ctx, ret); } #if defined(_WIN32) static int js_os_poll(JSContext *ctx) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); int min_delay, console_fd; int64_t cur_time, delay; JSOSRWHandler *rh; struct list_head *el; /* XXX: handle signals if useful */ if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers)) { return -1; /* no more events */ } /* XXX: only timers and basic console input are supported */ if (!list_empty(&ts->os_timers)) { cur_time = get_time_ms(); min_delay = 10000; list_for_each(el, &ts->os_timers) { JSOSTimer *th = list_entry(el, JSOSTimer, link); delay = th->timeout - cur_time; if (delay <= 0) { JSValue func; /* the timer expired */ func = th->func; th->func = JS_UNDEFINED; unlink_timer(rt, th); if (!th->has_object) { free_timer(rt, th); } call_handler(ctx, func); JS_FreeValue(ctx, func); return 0; } else if (delay < min_delay) { min_delay = delay; } } } else { min_delay = -1; } console_fd = -1; list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (rh->fd == 0 && !JS_IsNull(rh->rw_func[0])) { console_fd = rh->fd; break; } } if (console_fd >= 0) { DWORD ti, ret; HANDLE handle; if (min_delay == -1) { ti = INFINITE; } else { ti = min_delay; } handle = (HANDLE)_get_osfhandle(console_fd); ret = WaitForSingleObject(handle, ti); if (ret == WAIT_OBJECT_0) { list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (rh->fd == console_fd && !JS_IsNull(rh->rw_func[0])) { call_handler(ctx, rh->rw_func[0]); /* must stop because the list may have been modified */ break; } } } } else { Sleep(min_delay); } return 0; } #else #ifdef USE_WORKER static void js_free_message(JSWorkerMessage *msg); /* return 1 if a message was handled, 0 if no message */ static int handle_posted_message(JSRuntime *rt, JSContext *ctx, JSWorkerMessageHandler *port) { JSWorkerMessagePipe *ps = port->recv_pipe; int ret; struct list_head *el; JSWorkerMessage *msg; JSValue obj, data_obj, func, retval; pthread_mutex_lock(&ps->mutex); if (!list_empty(&ps->msg_queue)) { el = ps->msg_queue.next; msg = list_entry(el, JSWorkerMessage, link); /* remove the message from the queue */ list_del(&msg->link); if (list_empty(&ps->msg_queue)) { uint8_t buf[16]; int ret; for (;;) { ret = read(ps->read_fd, buf, sizeof(buf)); if (ret >= 0) { break; } if (errno != EAGAIN && errno != EINTR) { break; } } } pthread_mutex_unlock(&ps->mutex); data_obj = JS_ReadObject(ctx, msg->data, msg->data_len, JS_READ_OBJ_SAB | JS_READ_OBJ_REFERENCE); js_free_message(msg); if (JS_IsException(data_obj)) { goto fail; } obj = JS_NewObject(ctx); if (JS_IsException(obj)) { JS_FreeValue(ctx, data_obj); goto fail; } JS_DefinePropertyValueStr(ctx, obj, "data", data_obj, JS_PROP_C_W_E); /* 'func' might be destroyed when calling itself (if it frees the handler), so must take extra care */ func = JS_DupValue(ctx, port->on_message_func); retval = JS_Call(ctx, func, JS_UNDEFINED, 1, (JSValueConst *)&obj); JS_FreeValue(ctx, obj); JS_FreeValue(ctx, func); if (JS_IsException(retval)) { fail: js_std_dump_error(ctx); } else { JS_FreeValue(ctx, retval); } ret = 1; } else { pthread_mutex_unlock(&ps->mutex); ret = 0; } return ret; } #else static int handle_posted_message(JSRuntime *rt, JSContext *ctx, JSWorkerMessageHandler *port) { return 0; } #endif static int js_os_poll(JSContext *ctx) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); int ret, fd_max, min_delay; int64_t cur_time, delay; fd_set rfds, wfds; JSOSRWHandler *rh; struct list_head *el; struct timeval tv, *tvp; /* only check signals in the main thread */ if (!ts->recv_pipe && unlikely(os_pending_signals != 0)) { JSOSSignalHandler *sh; uint64_t mask; list_for_each(el, &ts->os_signal_handlers) { sh = list_entry(el, JSOSSignalHandler, link); mask = (uint64_t)1 << sh->sig_num; if (os_pending_signals & mask) { os_pending_signals &= ~mask; call_handler(ctx, sh->func); return 0; } } } if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers) && list_empty(&ts->port_list)) { return -1; /* no more events */ } if (!list_empty(&ts->os_timers)) { cur_time = get_time_ms(); min_delay = 10000; list_for_each(el, &ts->os_timers) { JSOSTimer *th = list_entry(el, JSOSTimer, link); delay = th->timeout - cur_time; if (delay <= 0) { JSValue func; /* the timer expired */ func = th->func; th->func = JS_UNDEFINED; unlink_timer(rt, th); if (!th->has_object) { free_timer(rt, th); } call_handler(ctx, func); JS_FreeValue(ctx, func); return 0; } else if (delay < min_delay) { min_delay = delay; } } tv.tv_sec = min_delay / 1000; tv.tv_usec = (min_delay % 1000) * 1000; tvp = &tv; } else { tvp = NULL; } FD_ZERO(&rfds); FD_ZERO(&wfds); fd_max = -1; list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); fd_max = max_int(fd_max, rh->fd); if (!JS_IsNull(rh->rw_func[0])) { FD_SET(rh->fd, &rfds); } if (!JS_IsNull(rh->rw_func[1])) { FD_SET(rh->fd, &wfds); } } list_for_each(el, &ts->port_list) { JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link); if (!JS_IsNull(port->on_message_func)) { JSWorkerMessagePipe *ps = port->recv_pipe; fd_max = max_int(fd_max, ps->read_fd); FD_SET(ps->read_fd, &rfds); } } ret = select(fd_max + 1, &rfds, &wfds, NULL, tvp); if (ret > 0) { list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (!JS_IsNull(rh->rw_func[0]) && FD_ISSET(rh->fd, &rfds)) { call_handler(ctx, rh->rw_func[0]); /* must stop because the list may have been modified */ goto done; } if (!JS_IsNull(rh->rw_func[1]) && FD_ISSET(rh->fd, &wfds)) { call_handler(ctx, rh->rw_func[1]); /* must stop because the list may have been modified */ goto done; } } list_for_each(el, &ts->port_list) { JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link); if (!JS_IsNull(port->on_message_func)) { JSWorkerMessagePipe *ps = port->recv_pipe; if (FD_ISSET(ps->read_fd, &rfds)) { if (handle_posted_message(rt, ctx, port)) { goto done; } } } } } done: return 0; } #endif /* !_WIN32 */ static JSValue make_obj_error(JSContext *ctx, JSValue obj, int err) { JSValue arr; if (JS_IsException(obj)) { return obj; } arr = JS_NewArray(ctx); if (JS_IsException(arr)) { return JS_EXCEPTION; } JS_DefinePropertyValueUint32(ctx, arr, 0, obj, JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, arr, 1, JS_NewInt32(ctx, err), JS_PROP_C_W_E); return arr; } static JSValue make_string_error(JSContext *ctx, const char *buf, int err) { return make_obj_error(ctx, JS_NewString(ctx, buf), err); } /* return [cwd, errorcode] */ static JSValue js_os_getcwd(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char buf[PATH_MAX]; int err; if (!getcwd(buf, sizeof(buf))) { buf[0] = '\0'; err = errno; } else { err = 0; } return make_string_error(ctx, buf, err); } static JSValue js_os_chdir(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *target; int err; target = JS_ToCString(ctx, argv[0]); if (!target) { return JS_EXCEPTION; } err = js_get_errno(chdir(target)); JS_FreeCString(ctx, target); return JS_NewInt32(ctx, err); } static JSValue js_os_mkdir(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int mode, ret; const char *path; if (argc >= 2) { if (JS_ToInt32(ctx, &mode, argv[1])) { return JS_EXCEPTION; } } else { mode = 0777; } path = JS_ToCString(ctx, argv[0]); if (!path) { return JS_EXCEPTION; } #if defined(_WIN32) (void)mode; ret = js_get_errno(mkdir(path)); #else ret = js_get_errno(mkdir(path, mode)); #endif JS_FreeCString(ctx, path); return JS_NewInt32(ctx, ret); } /* return [array, errorcode] */ static JSValue js_os_readdir(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; DIR *f; struct dirent *d; JSValue obj; int err; uint32_t len; path = JS_ToCString(ctx, argv[0]); if (!path) { return JS_EXCEPTION; } obj = JS_NewArray(ctx); if (JS_IsException(obj)) { JS_FreeCString(ctx, path); return JS_EXCEPTION; } f = opendir(path); if (!f) { err = errno; } else { err = 0; } JS_FreeCString(ctx, path); if (!f) { goto done; } len = 0; for (;;) { errno = 0; d = readdir(f); if (!d) { err = errno; break; } JS_DefinePropertyValueUint32(ctx, obj, len++, JS_NewString(ctx, d->d_name), JS_PROP_C_W_E); } closedir(f); done: return make_obj_error(ctx, obj, err); } #if !defined(_WIN32) static int64_t timespec_to_ms(const struct timespec *tv) { return (int64_t)tv->tv_sec * 1000 + (tv->tv_nsec / 1000000); } #endif /* return [obj, errcode] */ static JSValue js_os_stat(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int is_lstat) { const char *path; int err, res; struct stat st; JSValue obj; path = JS_ToCString(ctx, argv[0]); if (!path) { return JS_EXCEPTION; } #if defined(_WIN32) res = stat(path, &st); #else if (is_lstat) #if !defined(__AOS_AMP__) res = lstat(path, &st); #else res = 0; // TODO: need implement #endif else { res = stat(path, &st); } #endif JS_FreeCString(ctx, path); if (res < 0) { err = errno; obj = JS_NULL; } else { err = 0; obj = JS_NewObject(ctx); if (JS_IsException(obj)) { return JS_EXCEPTION; } JS_DefinePropertyValueStr(ctx, obj, "dev", JS_NewInt64(ctx, st.st_dev), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ino", JS_NewInt64(ctx, st.st_ino), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mode", JS_NewInt32(ctx, st.st_mode), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "nlink", JS_NewInt64(ctx, st.st_nlink), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "uid", JS_NewInt64(ctx, st.st_uid), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "gid", JS_NewInt64(ctx, st.st_gid), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "rdev", JS_NewInt64(ctx, st.st_rdev), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "size", JS_NewInt64(ctx, st.st_size), JS_PROP_C_W_E); #if !defined(_WIN32) JS_DefinePropertyValueStr(ctx, obj, "blocks", JS_NewInt64(ctx, st.st_blocks), JS_PROP_C_W_E); #endif #if defined(_WIN32) JS_DefinePropertyValueStr(ctx, obj, "atime", JS_NewInt64(ctx, (int64_t)st.st_atime * 1000), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mtime", JS_NewInt64(ctx, (int64_t)st.st_mtime * 1000), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ctime", JS_NewInt64(ctx, (int64_t)st.st_ctime * 1000), JS_PROP_C_W_E); #elif defined(__APPLE__) JS_DefinePropertyValueStr(ctx, obj, "atime", JS_NewInt64(ctx, timespec_to_ms(&st.st_atimespec)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mtime", JS_NewInt64(ctx, timespec_to_ms(&st.st_mtimespec)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ctime", JS_NewInt64(ctx, timespec_to_ms(&st.st_ctimespec)), JS_PROP_C_W_E); #elif !defined(__AOS_AMP__) JS_DefinePropertyValueStr(ctx, obj, "atime", JS_NewInt64(ctx, timespec_to_ms(&st.st_atim)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mtime", JS_NewInt64(ctx, timespec_to_ms(&st.st_mtim)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ctime", JS_NewInt64(ctx, timespec_to_ms(&st.st_ctim)), JS_PROP_C_W_E); #endif } return make_obj_error(ctx, obj, err); } #if !defined(_WIN32) static void ms_to_timeval(struct timeval *tv, uint64_t v) { tv->tv_sec = v / 1000; tv->tv_usec = (v % 1000) * 1000; } #endif static JSValue js_os_utimes(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; int64_t atime, mtime; int ret; if (JS_ToInt64(ctx, &atime, argv[1])) { return JS_EXCEPTION; } if (JS_ToInt64(ctx, &mtime, argv[2])) { return JS_EXCEPTION; } path = JS_ToCString(ctx, argv[0]); if (!path) { return JS_EXCEPTION; } #if defined(_WIN32) { struct _utimbuf times; times.actime = atime / 1000; times.modtime = mtime / 1000; ret = js_get_errno(_utime(path, &times)); } #else #if !defined(__AOS_AMP__) { struct timeval times[2]; ms_to_timeval(&times[0], atime); ms_to_timeval(&times[1], mtime); ret = js_get_errno(utimes(path, times)); } #else ret = 0; // TODO: need implement #endif #endif JS_FreeCString(ctx, path); return JS_NewInt32(ctx, ret); } #if !defined(_WIN32) /* return [path, errorcode] */ static JSValue js_os_realpath(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; char buf[PATH_MAX], *res; int err; path = JS_ToCString(ctx, argv[0]); if (!path) { return JS_EXCEPTION; } res = realpath(path, buf); JS_FreeCString(ctx, path); if (!res) { buf[0] = '\0'; err = errno; } else { err = 0; } return make_string_error(ctx, buf, err); } static JSValue js_os_symlink(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *target, *linkpath; int err; target = JS_ToCString(ctx, argv[0]); if (!target) { return JS_EXCEPTION; } linkpath = JS_ToCString(ctx, argv[1]); if (!linkpath) { JS_FreeCString(ctx, target); return JS_EXCEPTION; } err = js_get_errno(symlink(target, linkpath)); JS_FreeCString(ctx, target); JS_FreeCString(ctx, linkpath); return JS_NewInt32(ctx, err); } /* return [path, errorcode] */ static JSValue js_os_readlink(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; char buf[PATH_MAX]; int err; ssize_t res; path = JS_ToCString(ctx, argv[0]); if (!path) { return JS_EXCEPTION; } res = readlink(path, buf, sizeof(buf) - 1); if (res < 0) { buf[0] = '\0'; err = errno; } else { buf[res] = '\0'; err = 0; } JS_FreeCString(ctx, path); return make_string_error(ctx, buf, err); } static char **build_envp(JSContext *ctx, JSValueConst obj) { uint32_t len, i; JSPropertyEnum *tab; char **envp, *pair; const char *key, *str; JSValue val; size_t key_len, str_len; if (JS_GetOwnPropertyNames(ctx, &tab, &len, obj, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) < 0) { return NULL; } envp = js_mallocz(ctx, sizeof(envp[0]) * ((size_t)len + 1)); if (!envp) { goto fail; } for (i = 0; i < len; i++) { val = JS_GetProperty(ctx, obj, tab[i].atom); if (JS_IsException(val)) { goto fail; } str = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!str) { goto fail; } key = JS_AtomToCString(ctx, tab[i].atom); if (!key) { JS_FreeCString(ctx, str); goto fail; } key_len = strlen(key); str_len = strlen(str); pair = js_malloc(ctx, key_len + str_len + 2); if (!pair) { JS_FreeCString(ctx, key); JS_FreeCString(ctx, str); goto fail; } memcpy(pair, key, key_len); pair[key_len] = '='; memcpy(pair + key_len + 1, str, str_len); pair[key_len + 1 + str_len] = '\0'; envp[i] = pair; JS_FreeCString(ctx, key); JS_FreeCString(ctx, str); } done: for (i = 0; i < len; i++) { JS_FreeAtom(ctx, tab[i].atom); } js_free(ctx, tab); return envp; fail: if (envp) { for (i = 0; i < len; i++) { js_free(ctx, envp[i]); } js_free(ctx, envp); envp = NULL; } goto done; } /* execvpe is not available on non GNU systems */ static int my_execvpe(const char *filename, char **argv, char **envp) { char *path, *p, *p_next, *p1; char buf[PATH_MAX]; size_t filename_len, path_len; BOOL eacces_error; filename_len = strlen(filename); if (filename_len == 0) { errno = ENOENT; return -1; } if (strchr(filename, '/')) { return execve(filename, argv, envp); } path = getenv("PATH"); if (!path) { path = (char *)"/bin:/usr/bin"; } eacces_error = FALSE; p = path; for (p = path; p != NULL; p = p_next) { p1 = strchr(p, ':'); if (!p1) { p_next = NULL; path_len = strlen(p); } else { p_next = p1 + 1; path_len = p1 - p; } /* path too long */ if ((path_len + 1 + filename_len + 1) > PATH_MAX) { continue; } memcpy(buf, p, path_len); buf[path_len] = '/'; memcpy(buf + path_len + 1, filename, filename_len); buf[path_len + 1 + filename_len] = '\0'; execve(buf, argv, envp); switch (errno) { case EACCES: eacces_error = TRUE; break; case ENOENT: case ENOTDIR: break; default: return -1; } } if (eacces_error) { errno = EACCES; } return -1; } #if !defined(__AOS_AMP__) /* exec(args[, options]) -> exitcode */ static JSValue js_os_exec(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSValueConst options, args = argv[0]; JSValue val, ret_val; const char **exec_argv, *file = NULL, *str, *cwd = NULL; char **envp = environ; uint32_t exec_argc, i; int ret, pid, status; BOOL block_flag = TRUE, use_path = TRUE; static const char *std_name[3] = { "stdin", "stdout", "stderr" }; int std_fds[3]; uint32_t uid = -1, gid = -1; val = JS_GetPropertyStr(ctx, args, "length"); if (JS_IsException(val)) { return JS_EXCEPTION; } ret = JS_ToUint32(ctx, &exec_argc, val); JS_FreeValue(ctx, val); if (ret) { return JS_EXCEPTION; } /* arbitrary limit to avoid overflow */ if (exec_argc < 1 || exec_argc > 65535) { return JS_ThrowTypeError(ctx, "invalid number of arguments"); } exec_argv = js_mallocz(ctx, sizeof(exec_argv[0]) * (exec_argc + 1)); if (!exec_argv) { return JS_EXCEPTION; } for (i = 0; i < exec_argc; i++) { val = JS_GetPropertyUint32(ctx, args, i); if (JS_IsException(val)) { goto exception; } str = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!str) { goto exception; } exec_argv[i] = str; } exec_argv[exec_argc] = NULL; for (i = 0; i < 3; i++) { std_fds[i] = i; } /* get the options, if any */ if (argc >= 2) { options = argv[1]; if (get_bool_option(ctx, &block_flag, options, "block")) { goto exception; } if (get_bool_option(ctx, &use_path, options, "usePath")) { goto exception; } val = JS_GetPropertyStr(ctx, options, "file"); if (JS_IsException(val)) { goto exception; } if (!JS_IsUndefined(val)) { file = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!file) { goto exception; } } val = JS_GetPropertyStr(ctx, options, "cwd"); if (JS_IsException(val)) { goto exception; } if (!JS_IsUndefined(val)) { cwd = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!cwd) { goto exception; } } /* stdin/stdout/stderr handles */ for (i = 0; i < 3; i++) { val = JS_GetPropertyStr(ctx, options, std_name[i]); if (JS_IsException(val)) { goto exception; } if (!JS_IsUndefined(val)) { int fd; ret = JS_ToInt32(ctx, &fd, val); JS_FreeValue(ctx, val); if (ret) { goto exception; } std_fds[i] = fd; } } val = JS_GetPropertyStr(ctx, options, "env"); if (JS_IsException(val)) { goto exception; } if (!JS_IsUndefined(val)) { envp = build_envp(ctx, val); JS_FreeValue(ctx, val); if (!envp) { goto exception; } } val = JS_GetPropertyStr(ctx, options, "uid"); if (JS_IsException(val)) { goto exception; } if (!JS_IsUndefined(val)) { ret = JS_ToUint32(ctx, &uid, val); JS_FreeValue(ctx, val); if (ret) { goto exception; } } val = JS_GetPropertyStr(ctx, options, "gid"); if (JS_IsException(val)) { goto exception; } if (!JS_IsUndefined(val)) { ret = JS_ToUint32(ctx, &gid, val); JS_FreeValue(ctx, val); if (ret) { goto exception; } } } pid = fork(); if (pid < 0) { JS_ThrowTypeError(ctx, "fork error"); goto exception; } if (pid == 0) { /* child */ int fd_max = sysconf(_SC_OPEN_MAX); /* remap the stdin/stdout/stderr handles if necessary */ for (i = 0; i < 3; i++) { if (std_fds[i] != i) { if (dup2(std_fds[i], i) < 0) { _exit(127); } } } for (i = 3; i < fd_max; i++) { close(i); } if (cwd) { if (chdir(cwd) < 0) { _exit(127); } } if (uid != -1) { if (setuid(uid) < 0) { _exit(127); } } if (gid != -1) { if (setgid(gid) < 0) { _exit(127); } } if (!file) { file = exec_argv[0]; } if (use_path) { ret = my_execvpe(file, (char **)exec_argv, envp); } else { ret = execve(file, (char **)exec_argv, envp); } _exit(127); } /* parent */ if (block_flag) { for (;;) { ret = waitpid(pid, &status, 0); if (ret == pid) { if (WIFEXITED(status)) { ret = WEXITSTATUS(status); break; } else if (WIFSIGNALED(status)) { ret = -WTERMSIG(status); break; } } } } else { ret = pid; } ret_val = JS_NewInt32(ctx, ret); done: JS_FreeCString(ctx, file); JS_FreeCString(ctx, cwd); for (i = 0; i < exec_argc; i++) { JS_FreeCString(ctx, exec_argv[i]); } js_free(ctx, exec_argv); if (envp != environ) { char **p; p = envp; while (*p != NULL) { js_free(ctx, *p); p++; } js_free(ctx, envp); } return ret_val; exception: ret_val = JS_EXCEPTION; goto done; } /* waitpid(pid, block) -> [pid, status] */ static JSValue js_os_waitpid(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int pid, status, options, ret; JSValue obj; if (JS_ToInt32(ctx, &pid, argv[0])) { return JS_EXCEPTION; } if (JS_ToInt32(ctx, &options, argv[1])) { return JS_EXCEPTION; } ret = waitpid(pid, &status, options); if (ret < 0) { ret = -errno; status = 0; } obj = JS_NewArray(ctx); if (JS_IsException(obj)) { return obj; } JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ret), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, status), JS_PROP_C_W_E); return obj; } /* pipe() -> [read_fd, write_fd] or null if error */ static JSValue js_os_pipe(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int pipe_fds[2], ret; JSValue obj; ret = pipe(pipe_fds); if (ret < 0) { return JS_NULL; } obj = JS_NewArray(ctx); if (JS_IsException(obj)) { return obj; } JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, pipe_fds[0]), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, pipe_fds[1]), JS_PROP_C_W_E); return obj; } /* kill(pid, sig) */ static JSValue js_os_kill(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int pid, sig, ret; if (JS_ToInt32(ctx, &pid, argv[0])) { return JS_EXCEPTION; } if (JS_ToInt32(ctx, &sig, argv[1])) { return JS_EXCEPTION; } ret = js_get_errno(kill(pid, sig)); return JS_NewInt32(ctx, ret); } #endif /* sleep(delay_ms) */ static JSValue js_os_sleep(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { #if !defined(__AOS_AMP__) int64_t delay; struct timespec ts; int ret; if (JS_ToInt64(ctx, &delay, argv[0])) { return JS_EXCEPTION; } ts.tv_sec = delay / 1000; ts.tv_nsec = (delay % 1000) * 1000000; ret = js_get_errno(nanosleep(&ts, NULL)); #else int64_t delay; int ret = 0; if (JS_ToInt64(ctx, &delay, argv[0])) { return JS_EXCEPTION; } aos_msleep((unsigned int)delay); #endif return JS_NewInt32(ctx, ret); } /* dup(fd) */ static JSValue js_os_dup(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { #if !defined(__AOS_AMP__) int fd, ret; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } ret = js_get_errno(dup(fd)); return JS_NewInt32(ctx, ret); #endif } /* dup2(fd) */ static JSValue js_os_dup2(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { #if !defined(__AOS_AMP__) int fd, fd2, ret; if (JS_ToInt32(ctx, &fd, argv[0])) { return JS_EXCEPTION; } if (JS_ToInt32(ctx, &fd2, argv[1])) { return JS_EXCEPTION; } ret = js_get_errno(dup2(fd, fd2)); return JS_NewInt32(ctx, ret); #endif } #endif /* !_WIN32 */ #ifdef USE_WORKER /* Worker */ typedef struct { JSWorkerMessagePipe *recv_pipe; JSWorkerMessagePipe *send_pipe; JSWorkerMessageHandler *msg_handler; } JSWorkerData; typedef struct { /* source code of the worker */ char *eval_buf; size_t eval_buf_len; JSWorkerMessagePipe *recv_pipe, *send_pipe; } WorkerFuncArgs; typedef struct { int ref_count; uint64_t buf[0]; } JSSABHeader; static JSClassID js_worker_class_id; static int atomic_add_int(int *ptr, int v) { return atomic_fetch_add((_Atomic(uint32_t) *)ptr, v) + v; } /* shared array buffer allocator */ static void *js_sab_alloc(void *opaque, size_t size) { JSSABHeader *sab; sab = malloc(sizeof(JSSABHeader) + size); if (!sab) { return NULL; } sab->ref_count = 1; return sab->buf; } static void js_sab_free(void *opaque, void *ptr) { JSSABHeader *sab; int ref_count; sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader)); ref_count = atomic_add_int(&sab->ref_count, -1); assert(ref_count >= 0); if (ref_count == 0) { free(sab); } } static void js_sab_dup(void *opaque, void *ptr) { JSSABHeader *sab; sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader)); atomic_add_int(&sab->ref_count, 1); } static JSWorkerMessagePipe *js_new_message_pipe(void) { #if !defined(__AOS_AMP__) JSWorkerMessagePipe *ps; int pipe_fds[2]; if (pipe(pipe_fds) < 0) { return NULL; } ps = malloc(sizeof(*ps)); if (!ps) { close(pipe_fds[0]); close(pipe_fds[1]); return NULL; } ps->ref_count = 1; init_list_head(&ps->msg_queue); pthread_mutex_init(&ps->mutex, NULL); ps->read_fd = pipe_fds[0]; ps->write_fd = pipe_fds[1]; return ps; #endif } static JSWorkerMessagePipe *js_dup_message_pipe(JSWorkerMessagePipe *ps) { atomic_add_int(&ps->ref_count, 1); return ps; } static void js_free_message(JSWorkerMessage *msg) { size_t i; /* free the SAB */ for (i = 0; i < msg->sab_tab_len; i++) { js_sab_free(NULL, msg->sab_tab[i]); } free(msg->sab_tab); free(msg->data); free(msg); } static void js_free_message_pipe(JSWorkerMessagePipe *ps) { struct list_head *el, *el1; JSWorkerMessage *msg; int ref_count; if (!ps) { return; } ref_count = atomic_add_int(&ps->ref_count, -1); assert(ref_count >= 0); if (ref_count == 0) { list_for_each_safe(el, el1, &ps->msg_queue) { msg = list_entry(el, JSWorkerMessage, link); js_free_message(msg); } pthread_mutex_destroy(&ps->mutex); close(ps->read_fd); close(ps->write_fd); free(ps); } } static void js_free_port(JSRuntime *rt, JSWorkerMessageHandler *port) { if (port) { js_free_message_pipe(port->recv_pipe); JS_FreeValueRT(rt, port->on_message_func); list_del(&port->link); js_free_rt(rt, port); } } static void js_worker_finalizer(JSRuntime *rt, JSValue val) { JSWorkerData *worker = JS_GetOpaque(val, js_worker_class_id); if (worker) { js_free_message_pipe(worker->recv_pipe); js_free_message_pipe(worker->send_pipe); js_free_port(rt, worker->msg_handler); js_free_rt(rt, worker); } } static JSClassDef js_worker_class = { "Worker", .finalizer = js_worker_finalizer, }; static void *worker_func(void *opaque) { WorkerFuncArgs *args = opaque; JSRuntime *rt; JSThreadState *ts; JSContext *ctx; JSValue retval; rt = JS_NewRuntime(); if (rt == NULL) { fprintf(stderr, "JS_NewRuntime failure"); exit(1); } js_std_init_handlers(rt); /* set the pipe to communicate with the parent */ ts = JS_GetRuntimeOpaque(rt); ts->recv_pipe = args->recv_pipe; ts->send_pipe = args->send_pipe; ctx = JS_NewContext(rt); if (ctx == NULL) { fprintf(stderr, "JS_NewContext failure"); } JS_SetCanBlock(rt, TRUE); js_std_add_helpers(ctx, -1, NULL); /* system modules */ js_init_module_std(ctx, "std"); js_init_module_os(ctx, "os"); retval = JS_Eval(ctx, args->eval_buf, args->eval_buf_len, "<worker>", JS_EVAL_TYPE_MODULE); free(args->eval_buf); free(args); if (JS_IsException(retval)) { js_std_dump_error(ctx); } JS_FreeValue(ctx, retval); js_std_loop(ctx); JS_FreeContext(ctx); js_std_free_handlers(rt); JS_FreeRuntime(rt); return NULL; } static JSValue js_worker_ctor_internal(JSContext *ctx, JSValueConst new_target, JSWorkerMessagePipe *recv_pipe, JSWorkerMessagePipe *send_pipe) { JSValue obj = JS_UNDEFINED, proto; JSWorkerData *s; /* create the object */ if (JS_IsUndefined(new_target)) { proto = JS_GetClassProto(ctx, js_worker_class_id); } else { proto = JS_GetPropertyStr(ctx, new_target, "prototype"); if (JS_IsException(proto)) { goto fail; } } obj = JS_NewObjectProtoClass(ctx, proto, js_worker_class_id); JS_FreeValue(ctx, proto); if (JS_IsException(obj)) { goto fail; } s = js_mallocz(ctx, sizeof(*s)); if (!s) { goto fail; } s->recv_pipe = js_dup_message_pipe(recv_pipe); s->send_pipe = js_dup_message_pipe(send_pipe); JS_SetOpaque(obj, s); return obj; fail: JS_FreeValue(ctx, obj); return JS_EXCEPTION; } static JSValue js_worker_ctor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); WorkerFuncArgs *args; const char *str; size_t str_len; pthread_t tid; pthread_attr_t attr; JSValue obj = JS_UNDEFINED; int ret; /* XXX: in order to avoid problems with resource liberation, we don't support creating workers inside workers */ if (!is_main_thread(rt)) { return JS_ThrowTypeError(ctx, "cannot create a worker inside a worker"); } /* script source */ str = JS_ToCStringLen(ctx, &str_len, argv[0]); if (!str) { return JS_EXCEPTION; } args = malloc(sizeof(*args)); if (!args) { JS_ThrowOutOfMemory(ctx); goto fail; } memset(args, 0, sizeof(*args)); args->eval_buf = malloc(str_len + 1); if (!args->eval_buf) { JS_ThrowOutOfMemory(ctx); goto fail; } memcpy(args->eval_buf, str, str_len + 1); args->eval_buf_len = str_len; JS_FreeCString(ctx, str); str = NULL; /* ports */ args->recv_pipe = js_new_message_pipe(); if (!args->recv_pipe) { goto fail; } args->send_pipe = js_new_message_pipe(); if (!args->send_pipe) { goto fail; } obj = js_worker_ctor_internal(ctx, new_target, args->send_pipe, args->recv_pipe); if (JS_IsUndefined(obj)) { goto fail; } pthread_attr_init(&attr); /* no join at the end */ pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); ret = pthread_create(&tid, &attr, worker_func, args); pthread_attr_destroy(&attr); if (ret != 0) { JS_ThrowTypeError(ctx, "could not create worker"); goto fail; } return obj; fail: JS_FreeCString(ctx, str); if (args) { free(args->eval_buf); js_free_message_pipe(args->recv_pipe); js_free_message_pipe(args->send_pipe); free(args); } JS_FreeValue(ctx, obj); return JS_EXCEPTION; } static JSValue js_worker_postMessage(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id); JSWorkerMessagePipe *ps; size_t data_len, sab_tab_len, i; uint8_t *data; JSWorkerMessage *msg; uint8_t **sab_tab; if (!worker) { return JS_EXCEPTION; } data = JS_WriteObject2(ctx, &data_len, argv[0], JS_WRITE_OBJ_SAB | JS_WRITE_OBJ_REFERENCE, &sab_tab, &sab_tab_len); if (!data) { return JS_EXCEPTION; } msg = malloc(sizeof(*msg)); if (!msg) { goto fail; } msg->data = NULL; msg->sab_tab = NULL; /* must reallocate because the allocator may be different */ msg->data = malloc(data_len); if (!msg->data) { goto fail; } memcpy(msg->data, data, data_len); msg->data_len = data_len; msg->sab_tab = malloc(sizeof(msg->sab_tab[0]) * sab_tab_len); if (!msg->sab_tab) { goto fail; } memcpy(msg->sab_tab, sab_tab, sizeof(msg->sab_tab[0]) * sab_tab_len); msg->sab_tab_len = sab_tab_len; js_free(ctx, data); js_free(ctx, sab_tab); /* increment the SAB reference counts */ for (i = 0; i < msg->sab_tab_len; i++) { js_sab_dup(NULL, msg->sab_tab[i]); } ps = worker->send_pipe; pthread_mutex_lock(&ps->mutex); /* indicate that data is present */ if (list_empty(&ps->msg_queue)) { uint8_t ch = '\0'; int ret; for (;;) { ret = write(ps->write_fd, &ch, 1); if (ret == 1) { break; } if (ret < 0 && (errno != EAGAIN || errno != EINTR)) { break; } } } list_add_tail(&msg->link, &ps->msg_queue); pthread_mutex_unlock(&ps->mutex); return JS_UNDEFINED; fail: if (msg) { free(msg->data); free(msg->sab_tab); free(msg); } js_free(ctx, data); js_free(ctx, sab_tab); return JS_EXCEPTION; } static JSValue js_worker_set_onmessage(JSContext *ctx, JSValueConst this_val, JSValueConst func) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id); JSWorkerMessageHandler *port; if (!worker) { return JS_EXCEPTION; } port = worker->msg_handler; if (JS_IsNull(func)) { if (port) { js_free_port(rt, port); worker->msg_handler = NULL; } } else { if (!JS_IsFunction(ctx, func)) { return JS_ThrowTypeError(ctx, "not a function"); } if (!port) { port = js_mallocz(ctx, sizeof(*port)); if (!port) { return JS_EXCEPTION; } port->recv_pipe = js_dup_message_pipe(worker->recv_pipe); port->on_message_func = JS_NULL; list_add_tail(&port->link, &ts->port_list); worker->msg_handler = port; } JS_FreeValue(ctx, port->on_message_func); port->on_message_func = JS_DupValue(ctx, func); } return JS_UNDEFINED; } static JSValue js_worker_get_onmessage(JSContext *ctx, JSValueConst this_val) { JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id); JSWorkerMessageHandler *port; if (!worker) { return JS_EXCEPTION; } port = worker->msg_handler; if (port) { return JS_DupValue(ctx, port->on_message_func); } else { return JS_NULL; } } static const JSCFunctionListEntry js_worker_proto_funcs[] = { JS_CFUNC_DEF("postMessage", 1, js_worker_postMessage), JS_CGETSET_DEF("onmessage", js_worker_get_onmessage, js_worker_set_onmessage), }; #endif /* USE_WORKER */ #define OS_PLATFORM "aos_amp" #define OS_FLAG(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE ) static const JSCFunctionListEntry js_os_funcs[] = { JS_CFUNC_DEF("open", 2, js_os_open), OS_FLAG(O_RDONLY), OS_FLAG(O_WRONLY), OS_FLAG(O_RDWR), OS_FLAG(O_APPEND), OS_FLAG(O_CREAT), OS_FLAG(O_EXCL), OS_FLAG(O_TRUNC), #if defined(_WIN32) OS_FLAG(O_BINARY), OS_FLAG(O_TEXT), #endif JS_CFUNC_DEF("close", 1, js_os_close), JS_CFUNC_DEF("seek", 3, js_os_seek), JS_CFUNC_MAGIC_DEF("read", 4, js_os_read_write, 0), JS_CFUNC_MAGIC_DEF("write", 4, js_os_read_write, 1), JS_CFUNC_DEF("isatty", 1, js_os_isatty), JS_CFUNC_DEF("ttyGetWinSize", 1, js_os_ttyGetWinSize), JS_CFUNC_DEF("ttySetRaw", 1, js_os_ttySetRaw), JS_CFUNC_DEF("remove", 1, js_os_remove), JS_CFUNC_DEF("rename", 2, js_os_rename), JS_CFUNC_MAGIC_DEF("setReadHandler", 2, js_os_setReadHandler, 0), JS_CFUNC_MAGIC_DEF("setWriteHandler", 2, js_os_setReadHandler, 1), #if !defined(__AOS_AMP__) JS_CFUNC_DEF("signal", 2, js_os_signal), OS_FLAG(SIGINT), OS_FLAG(SIGABRT), OS_FLAG(SIGFPE), OS_FLAG(SIGILL), OS_FLAG(SIGSEGV), OS_FLAG(SIGTERM), #endif #if !defined(_WIN32) && !defined(__AOS_AMP__) OS_FLAG(SIGQUIT), OS_FLAG(SIGPIPE), OS_FLAG(SIGALRM), OS_FLAG(SIGUSR1), OS_FLAG(SIGUSR2), #if !defined(__AOS_AMP__) OS_FLAG(SIGCHLD), OS_FLAG(SIGCONT), #endif /* __AOS_AMP__ */ #if !defined(__AOS_AMP__) OS_FLAG(SIGSTOP), OS_FLAG(SIGTSTP), #endif #if !defined(__AOS_AMP__) OS_FLAG(SIGTTIN), OS_FLAG(SIGTTOU), #endif /* __AOS_AMP__ */ #endif JS_CFUNC_DEF("setTimeout", 2, js_os_setTimeout), JS_CFUNC_DEF("clearTimeout", 1, js_os_clearTimeout), JS_PROP_STRING_DEF("platform", OS_PLATFORM, 0), JS_CFUNC_DEF("getcwd", 0, js_os_getcwd), JS_CFUNC_DEF("chdir", 0, js_os_chdir), JS_CFUNC_DEF("mkdir", 1, js_os_mkdir), JS_CFUNC_DEF("readdir", 1, js_os_readdir), /* st_mode constants */ OS_FLAG(S_IFMT), OS_FLAG(S_IFIFO), OS_FLAG(S_IFCHR), OS_FLAG(S_IFDIR), OS_FLAG(S_IFBLK), OS_FLAG(S_IFREG), #if !defined(_WIN32) OS_FLAG(S_IFSOCK), OS_FLAG(S_IFLNK), OS_FLAG(S_ISGID), OS_FLAG(S_ISUID), #endif JS_CFUNC_MAGIC_DEF("stat", 1, js_os_stat, 0), JS_CFUNC_DEF("utimes", 3, js_os_utimes), #if !defined(_WIN32) #if !defined(__AOS_AMP__) JS_CFUNC_MAGIC_DEF("lstat", 1, js_os_stat, 1), JS_CFUNC_DEF("realpath", 1, js_os_realpath), JS_CFUNC_DEF("symlink", 2, js_os_symlink), JS_CFUNC_DEF("readlink", 1, js_os_readlink), JS_CFUNC_DEF("exec", 1, js_os_exec), JS_CFUNC_DEF("waitpid", 2, js_os_waitpid), OS_FLAG(WNOHANG), JS_CFUNC_DEF("pipe", 0, js_os_pipe), JS_CFUNC_DEF("kill", 2, js_os_kill), JS_CFUNC_DEF("sleep", 1, js_os_sleep), JS_CFUNC_DEF("dup", 1, js_os_dup), JS_CFUNC_DEF("dup2", 2, js_os_dup2), #endif #endif }; static int js_os_init(JSContext *ctx, JSModuleDef *m) { os_poll_func = js_os_poll; /* OSTimer class */ JS_NewClassID(&js_os_timer_class_id); JS_NewClass(JS_GetRuntime(ctx), js_os_timer_class_id, &js_os_timer_class); #ifdef USE_WORKER { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); JSValue proto, obj; /* Worker class */ JS_NewClassID(&js_worker_class_id); JS_NewClass(JS_GetRuntime(ctx), js_worker_class_id, &js_worker_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_worker_proto_funcs, countof(js_worker_proto_funcs)); obj = JS_NewCFunction2(ctx, js_worker_ctor, "Worker", 1, JS_CFUNC_constructor, 0); JS_SetConstructor(ctx, obj, proto); JS_SetClassProto(ctx, js_worker_class_id, proto); /* set 'Worker.parent' if necessary */ if (ts->recv_pipe && ts->send_pipe) { JS_DefinePropertyValueStr(ctx, obj, "parent", js_worker_ctor_internal(ctx, JS_UNDEFINED, ts->recv_pipe, ts->send_pipe), JS_PROP_C_W_E); } JS_SetModuleExport(ctx, m, "Worker", obj); } #endif /* USE_WORKER */ return JS_SetModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs)); } JSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_os_init); if (!m) { return NULL; } JS_AddModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs)); #ifdef USE_WORKER JS_AddModuleExport(ctx, m, "Worker"); #endif return m; } /**********************************************************/ static JSValue js_print(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int i, j; const char *str; size_t len; for (i = 0; i < argc; i++) { if (i != 0) { aos_putchar(' '); } str = JS_ToCStringLen(ctx, &len, argv[i]); if (!str) { return JS_EXCEPTION; } for (j = 0; j < len; j++) { aos_putchar(str[j]); } JS_FreeCString(ctx, str); } aos_putchar('\n'); return JS_UNDEFINED; } void js_std_add_helpers(JSContext *ctx, int argc, char **argv) { JSValue global_obj, console, args; int i; /* XXX: should these global definitions be enumerable? */ global_obj = JS_GetGlobalObject(ctx); console = JS_NewObject(ctx); JS_SetPropertyStr(ctx, console, "log", JS_NewCFunction(ctx, js_print, "log", 1)); JS_SetPropertyStr(ctx, global_obj, "console", console); /* same methods as the mozilla JS shell */ if (argc >= 0) { args = JS_NewArray(ctx); for (i = 0; i < argc; i++) { JS_SetPropertyUint32(ctx, args, i, JS_NewString(ctx, argv[i])); } JS_SetPropertyStr(ctx, global_obj, "scriptArgs", args); } JS_SetPropertyStr(ctx, global_obj, "print", JS_NewCFunction(ctx, js_print, "print", 1)); JS_SetPropertyStr(ctx, global_obj, "__loadScript", JS_NewCFunction(ctx, js_loadScript, "__loadScript", 1)); JS_FreeValue(ctx, global_obj); } void js_std_init_handlers(JSRuntime *rt) { JSThreadState *ts; ts = malloc(sizeof(*ts)); if (!ts) { fprintf(stderr, "Could not allocate memory for the worker"); exit(1); } memset(ts, 0, sizeof(*ts)); init_list_head(&ts->os_rw_handlers); init_list_head(&ts->os_signal_handlers); init_list_head(&ts->os_timers); init_list_head(&ts->port_list); JS_SetRuntimeOpaque(rt, ts); #ifdef USE_WORKER /* set the SharedArrayBuffer memory handlers */ { JSSharedArrayBufferFunctions sf; memset(&sf, 0, sizeof(sf)); sf.sab_alloc = js_sab_alloc; sf.sab_free = js_sab_free; sf.sab_dup = js_sab_dup; JS_SetSharedArrayBufferFunctions(rt, &sf); } #endif } void js_std_free_handlers(JSRuntime *rt) { JSThreadState *ts = JS_GetRuntimeOpaque(rt); struct list_head *el, *el1; list_for_each_safe(el, el1, &ts->os_rw_handlers) { JSOSRWHandler *rh = list_entry(el, JSOSRWHandler, link); free_rw_handler(rt, rh); } list_for_each_safe(el, el1, &ts->os_signal_handlers) { JSOSSignalHandler *sh = list_entry(el, JSOSSignalHandler, link); free_sh(rt, sh); } list_for_each_safe(el, el1, &ts->os_timers) { JSOSTimer *th = list_entry(el, JSOSTimer, link); unlink_timer(rt, th); if (!th->has_object) { free_timer(rt, th); } } free(ts); JS_SetRuntimeOpaque(rt, NULL); /* fail safe */ } static void js_dump_obj(JSContext *ctx, FILE *f, JSValueConst val) { const char *str; str = JS_ToCString(ctx, val); if (str) { if (f != stderr) { fprintf(f, "%s\n", str); } else { printf("%s\n", str); } JS_FreeCString(ctx, str); } else { if (f != stderr) { fprintf(f, "[exception]\n"); } else { printf("[exception]\n"); } } } static void js_std_dump_error1(JSContext *ctx, JSValueConst exception_val) { JSValue val; BOOL is_error; is_error = JS_IsError(ctx, exception_val); js_dump_obj(ctx, stderr, exception_val); if (is_error) { val = JS_GetPropertyStr(ctx, exception_val, "stack"); if (!JS_IsUndefined(val)) { js_dump_obj(ctx, stderr, val); } JS_FreeValue(ctx, val); } } void js_std_dump_error(JSContext *ctx) { JSValue exception_val; exception_val = JS_GetException(ctx); js_std_dump_error1(ctx, exception_val); JS_FreeValue(ctx, exception_val); } void js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise, JSValueConst reason, BOOL is_handled, void *opaque) { if (!is_handled) { fprintf(stderr, "Possibly unhandled promise rejection: "); js_std_dump_error1(ctx, reason); } } /* main loop which calls the user JS callbacks */ void js_std_loop(JSContext *ctx) { JSContext *ctx1; int err; for (;;) { /* execute the pending jobs */ for (;;) { err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1); if (err <= 0) { if (err < 0) { js_std_dump_error(ctx1); } break; } } if (!os_poll_func || os_poll_func(ctx)) { break; } } } /* main loop which calls the user JS callbacks */ void js_std_loop_once(JSContext *ctx) { JSContext *ctx1; int err; /* execute the pending jobs */ for (;;) { err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1); if (err <= 0) { if (err < 0) { js_std_dump_error(ctx1); } break; } } if (!os_poll_func || os_poll_func(ctx)) { return; } } void js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len, int load_only) { JSValue obj, val; obj = JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE); if (JS_IsException(obj)) { goto exception; } if (load_only) { if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) { js_module_set_import_meta(ctx, obj, FALSE, FALSE); } } else { if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) { if (JS_ResolveModule(ctx, obj) < 0) { JS_FreeValue(ctx, obj); goto exception; } js_module_set_import_meta(ctx, obj, FALSE, TRUE); } val = JS_EvalFunction(ctx, obj); if (JS_IsException(val)) { exception: js_std_dump_error(ctx); return; } JS_FreeValue(ctx, val); } return; } JSValue js_load_binary_module(JSContext *ctx, const uint8_t *buf, size_t buf_len) { JSValue obj, val; obj = JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE); if (JS_IsException(obj)) { js_std_dump_error(ctx); aos_printf("js_load_binary_module Error %d\n", __LINE__); return JS_UNDEFINED; } if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) { if (JS_ResolveModule(ctx, obj) < 0) { JS_FreeValue(ctx, obj); js_std_dump_error(ctx); aos_printf("js_load_binary_module Error %d\n", __LINE__); return JS_UNDEFINED; } js_module_set_import_meta(ctx, obj, FALSE, FALSE); } return obj; } JSValue js_eval_binary_module(JSContext *ctx, const uint8_t *buf, size_t buf_len) { JSValue obj = JS_UNDEFINED, val = JS_UNDEFINED; obj = JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE); printf("run %s %d\n", __FUNCTION__, __LINE__); if (JS_IsException(obj)) { qjs_std_dump_error(ctx); return obj; } printf("run %s %d\n", __FUNCTION__, __LINE__); if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) { if (JS_ResolveModule(ctx, obj) < 0) { JS_FreeValue(ctx, obj); qjs_std_dump_error(ctx); return obj; } js_module_set_import_meta(ctx, obj, FALSE, FALSE); } printf("run %s %d\n", __FUNCTION__, __LINE__); val = JS_EvalFunction(ctx, obj); return val; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/libc/quickjs_libc.c
C
apache-2.0
116,514
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "aos_system.h" #include "amp_defines.h" #include "aos_network.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "CELLULAR" typedef struct { int status; JSValue js_cb_ref; } network_status_notify_param_t; static JSValue g_js_cb_ref; static JSClassID js_cellular_class_id; /************************************************************************************* * Function: native_cellular_get_simInfo * Description: js native addon for * UDP.close(sock_id) * Called by: js api * Input: sock_id: interger * * Output: return 0 when UDP.close call ok * return error number UDP.close call fail **************************************************************************************/ static JSValue native_cellular_get_simInfo(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; aos_sim_info_t sim_info; JSValue obj = JS_NewObject(ctx); memset(&sim_info, 0, sizeof(sim_info)); ret = aos_get_sim_info(&sim_info); if (ret != 0) { amp_debug(MOD_STR, "get sim card info failed"); goto out; } JS_SetPropertyStr(ctx, obj, "imsi", JS_NewString(ctx, sim_info.imsi)); JS_SetPropertyStr(ctx, obj, "imei", JS_NewString(ctx, sim_info.imei)); JS_SetPropertyStr(ctx, obj, "iccid", JS_NewString(ctx, sim_info.iccid)); out: return obj; } /************************************************************************************* * Function: native_aiot_close * Description: js native addon for * UDP.close(sock_id) * Called by: js api * Input: sock_id: interger * * Output: return 0 when UDP.close call ok * return error number UDP.close call fail **************************************************************************************/ static JSValue native_cellular_get_locatorInfo(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; aos_locator_info_t locator_info; JSValue obj = JS_NewObject(ctx); memset(&locator_info, 0, sizeof(locator_info)); ret = aos_get_locator_info(&locator_info); if (ret != 0) { amp_debug(MOD_STR, "get locator card info failed"); goto out; } JS_SetPropertyStr(ctx, obj, "cellid", JS_NewInt32(ctx, locator_info.cellid)); JS_SetPropertyStr(ctx, obj, "lac", JS_NewInt32(ctx, locator_info.lac)); JS_SetPropertyStr(ctx, obj, "mcc", JS_NewString(ctx, locator_info.mcc)); JS_SetPropertyStr(ctx, obj, "mnc", JS_NewString(ctx, locator_info.mnc)); JS_SetPropertyStr(ctx, obj, "signal", JS_NewInt32(ctx, locator_info.signal)); out: return obj; } /************************************************************************************* * Function: native_aiot_close * Description: js native addon for * UDP.close(sock_id) * Called by: js api * Input: sock_id: interger * * Output: return 0 when UDP.close call ok * return error number UDP.close call fail **************************************************************************************/ void cellInfo_receive_callback(aos_locator_info_t *locator_info, int cell_num) { int ret = -1; int i; JSContext *ctx = js_get_context(); JSValue args = JS_NewArray(ctx); for (i = 0; i < cell_num; i++) { JSValue obj = JS_NewObject(ctx); JS_SetPropertyStr(ctx, obj, "cellid", JS_NewInt32(ctx, locator_info[i].cellid)); JS_SetPropertyStr(ctx, obj, "lac", JS_NewInt32(ctx, locator_info[i].lac)); JS_SetPropertyStr(ctx, obj, "mcc", JS_NewString(ctx, locator_info[i].mcc)); JS_SetPropertyStr(ctx, obj, "mnc", JS_NewString(ctx, locator_info[i].mnc)); JS_SetPropertyUint32(ctx, args, i, obj); } JSValue val = JS_Call(ctx, g_js_cb_ref, JS_UNDEFINED, 1, &args); JS_FreeValue(ctx, args); if (JS_IsException(val)) { amp_info(MOD_STR,"cellinfo callback error"); } } static JSValue native_cellular_neighborCellInfo(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; ret = aos_get_neighbor_locator_info(cellInfo_receive_callback); if (ret != 0) { amp_debug(MOD_STR, "get locator card info failed"); goto out; } out: return JS_NewInt32(ctx, ret); } static JSValue native_cellular_getStatus(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; ret = aos_get_network_status(); if (ret != 1) { amp_debug(MOD_STR, "network status disconnect %d", ret); goto out; } out: return JS_NewInt32(ctx, ret); } static void network_status_notify(void *pdata) { int i = 0; network_status_notify_param_t *p = (network_status_notify_param_t *)pdata; JSContext *ctx = js_get_context(); JSValue status = JS_NewInt32(ctx, p->status); JSValue val = JS_Call(ctx, p->js_cb_ref, JS_UNDEFINED, 1, &status); JS_FreeValue(ctx, status); if (JS_IsException(val)) { amp_info(MOD_STR,"network_status_notify callback error"); } } static void network_status_callback(int status, void *args) { network_status_notify_param_t *p = args; if (!p) { amp_warn(MOD_STR, "allocate memory failed"); return; } p->status = status; amp_task_schedule_call(network_status_notify, p); } static JSValue native_cellular_onconnect(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; JSValue js_cb_ref; network_status_notify_param_t *p = NULL; if (!JS_IsFunction(ctx, argv[0])) { amp_warn(MOD_STR, "parameter must be function"); goto out; } JSValue on_cb = argv[0]; if (!JS_IsFunction(ctx, on_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } js_cb_ref = JS_DupValue(ctx, on_cb); p = aos_calloc(1, sizeof(network_status_notify_param_t)); p->js_cb_ref = js_cb_ref; ret = aos_network_status_registercb(network_status_callback, p); if (ret != 0) { JS_FreeValue(ctx, js_cb_ref); return JS_NewInt32(ctx, ret); } out: return JS_NewInt32(ctx, ret); } static JSValue native_get_netshare_mode(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; ret = aos_get_netsharemode(); out: return JS_NewInt32(ctx, ret); } static JSValue native_set_netshare_mode(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int share_mode = 0; if (!JS_IsNumber(argv[0])) { amp_warn(MOD_STR, "parameter must be number"); goto out; } JS_ToInt32(ctx, &share_mode, argv[0]); amp_error(MOD_STR, "native set net share mode = %d", share_mode); ret = aos_set_netsharemode(share_mode); if (ret != 0) { return JS_NewInt32(ctx, ret); } amp_error(MOD_STR, "native set net share mode success"); out: return JS_NewInt32(ctx, ret); } static JSValue native_get_netshare_config(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; aos_sharemode_info_t *share_mode_info; JSValue obj = JS_NewObject(ctx); share_mode_info = aos_malloc(sizeof(aos_sharemode_info_t)); if (share_mode_info == NULL) { amp_debug(MOD_STR, "get net share config failed"); goto out; } memset(share_mode_info, 0, sizeof(aos_sharemode_info_t)); ret = aos_get_netshareconfig(share_mode_info); if (ret != 0) { amp_debug(MOD_STR, "get net share config failed"); goto out; } JS_SetPropertyStr(ctx, obj, "action", JS_NewInt32(ctx, share_mode_info->action)); JS_SetPropertyStr(ctx, obj, "auto_connect", JS_NewInt32(ctx, share_mode_info->auto_connect)); JS_SetPropertyStr(ctx, obj, "apn", JS_NewString(ctx, share_mode_info->apn)); JS_SetPropertyStr(ctx, obj, "username", JS_NewString(ctx, share_mode_info->username)); JS_SetPropertyStr(ctx, obj, "password", JS_NewString(ctx, share_mode_info->password)); JS_SetPropertyStr(ctx, obj, "ip_type", JS_NewInt32(ctx, share_mode_info->ip_type)); JS_SetPropertyStr(ctx, obj, "share_mode", JS_NewInt32(ctx, share_mode_info->share_mode)); aos_free(share_mode_info); return obj; out: if (share_mode_info) { aos_free(share_mode_info); } return JS_NewInt32(ctx, 0); } static JSValue native_set_netshare_config(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; aos_sharemode_info_t *share_mode_info; JSValue obj = JS_NewObject(ctx); /* check paramters */ if (!JS_IsObject(argv[0])) { amp_warn(MOD_STR, "parameter must be object\n"); goto out; } const uint16_t ipType = QUICKJS_GET_PROPERTY_INT32(ctx, argv[0], "ipType"); const uint16_t authType = QUICKJS_GET_PROPERTY_INT32(ctx, argv[0], "authType"); const char *password = QUICKJS_GET_PROPERTY_STR(ctx, argv[0], "password"); const char *username = QUICKJS_GET_PROPERTY_STR(ctx, argv[0], "username"); const char *apn = QUICKJS_GET_PROPERTY_STR(ctx, argv[0], "apn"); const uint16_t autoConnect = QUICKJS_GET_PROPERTY_INT32(ctx, argv[0], "autoConnect"); const uint16_t action = QUICKJS_GET_PROPERTY_INT32(ctx, argv[0], "action"); const uint16_t ucid = QUICKJS_GET_PROPERTY_INT32(ctx, argv[0], "ucid"); share_mode_info = aos_malloc(sizeof(aos_sharemode_info_t)); if (share_mode_info == NULL) { amp_debug(MOD_STR, "set net share config failed"); goto out; } memset(share_mode_info, 0, sizeof(aos_sharemode_info_t)); share_mode_info->action = action; share_mode_info->auto_connect = autoConnect; memcpy(share_mode_info->apn, apn, strlen(apn)); memcpy(share_mode_info->username, username, strlen(username)); memcpy(share_mode_info->password, password, strlen(password)); share_mode_info->ip_type = ipType; JS_FreeCString(ctx, password); JS_FreeCString(ctx, username); JS_FreeCString(ctx, apn); ret = aos_set_netshareconfig(ucid, authType, share_mode_info); if (ret != 0) { amp_warn(MOD_STR, "amp set net share config failed!"); aos_free(share_mode_info); return JS_NewInt32(ctx, 0); } out: if (share_mode_info) { aos_free(share_mode_info); } return JS_NewInt32(ctx, 0); } static JSClassDef js_cellular_class = { "CELLULAR", }; static const JSCFunctionListEntry js_cellular_funcs[] = { JS_CFUNC_DEF("getSimInfo", 0, native_cellular_get_simInfo), JS_CFUNC_DEF("getLocatorInfo", 0, native_cellular_get_locatorInfo), JS_CFUNC_DEF("getStatus", 0, native_cellular_getStatus), JS_CFUNC_DEF("onConnect", 1, native_cellular_onconnect), JS_CFUNC_DEF("getNeighborCellInfo", 0, native_cellular_neighborCellInfo), JS_CFUNC_DEF("getNetSharemode", 0, native_get_netshare_mode), JS_CFUNC_DEF("setNetSharemode", 1, native_set_netshare_mode), JS_CFUNC_DEF("getNetShareconfig", 0, native_get_netshare_config), JS_CFUNC_DEF("setNetShareconfig", 1, native_set_netshare_config) }; static int js_cellular_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_cellular_class_id); JS_NewClass(JS_GetRuntime(ctx), js_cellular_class_id, &js_cellular_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_cellular_funcs, countof(js_cellular_funcs)); JS_SetClassProto(ctx, js_cellular_class_id, proto); return JS_SetModuleExportList(ctx, m, js_cellular_funcs, countof(js_cellular_funcs)); } JSModuleDef *js_init_module_cellular(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_cellular_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_cellular_funcs, countof(js_cellular_funcs)); return m; } void module_cellular_register(void) { amp_debug(MOD_STR, "module_cellular_register"); JSContext *ctx = js_get_context(); js_init_module_cellular(ctx, "CELLULAR"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/network/cellular/module_cellular.c
C
apache-2.0
12,256
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "amp_platform.h" #include "aos_system.h" #include "aos_network.h" #include "amp_defines.h" #include "aos_network.h" #include "aos_socket.h" #include "httpclient.h" #include "aos_tcp.h" #include "amp_task.h" #include "cJSON.h" #include "aos/list.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "HTTP" #define HTTP_BUFF_SIZE 2048 #define HTTP_HEADER_SIZE 1024 #define HTTP_HEADER_COUNT 8 #define HTTP_REQUEST_PARAMS_LEN_MAX 2048 #define HTTP_SEND_RECV_TIMEOUT 10000 #define HTTP_REQUEST_TIMEOUT 30000 #define HTTP_DEFAULT_HEADER_NAME "content-type" #define HTTP_DEFAULT_HEADER_DATA "application/json" #define HTTP_CRLF "\r\n" #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif static JSClassID js_http_class_id; static int http_header_index = 0; typedef struct { char *name; char *data; } http_header_t; typedef struct { char *url; char *filepath; int method; int content_size; http_header_t http_header[HTTP_HEADER_COUNT]; uint32_t timeout; char *params; int params_len; char *buffer; char *header_buffer; int error; JSValue js_cb_ref; } http_param_t; /**************** http download ******************/ typedef struct { http_param_t *http_param; int index; } http_download_param_t; typedef struct { JSValue js_cb_ref; int error; } http_download_resp_t; typedef struct { http_download_param_t *dload_param; dlist_t node; } http_dload_node_t; #define HTTP_HEADER \ "GET /%s HTTP/1.1\r\nAccept:*/*\r\n" \ "User-Agent: Mozilla/5.0\r\n" \ "Cache-Control: no-cache\r\n" \ "Connection: close\r\n" \ "Host:%s:%d\r\n\r\n" #define TCP_WRITE_TIMEOUT 3000 #define TCP_READ_TIMEOUT 3000 #define HTTP_ERROR_NET 1 #define HTTP_ERROR_FS 2 static dlist_t g_dload_list = AOS_DLIST_HEAD_INIT(g_dload_list); static int dload_list_count = 0; int32_t httpc_construct_header(char *buf, uint16_t buf_size, const char *name, const char *data) { uint32_t hdr_len; uint32_t hdr_data_len; int32_t hdr_length; if (buf == NULL || buf_size == 0 || name == NULL || data == NULL) { return HTTP_EARG; } hdr_len = strlen(name); hdr_data_len = strlen(data); hdr_length = hdr_len + hdr_data_len + 4; if (hdr_length < 0 || hdr_length > buf_size) { return HTTP_ENOBUFS; } memcpy(buf, name, hdr_len); buf += hdr_len; memcpy(buf, ": ", 2); buf += 2; memcpy(buf, data, hdr_data_len); buf += hdr_data_len; memcpy(buf, HTTP_CRLF, 2); return hdr_length; } static void http_request_notify(void *pdata) { http_param_t *msg = (http_param_t *)pdata; JSContext *ctx = js_get_context(); JSValue args[2]; int num = 1; args[0] = JS_NewString(ctx, msg->buffer); if (msg->header_buffer) { args[1] = JS_NewString(ctx, msg->header_buffer); num = 2; } JSValue val = JS_Call(ctx, msg->js_cb_ref, JS_UNDEFINED, num, args); JS_FreeValue(ctx, args[0]); if (msg->header_buffer) { JS_FreeValue(ctx, args[1]); amp_free(msg->header_buffer); } JS_FreeValue(ctx, msg->js_cb_ref); if (JS_IsException(val)) { amp_info(MOD_STR, "http_request_notify callback error"); } JS_FreeValue(ctx, val); amp_free(msg->buffer); amp_free(msg); } /* create task for http download */ static int http_download_func(http_param_t *param) { httpclient_t client = { 0 }; httpclient_data_t client_data = { 0 }; int num = 0; int wirte_file_len = 0; int ret = 0; int rtn = 0; char *customer_header = NULL; if (param == NULL) { return HTTP_ERROR_FS; } if (param->filepath == NULL) { ret = HTTP_ERROR_FS; amp_warn(MOD_STR, "filepath empty\n"); goto exit; } char *req_url = param->url; int fd = aos_open(param->filepath, O_CREAT | O_RDWR); client_data.header_buf = amp_calloc(HTTP_BUFF_SIZE, 1); client_data.header_buf_len = HTTP_BUFF_SIZE; client_data.response_buf = amp_calloc(HTTP_BUFF_SIZE, 1); client_data.response_buf_len = HTTP_BUFF_SIZE; aos_msleep(50); /* need do things after state changed in main task */ customer_header = amp_calloc(HTTP_HEADER_SIZE, 1); for (int i = 0; i < 8; i++) { if ((param->http_header[i].name != NULL) && (param->http_header[i].data != NULL)) { httpc_construct_header(customer_header, HTTP_HEADER_SIZE, param->http_header[i].name, param->http_header[i].data); amp_free(param->http_header[i].name); amp_free(param->http_header[i].data); } } httpclient_set_custom_header(&client, customer_header); ret = httpclient_conn(&client, req_url); if (ret == HTTP_SUCCESS) { ret = httpclient_send(&client, req_url, HTTP_GET, &client_data); if (ret == HTTP_SUCCESS) { do { rtn = 0; memset(client_data.response_buf, 0, HTTP_BUFF_SIZE); ret = httpclient_recv(&client, &client_data); if (ret < HTTP_SUCCESS) { amp_warn(MOD_STR, "http recv file %s error %d\n", param->filepath, ret); rtn = HTTP_ERROR_NET; break; } num = aos_write(fd, client_data.response_buf, client_data.content_block_len); if (num < 0) { amp_warn(MOD_STR, "write file %s error\n", param->filepath); rtn = HTTP_ERROR_FS; break; } wirte_file_len += num; } while (client_data.is_more); } else { amp_warn(MOD_STR, "http send error %d\n", ret); } } else { amp_warn(MOD_STR, "http conn error %d\n", ret); } amp_debug(MOD_STR, "write file %s size: %d\n", param->filepath, wirte_file_len); ret = aos_sync(fd); param->buffer = amp_malloc(32); strcpy(param->buffer, "http download success"); httpclient_clse(&client); exit: if (customer_header != NULL) { amp_free(customer_header); } if (client_data.header_buf) { amp_free(client_data.header_buf); } if (client_data.response_buf) { amp_free(client_data.response_buf); } if (param->url != NULL) { amp_free(param->url); } if (param->filepath != NULL) { amp_free(param->filepath); } if (param->params != NULL) { amp_free(param->params); } param->error = rtn; return rtn; } static void task_http_download(void *arg) { http_download_func(arg); amp_task_schedule_call(http_request_notify, arg); aos_task_exit(0); } /* create task for http request */ static void task_http_request_func(void *arg) { int ret = 0; char *customer_header = NULL; httpclient_t client = { 0 }; httpclient_data_t client_data = { 0 }; http_param_t *param = (http_param_t *)arg; if (param == NULL) { amp_error(MOD_STR, "param is NULL"); return; } amp_info(MOD_STR, "task_http_request_func url: %s\n", param->url); amp_info(MOD_STR, "task_http_request_func method: %d", param->method); amp_info(MOD_STR, "task_http_request_func timeout: %d", param->timeout); client_data.header_buf = amp_calloc(HTTP_BUFF_SIZE, 1); client_data.header_buf_len = HTTP_BUFF_SIZE; client_data.response_buf = amp_calloc(HTTP_BUFF_SIZE, 1); client_data.response_buf_len = HTTP_BUFF_SIZE; aos_msleep(50); /* need do things after state changed in main task */ customer_header = amp_calloc(HTTP_HEADER_SIZE, 1); for (int i = 0; i < 8; i++) { if ((param->http_header[i].name != NULL) && (param->http_header[i].data != NULL)) { httpc_construct_header(customer_header, HTTP_HEADER_SIZE, param->http_header[i].name, param->http_header[i].data); amp_free(param->http_header[i].name); amp_free(param->http_header[i].data); } } http_header_index = 0; httpclient_set_custom_header(&client, customer_header); param->buffer = amp_malloc(2048); memset(param->buffer, 0, 2048); param->header_buffer = amp_malloc(2048); memset(param->header_buffer, 0, 2048); if (param->method == HTTP_GET) { amp_info(MOD_STR, "http GET request=%s,timeout=%d\r\n", param->url, param->timeout); ret = httpclient_get(&client, param->url, &client_data); if (ret >= 0) { amp_info(MOD_STR, "GET Data received: %s, len=%d \r\n", client_data.response_buf, client_data.response_buf_len); strcpy(param->buffer, client_data.response_buf); strcpy(param->header_buffer, client_data.header_buf); } else { amp_error(MOD_STR, "http get error %d\r\n", ret); } } else if (param->method == HTTP_POST) { if (param->params != NULL) { amp_info(MOD_STR, "http POST request=%s, post_buf=%s, timeout=%d\r\n", param->url, param->params, param->timeout); memset(client_data.header_buf, 0, sizeof(client_data.header_buf)); strcpy(client_data.header_buf, param->params); client_data.post_buf = client_data.header_buf; client_data.post_buf_len = sizeof(client_data.header_buf); client_data.post_content_type = "application/x-www-form-urlencoded"; ret = httpclient_post(&client, param->url, &client_data); if (ret >= 0) { amp_info(MOD_STR, "POST Data received: %s, len=%d \r\n", client_data.response_buf, client_data.response_buf_len); strcpy(param->buffer, client_data.response_buf); } else { amp_error(MOD_STR, "http post error %d\r\n", ret); } } else { amp_error(MOD_STR, "method POST need params\n"); } } else if (param->method == HTTP_PUT) { if (param->params != NULL) { amp_info(MOD_STR, "http PUT request=%s, data=%s, timeout=%d\r\n", param->url, param->params, param->timeout); client_data.post_buf = param->params; client_data.post_buf_len = param->params_len; ret = httpclient_put(&client, param->url, &client_data); if (ret >= 0) { amp_info(MOD_STR, "Data received: %s, len=%d \r\n", client_data.response_buf, client_data.response_buf_len); strcpy(param->buffer, client_data.response_buf); } } else { amp_error(MOD_STR, "method PUT need params\n"); } } else { amp_error(MOD_STR, "method %d not supported\n", param->method); } if (param->url != NULL) { amp_free(param->url); } if (param->filepath != NULL) { amp_free(param->filepath); } if (param->params != NULL) { amp_free(param->params); } if (customer_header != NULL) { amp_free(customer_header); } if (client_data.header_buf) { amp_free(client_data.header_buf); } if (client_data.response_buf) { amp_free(client_data.response_buf); } amp_task_schedule_call(http_request_notify, param); aos_task_exit(0); return; } static http_param_t *native_http_get_param(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { http_param_t *http_param = NULL; char *http_buffer = NULL; cJSON *param_root; char localip[32]; http_param = (http_param_t *)amp_malloc(sizeof(http_param_t)); if (!http_param) { amp_warn(MOD_STR, "allocate memory failed\n"); return NULL; } memset(http_param, 0, sizeof(http_param_t)); /* get http request url */ JSValue url = JS_GetPropertyStr(ctx, argv[0], "url"); if (!JS_IsString(url)) { amp_debug(MOD_STR, "param no request url"); amp_free(http_param); return NULL; } char *url_c = JS_ToCString(ctx, url); if (url_c != NULL) { http_param->url = amp_malloc(strlen(url_c) + 1); strcpy(http_param->url, url_c); JS_FreeCString(ctx, url_c); } JS_FreeValue(ctx, url); /* get http request method */ JSValue method = JS_GetPropertyStr(ctx, argv[0], "method"); char *m = NULL; if (JS_IsString(method)) { m = JS_ToCString(ctx, method); if (strcmp(m, "GET") == 0) { http_param->method = HTTP_GET; /* GET */ } else if (strcmp(m, "POST") == 0) { http_param->method = HTTP_POST; /* POST */ } else if (strcmp(m, "PUT") == 0) { http_param->method = HTTP_PUT; /* PUT */ } else { http_param->method = HTTP_GET; } } else { http_param->method = HTTP_GET; } JS_FreeCString(ctx, m); JS_FreeValue(ctx, method); /* get http request timeout */ JSValue timeout = JS_GetPropertyStr(ctx, argv[0], "timeout"); int32_t time = 0; if (JS_IsNumber(timeout)) { JS_ToInt32(ctx, &time, timeout); http_param->timeout = time; } else { http_param->timeout = HTTP_REQUEST_TIMEOUT; } JS_FreeValue(ctx, timeout); // size JSValue jsize = JS_GetPropertyStr(ctx, argv[0], "size"); if ((!JS_IsException(jsize)) && (!JS_IsUndefined(jsize))) { if (JS_IsNumber(jsize)) { JS_ToInt32(ctx, &http_param->timeout, jsize); } } JS_FreeValue(ctx, jsize); /* get http request headers */ JSValue headers = JS_GetPropertyStr(ctx, argv[0], "headers"); JSPropertyEnum *ptab = NULL; int plen = 0; char *name = NULL; int ret = JS_GetOwnPropertyNames(ctx, &ptab, &plen, headers, JS_GPN_STRING_MASK); if (ret == 0) { for (int i = 0; i < plen; i++) { name = JS_AtomToCString(ctx, ptab[i].atom); if (name != NULL) { http_param->http_header[i].name = amp_malloc(strlen(name) + 1); strcpy(http_param->http_header[i].name, name); JS_FreeCString(ctx, name); JSValue value = JS_GetPropertyStr(ctx, headers, name); char *data = JS_ToCString(ctx, value); http_param->http_header[i].data = amp_malloc(strlen(data) + 1); strcpy(http_param->http_header[i].data, data); JS_FreeCString(ctx, data); JS_FreeValue(ctx, value); amp_debug(MOD_STR, "headers: %s:%s\n", http_param->http_header[i].name, http_param->http_header[i].data); } } } js_free(ctx, ptab); JS_FreeValue(ctx, headers); amp_debug(MOD_STR, "url: %s\n", http_param->url); amp_debug(MOD_STR, "method: %d\n", http_param->method); amp_debug(MOD_STR, "timeout: %d\n", http_param->timeout); /* get http request params */ JSValue params = JS_GetPropertyStr(ctx, argv[0], "params"); if (JS_IsString(params)) { char *params_str = JS_ToCString(ctx, params); if (params_str != NULL) { http_param->params = amp_malloc(strlen(params_str) + 1); strcpy(http_param->params, params_str); JS_FreeCString(ctx, params_str); http_param->params_len = strlen(http_param->params); amp_debug(MOD_STR, "params: %s, len %d\n", http_param->params, http_param->params_len); } } else { amp_debug(MOD_STR, "params not contained"); } JS_FreeValue(ctx, params); /* callback */ JSValue cb = JS_GetPropertyStr(ctx, argv[0], "success"); http_param->js_cb_ref = JS_DupValue(ctx, cb); JS_FreeValue(ctx, cb); JSValue filepath = JS_GetPropertyStr(ctx, argv[0], "filepath"); if (JS_IsString(filepath)) { char *filepath_c = JS_ToCString(ctx, filepath); if (filepath_c != NULL) { http_param->filepath = amp_malloc(strlen(filepath_c) + 1); strcpy(http_param->filepath, filepath_c); JS_FreeCString(ctx, filepath_c); } } JS_FreeValue(ctx, filepath); amp_debug(MOD_STR, "filepath: %s\n", http_param->filepath); return http_param; } static void http_param_free(JSContext *ctx, http_param_t *http_param) { if (http_param == NULL) { return; } if (http_param->url != NULL) { amp_free(http_param->url); } if (http_param->filepath != NULL) { amp_free(http_param->filepath); } if (http_param->params != NULL) { amp_free(http_param->params); } JS_FreeValue(ctx, http_param->js_cb_ref); } static JSValue native_http_download(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { aos_task_t http_task; http_param_t *http_param = native_http_get_param(ctx, this_val, argc, argv); if (http_param == NULL) { return JS_NewInt32(ctx, -1); } if (http_param->filepath == NULL) { http_param_free(ctx, http_param); return JS_NewInt32(ctx, -1); } aos_task_new_ext(&http_task, "amp http task", task_http_download, http_param, 1024 * 8, ADDON_TSK_PRIORRITY); return JS_NewInt32(ctx, 1); } static JSValue native_http_request(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { aos_task_t http_task; http_param_t *http_param = native_http_get_param(ctx, this_val, argc, argv); if (http_param == NULL) { return JS_NewInt32(ctx, -1); } aos_task_new_ext(&http_task, "amp http task", task_http_request_func, http_param, 1024 * 8, ADDON_TSK_PRIORRITY); return JS_NewInt32(ctx, 1); } static void http_recv_and_save_notify(void *pdata) { http_download_resp_t *resp = (http_download_resp_t *)pdata; JSContext *ctx = js_get_context(); JSValue args = JS_NewInt32(ctx, resp->error); JSValue val = JS_Call(ctx, resp->js_cb_ref, JS_UNDEFINED, 1, &args); JS_FreeValue(ctx, args); if (JS_IsException(val)) { amp_info(MOD_STR, "http_request_notify callback error"); } JS_FreeValue(ctx, val); JS_FreeValue(ctx, resp->js_cb_ref); amp_free(resp); } static void task_http_download_loop(void *arg) { http_download_resp_t *resp = (http_download_resp_t *)arg; http_dload_node_t *dload_node; dlist_t *temp; int ret; resp->error = 0; dlist_for_each_entry_safe(&g_dload_list, temp, dload_node, http_dload_node_t, node) { ret = http_download_func(dload_node->dload_param->http_param); if (ret > 0) { resp->error = ret; break; } dlist_del(&dload_node->node); amp_free(dload_node->dload_param); amp_free(dload_node); } if (ret > 0) { dlist_for_each_entry_safe(&g_dload_list, temp, dload_node, http_dload_node_t, node) { dlist_del(&dload_node->node); amp_free(dload_node->dload_param); amp_free(dload_node); } } dload_list_count = 0; amp_task_schedule_call(http_recv_and_save_notify, resp); aos_task_exit(0); } static JSValue native_http_download_start(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { aos_task_t http_task; http_download_resp_t *resp; int prio = AOS_DEFAULT_APP_PRI + 2; int ret; resp = amp_malloc(sizeof(http_download_resp_t)); if (!resp) { amp_error(MOD_STR, "alloc download resp fail\n"); return JS_NewInt32(ctx, -1); } /* callback */ JSValue val = JS_GetPropertyStr(ctx, argv[0], "success"); if ((!JS_IsException(val)) && (!JS_IsUndefined(val))) { resp->js_cb_ref = JS_DupValue(ctx, val); } else { resp->js_cb_ref = JS_UNDEFINED; } ret = aos_task_new_ext(&http_task, "http-dload", task_http_download_loop, resp, 10240, prio); if (ret) { amp_error(MOD_STR, "create dload task fail %d", ret); return JS_NewInt32(ctx, -1); } return JS_NewInt32(ctx, 0); } static JSValue native_http_download_add(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { http_download_param_t *http_download_param = NULL; http_dload_node_t *dload_node; http_param_t *http_param = native_http_get_param(ctx, this_val, argc, argv); if (http_param == NULL) { return JS_NewInt32(ctx, -1); } http_download_param = amp_malloc(sizeof(http_download_param_t)); if (http_download_param == NULL) { http_param_free(ctx, http_param); return JS_NewInt32(ctx, -1); } http_download_param->http_param = http_param; dload_node = amp_malloc(sizeof(http_dload_node_t)); if (!dload_node) { amp_error(MOD_STR, "alloc http dload node failed"); http_param_free(ctx, http_param); amp_free(http_download_param); return JS_NewInt32(ctx, -1); } memset(dload_node, 0, sizeof(http_dload_node_t)); dload_node->dload_param = http_download_param; dlist_add_tail(&dload_node->node, &g_dload_list); http_download_param->index = ++dload_list_count; return JS_NewInt32(ctx, 0); } static JSClassDef js_http_class = { "HTTP", }; static const JSCFunctionListEntry js_http_funcs[] = { JS_CFUNC_DEF("request", 1, native_http_request), JS_CFUNC_DEF("download", 1, native_http_download), JS_CFUNC_DEF("startDownload", 1, native_http_download_start), JS_CFUNC_DEF("addDownload", 1, native_http_download_add) }; static int js_http_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_http_class_id); JS_NewClass(JS_GetRuntime(ctx), js_http_class_id, &js_http_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_http_funcs, countof(js_http_funcs)); JS_SetClassProto(ctx, js_http_class_id, proto); return JS_SetModuleExportList(ctx, m, js_http_funcs, countof(js_http_funcs)); } JSModuleDef *js_init_module_http(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_http_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_http_funcs, countof(js_http_funcs)); return m; } void module_http_register(void) { amp_debug(MOD_STR, "module_http_register"); JSContext *ctx = js_get_context(); js_init_module_http(ctx, "http"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/network/http/module_http.c
C
apache-2.0
22,662
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "aos_system.h" #include "amp_defines.h" #include "aos_network.h" #include "amp_task.h" #include "aos/list.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "module_network" static JSClassID js_network_class_id; static JSValue native_network_get_type(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; ret = aos_get_network_type(); return JS_NewInt32(ctx, ret); } static JSClassDef js_network_class = { "NETWORK", }; static const JSCFunctionListEntry js_network_funcs[] = { JS_CFUNC_DEF("getType", 0, native_network_get_type) }; static int js_network_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_network_class_id); JS_NewClass(JS_GetRuntime(ctx), js_network_class_id, &js_network_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_network_funcs, countof(js_network_funcs)); JS_SetClassProto(ctx, js_network_class_id, proto); return JS_SetModuleExportList(ctx, m, js_network_funcs, countof(js_network_funcs)); } JSModuleDef *js_init_module_network(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_network_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_network_funcs, countof(js_network_funcs)); return m; } void module_network_register(void) { amp_debug(MOD_STR, "module_network_register"); JSContext *ctx = js_get_context(); js_init_module_network(ctx, "NETWORK"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/network/module_network.c
C
apache-2.0
1,700
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "amp_platform.h" #include "aos_system.h" #include "aos_network.h" #include "amp_memory.h" #include "amp_defines.h" #include "module_mqtt.h" #include "aiot_mqtt_api.h" #include "amp_task.h" #include "amp_list.h" #include "quickjs_addon_common.h" #define MOD_STR "MQTT" #define MQTT_TASK_YIELD_TIMEOUT 200 static char g_mqtt_close_flag = 0; static char g_mqtt_conn_flag = 0; static aos_sem_t g_mqtt_close_sem = NULL; #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif static JSClassID js_mqtt_class_id; static JSClassDef js_mqtt_class = { "MQTT", }; typedef struct { aos_mqtt_handle_t *aos_mqtt_handle; char *topic; char *payload; char *service_id; char *params; JSValue js_cb_ref; int ret_code; int topic_len; int payload_len; int params_len; uint64_t msg_id; aiot_mqtt_option_t option; aiot_mqtt_event_type_t event_type; aiot_mqtt_recv_type_t recv_type; } aos_mqtt_notify_param_t; static char *__amp_strdup(char *src) { char *dst; size_t len = 0; if (src == NULL) { return NULL; } len = strlen(src); dst = amp_malloc(len + 1); if (dst == NULL) { return NULL; } memcpy(dst, src, len); dst[len] = '\0'; return dst; } static void aos_mqtt_notify(void *pdata) { aos_mqtt_notify_param_t *param = (aos_mqtt_notify_param_t *)pdata; JSContext *ctx = js_get_context(); if (param->option == AIOT_MQTTOPT_EVENT_HANDLER) { switch (param->event_type) { case AIOT_MQTTEVT_CONNECT: case AIOT_MQTTEVT_RECONNECT: case AIOT_MQTTEVT_DISCONNECT: { JSValue obj = JS_NewObject(ctx); JS_SetPropertyStr(ctx, obj, "code", JS_NewInt32(ctx, param->ret_code)); JSValue mqtt = JS_NewObjectClass(ctx, js_mqtt_class_id); JS_SetOpaque(mqtt, param->aos_mqtt_handle); JS_SetPropertyStr(ctx, obj, "handle", mqtt); JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &obj); JS_FreeValue(ctx, val); JS_FreeValue(ctx, obj); } break; default: amp_free(param); return; } } else if (param->option == AIOT_MQTTOPT_RECV_HANDLER) { switch (param->recv_type) { case AIOT_MQTTRECV_PUB: { JSValue obj = JS_NewObject(ctx); JS_SetPropertyStr(ctx, obj, "code", JS_NewInt32(ctx, param->ret_code)); JSValue mqtt = JS_NewObjectClass(ctx, js_mqtt_class_id); JS_SetOpaque(mqtt, param->aos_mqtt_handle); JS_SetPropertyStr(ctx, obj, "handle", mqtt); JS_SetPropertyStr(ctx, obj, "topic", JS_NewString(ctx, param->topic)); JS_SetPropertyStr(ctx, obj, "payload", JS_NewString(ctx, param->payload)); JSValue val = JS_Call(ctx, param->js_cb_ref, JS_UNDEFINED, 1, &obj); JS_FreeValue(ctx, val); JS_FreeValue(ctx, obj); amp_free(param->topic); amp_free(param->payload); } break; default: amp_free(param); return; } } amp_free(param); } static void aos_mqtt_message_cb(aos_mqtt_message_t *message, void *userdata) { aos_mqtt_userdata_t *udata = (aos_mqtt_userdata_t *)userdata; aos_mqtt_handle_t *aos_mqtt_handle; aos_mqtt_notify_param_t *param; if (!message || !udata) return; param = amp_malloc(sizeof(aos_mqtt_notify_param_t)); if (!param) { amp_error(MOD_STR, "alloc device notify param fail"); return; } memset(param, 0, sizeof(aos_mqtt_notify_param_t)); param->aos_mqtt_handle = (aos_mqtt_handle_t *)udata->handle; param->option = message->option; param->js_cb_ref = param->aos_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_START_CLIENT_REF]; if (message->option == AIOT_MQTTOPT_EVENT_HANDLER) { switch (message->event.type) { case AIOT_MQTTEVT_CONNECT: case AIOT_MQTTEVT_RECONNECT: case AIOT_MQTTEVT_DISCONNECT: param->ret_code = message->event.code; param->event_type = message->event.type; break; default: amp_free(param); return; } } else if (message->option == AIOT_MQTTOPT_RECV_HANDLER) { switch (message->recv.type) { case AIOT_MQTTRECV_PUB: param->ret_code = message->recv.code; param->topic_len = message->recv.topic_len; param->payload_len = message->recv.payload_len; param->topic = __amp_strdup(message->recv.topic); param->payload = __amp_strdup(message->recv.payload); param->recv_type = message->recv.type; break; default: amp_free(param); return; } } else { amp_free(param); return; } amp_task_schedule_call(aos_mqtt_notify, param); } static void mqtt_connect_task(void *pdata) { int ret; JSContext *ctx = js_get_context(); aos_mqtt_handle_t *aos_mqtt_handle = (aos_mqtt_handle_t *)pdata; aos_mqtt_userdata_t *userdata = amp_malloc(sizeof(aos_mqtt_userdata_t)); if (userdata == NULL) { amp_error(MOD_STR, "amp mqtt handle malloc failed"); amp_free(aos_mqtt_handle); return; } userdata->callback = aos_mqtt_message_cb; userdata->handle = aos_mqtt_handle; ret = mqtt_client_start(&aos_mqtt_handle->mqtt_handle, userdata); if (ret < 0) { amp_error(MOD_STR, "mqtt client init failed"); goto out; } g_mqtt_conn_flag = 1; aos_mqtt_handle->res = ret; while (!g_mqtt_close_flag) { aos_msleep(1000); } out: JS_FreeValue(ctx, aos_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_START_CLIENT_REF]); JS_FreeCString(ctx, aos_mqtt_handle->host); JS_FreeCString(ctx, aos_mqtt_handle->clientid); JS_FreeCString(ctx, aos_mqtt_handle->username); JS_FreeCString(ctx, aos_mqtt_handle->password); aos_free(userdata); aos_free(aos_mqtt_handle); aos_sem_signal(&g_mqtt_close_sem); aos_task_exit(0); } static JSValue native_mqtt_start(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret; uint32_t val = 0; aos_mqtt_handle_t *aos_mqtt_handle = NULL; aos_task_t mqtt_task; JSValue js_cb_ref; /* check paramters */ JSValue options = argv[0]; JSValue cb = argv[1]; if (!JS_IsObject(options) || !JS_IsFunction(ctx, cb)) { amp_warn(MOD_STR, "parameter must be object and function\n"); ret = -1; goto out; } /* get device certificate */ JSValue j_host = JS_GetPropertyStr(ctx, argv[0], "host"); JSValue j_port = JS_GetPropertyStr(ctx, argv[0], "port"); JSValue j_client_id = JS_GetPropertyStr(ctx, argv[0], "client_id"); JSValue j_username = JS_GetPropertyStr(ctx, argv[0], "username"); JSValue j_password = JS_GetPropertyStr(ctx, argv[0], "password"); JSValue j_keepaliveSec = JS_GetPropertyStr(ctx, argv[0], "keepalive_interval"); if (!JS_IsString(j_host) || !JS_IsNumber(j_port) || !JS_IsString(j_client_id) || !JS_IsString(j_username) || !JS_IsString(j_password) || !JS_IsNumber(j_keepaliveSec)) { amp_warn(MOD_STR, "Parameter 1 must be an object like {host: string, " "port: uint, client_id: string, username: string, " "password: string, keepalive_interval: uint}\n"); ret = -2; goto out; } aos_mqtt_handle = (aos_mqtt_handle_t *)amp_malloc(sizeof(aos_mqtt_handle_t)); if (!aos_mqtt_handle) { amp_error(MOD_STR, "allocate memory failed\n"); goto out; } aos_mqtt_handle->host = JS_ToCString(ctx, j_host); JS_ToUint32(ctx, &val, j_port); aos_mqtt_handle->port = (uint16_t)val; aos_mqtt_handle->clientid = JS_ToCString(ctx, j_client_id); aos_mqtt_handle->username = JS_ToCString(ctx, j_username); aos_mqtt_handle->password = JS_ToCString(ctx, j_password); JS_ToUint32(ctx, &val, j_keepaliveSec); aos_mqtt_handle->keepaliveSec = (uint16_t)val; amp_debug(MOD_STR, "host: %s, port: %d\n", aos_mqtt_handle->host, aos_mqtt_handle->port); amp_debug(MOD_STR, "client_id: %s, username: %s, password: %s\n", aos_mqtt_handle->clientid, aos_mqtt_handle->username, aos_mqtt_handle->password); js_cb_ref = JS_DupValue(ctx, cb); aos_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_START_CLIENT_REF] = js_cb_ref; /* create task to IOT_MQTT_Yield() */ ret = aos_task_new_ext(&mqtt_task, "amp mqtt task", mqtt_connect_task, aos_mqtt_handle, 1024 * 4, MQTT_TSK_PRIORITY); if (ret < 0) { amp_warn(MOD_STR, "jse_osal_create_task failed\n"); JS_FreeValue(ctx, js_cb_ref); aos_free(aos_mqtt_handle); ret = -4; } out: return JS_NewInt32(ctx, ret); } /* subscribe */ static JSValue native_mqtt_subscribe(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; aos_mqtt_handle_t *amp_mqtt_handle = NULL; const char *topic = NULL; uint8_t qos = 0; int js_cb_ref = 0; amp_mqtt_handle = JS_GetOpaque2(ctx, argv[0], js_mqtt_class_id); if (amp_mqtt_handle == NULL) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } topic = JS_ToCString(ctx, argv[1]); JS_ToInt32(ctx, &qos, argv[2]); res = aiot_mqtt_sub(amp_mqtt_handle->mqtt_handle, topic, NULL, qos, NULL); if (res < 0) { amp_error(MOD_STR, "aiot app mqtt subscribe failed, ret = -0x%04X", res); } JS_FreeCString(ctx, topic); out: return JS_NewInt32(ctx, res); } /* unsubscribe */ static JSValue native_mqtt_unsubscribe(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; aos_mqtt_handle_t *amp_mqtt_handle = NULL; const char *topic; uint8_t qos = 0; int js_cb_ref = 0; amp_mqtt_handle = JS_GetOpaque2(ctx, argv[0], js_mqtt_class_id); if (amp_mqtt_handle == NULL) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } topic = JS_ToCString(ctx, argv[1]); amp_debug(MOD_STR, "unsubscribe topic: %s", topic); res = aiot_mqtt_unsub(amp_mqtt_handle->mqtt_handle, topic); if (res < 0) { amp_error(MOD_STR, "aiot app mqtt unsubscribe failed\n"); } JS_FreeCString(ctx, topic); out: return JS_NewInt32(ctx, res); } /* publish */ static JSValue native_mqtt_publish(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; aos_mqtt_handle_t *amp_mqtt_handle = NULL; const char *topic; const char *payload; uint16_t payload_len = 0; uint8_t qos = 0; int js_cb_ref = 0; amp_mqtt_handle = JS_GetOpaque2(ctx, argv[0], js_mqtt_class_id); if (amp_mqtt_handle == NULL) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } topic = JS_ToCString(ctx, argv[1]); payload = JS_ToCString(ctx, argv[2]); JS_ToInt32(ctx, &qos, argv[1]); payload_len = strlen(payload); amp_debug(MOD_STR, "publish topic: %s, payload: %s, qos is: %d", topic, payload, qos); res = aiot_mqtt_pub(amp_mqtt_handle->mqtt_handle, topic, payload, payload_len, qos); if (res < 0) { amp_error(MOD_STR, "aiot app mqtt publish failed"); } JS_FreeCString(ctx, topic); JS_FreeCString(ctx, payload); out: return JS_NewInt32(ctx, res); } static JSValue native_mqtt_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int res = -1; int js_cb_ref = 0; aos_mqtt_handle_t *amp_mqtt_handle = NULL; amp_mqtt_handle = JS_GetOpaque2(ctx, argv[0], js_mqtt_class_id); if (amp_mqtt_handle == NULL) { amp_warn(MOD_STR, "mqtt handle is null"); goto out; } res = mqtt_client_stop(&amp_mqtt_handle->mqtt_handle); if (res < 0) { amp_debug(MOD_STR, "mqtt client stop failed"); } out: /* release mqtt in mqtt_yield_task() */ g_mqtt_close_flag = 1; aos_sem_wait(&g_mqtt_close_sem, MQTT_TASK_YIELD_TIMEOUT + 50); g_mqtt_close_flag = 0; return JS_NewInt32(ctx, 1); } static void module_mqtt_source_clean(void) { if (g_mqtt_close_flag) { aos_sem_wait(&g_mqtt_close_sem, MQTT_TASK_YIELD_TIMEOUT + 50); g_mqtt_close_flag = 0; } } static const JSCFunctionListEntry js_mqtt_funcs[] = { JS_CFUNC_DEF("start", 2, native_mqtt_start), JS_CFUNC_DEF("subscribe", 3, native_mqtt_subscribe), JS_CFUNC_DEF("unsubscribe", 3, native_mqtt_unsubscribe), JS_CFUNC_DEF("publish", 5, native_mqtt_publish), JS_CFUNC_DEF("close", 2, native_mqtt_close), }; static int js_mqtt_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_mqtt_class_id); JS_NewClass(JS_GetRuntime(ctx), js_mqtt_class_id, &js_mqtt_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_mqtt_funcs, countof(js_mqtt_funcs)); JS_SetClassProto(ctx, js_mqtt_class_id, proto); return JS_SetModuleExportList(ctx, m, js_mqtt_funcs, countof(js_mqtt_funcs)); } JSModuleDef *js_init_module_mqtt(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_mqtt_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_mqtt_funcs, countof(js_mqtt_funcs)); return m; } void module_mqtt_register(void) { amp_debug(MOD_STR, "module_mqtt_register"); JSContext *ctx = js_get_context(); js_init_module_mqtt(ctx, "MQTT"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/network/mqtt/module_mqtt.c
C
apache-2.0
13,761
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "stdint.h" #include "quickjs.h" #include "aiot_mqtt_api.h" typedef enum { AOS_MQTT_CONNECT, AOS_MQTT_RECONNECT, AOS_MQTT_DISCONNECT, AOS_MQTT_MESSAGE } aos_mqtt_res_type_t; /** * @brief subdev模块内部发生值得用户关注的状态变化时, 通知用户的事件类型 */ typedef enum { /** * @brief 非法的应答报文 */ MQTT_JSCALLBACK_INVALID_REF, /** * @brief 应答报文的id字段非法 */ MQTT_JSCALLBACK_START_CLIENT_REF, /** * @brief 应答报文的id字段非法 */ MQTT_JSCALLBACK_SCRIBE_TOPIC_REF, /** * @brief 应答报文的id字段非法 */ MQTT_JSCALLBACK_UNSCRIBE_TOPIC_REF, /** * @brief 应答报文的id字段非法 */ MQTT_JSCALLBACK_PUBLISH_REF, /** * @brief 应答报文的id字段非法 */ MQTT_JSCALLBACK_CLIENT_STOP_REF, /** * @brief 应答报文的code字段非法 */ MQTT_JSCALLBACK_COMMON_REF, /** * @brief 应答报文的code字段非法 */ MQTT_JSCALLBACK_INVALID_CODE } amp_mqtt_jscallback_type_t; typedef struct { aiot_mqtt_recv_type_t type; int code; int topic_len; int payload_len; char *topic; char *payload; } aos_mqtt_recv_t; typedef struct { aiot_mqtt_event_type_t type; int code; } aos_mqtt_event_t; typedef struct { aiot_mqtt_option_t option; aos_mqtt_recv_t recv; aos_mqtt_event_t event; } aos_mqtt_message_t; typedef struct { void (*callback)(aos_mqtt_message_t *message, void *userdata); void *handle; } aos_mqtt_userdata_t; typedef struct aos_mqtt_handle { char *host; uint16_t port; char *clientid; char *username; char *password; uint16_t keepaliveSec; void *mqtt_handle; JSValue js_cb_ref[MQTT_JSCALLBACK_INVALID_CODE]; int res; } aos_mqtt_handle_t; /* create mqtt client */ int32_t mqtt_client_start(void **handle, aos_mqtt_userdata_t *userdata); /* destroy mqtt client */ int32_t mqtt_client_stop(void **handle);
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/network/mqtt/module_mqtt.h
C
apache-2.0
2,106
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" #include "aos/kv.h" #include "aiot_state_api.h" #include "aiot_sysdep_api.h" #include "aiot_mqtt_api.h" #include "module_mqtt.h" #define MOD_STR "MODULE_MQTT_CLIENT" /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */ extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile; /* 位于external/ali_ca_cert.c中的服务器证书 */ extern const char *ali_ca_cert; uint8_t mqtt_process_thread_running = 0; uint8_t mqtt_recv_thread_running = 0; static char *__amp_strdup(char *src, int len) { char *dst; if (src == NULL) { return NULL; } dst = amp_malloc(len + 1); if (dst == NULL) { return NULL; } memcpy(dst, src, len); dst[len] = '\0'; return dst; } /* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */ void mqtt_process_thread(void *args) { int32_t res = STATE_SUCCESS; while (mqtt_process_thread_running) { res = aiot_mqtt_process(args); if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } aos_task_exit(0); return; } /* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */ void mqtt_recv_thread(void *args) { int32_t res = STATE_SUCCESS; while (mqtt_recv_thread_running) { res = aiot_mqtt_recv(args); if (res < STATE_SUCCESS) { if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } } aos_task_exit(0); return; } /* MQTT默认消息处理回调, 当SDK从服务器收到MQTT消息时, 且无对应用户回调处理时被调用 */ void mqtt_recv_handler(void *handle, const aiot_mqtt_recv_t *packet, void *userdata) { void (*callback)(void *userdata) = (void (*)(void *))userdata; switch (packet->type) { case AIOT_MQTTRECV_HEARTBEAT_RESPONSE: { // amp_debug(MOD_STR, "heartbeat response"); /* TODO: 处理服务器对心跳的回应, 一般不处理 */ } break; case AIOT_MQTTRECV_SUB_ACK: { amp_debug(MOD_STR, "suback, res: -0x%04X, packet id: %d, max qos: %d", -packet->data.sub_ack.res, packet->data.sub_ack.packet_id, packet->data.sub_ack.max_qos); /* TODO: 处理服务器对订阅请求的回应, 一般不处理 */ } break; case AIOT_MQTTRECV_PUB: { // amp_debug(MOD_STR, "pub, qos: %d, topic: %.*s", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic); // amp_debug(MOD_STR, "pub, payload: %.*s", packet->data.pub.payload_len, packet->data.pub.payload); /* TODO: 处理服务器下发的业务报文 */ aos_mqtt_userdata_t *udata = (aos_mqtt_userdata_t *)userdata; aos_mqtt_message_t message; memset(&message, 0, sizeof(aos_mqtt_message_t)); if (udata && udata->callback) { message.option = AIOT_MQTTOPT_RECV_HANDLER; message.recv.type = packet->type; message.recv.code = AOS_MQTT_MESSAGE; message.recv.topic = __amp_strdup(packet->data.pub.topic, packet->data.pub.topic_len); message.recv.payload = __amp_strdup(packet->data.pub.payload, packet->data.pub.payload_len); message.recv.topic_len = packet->data.pub.topic_len; message.recv.payload_len = packet->data.pub.payload_len; udata->callback(&message, udata); amp_free(message.recv.topic); amp_free(message.recv.payload); } } break; case AIOT_MQTTRECV_PUB_ACK: { amp_debug(MOD_STR, "puback, packet id: %d", packet->data.pub_ack.packet_id); /* TODO: 处理服务器对QoS1上报消息的回应, 一般不处理 */ } break; default: { } } } /* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */ void mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata) { aos_mqtt_userdata_t *udata = (aos_mqtt_userdata_t *)userdata; aos_mqtt_message_t message; memset(&message, 0, sizeof(aos_mqtt_message_t)); message.option = AIOT_MQTTOPT_EVENT_HANDLER; message.event.type = event->type; switch (event->type) { /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */ case AIOT_MQTTEVT_CONNECT: { amp_debug(MOD_STR, "AIOT_MQTTEVT_CONNECT"); /* TODO: 处理SDK建连成功, 不可以在这里调用耗时较长的阻塞函数 */ message.event.code = AOS_MQTT_CONNECT; } break; /* SDK因为网络状况被动断连后, 自动发起重连已成功 */ case AIOT_MQTTEVT_RECONNECT: { amp_debug(MOD_STR, "AIOT_MQTTEVT_RECONNECT"); /* TODO: 处理SDK重连成功, 不可以在这里调用耗时较长的阻塞函数 */ message.event.code = AOS_MQTT_RECONNECT; } break; /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */ case AIOT_MQTTEVT_DISCONNECT: { char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") : ("heartbeat disconnect"); amp_debug(MOD_STR, "AIOT_MQTTEVT_DISCONNECT: %s", cause); /* TODO: 处理SDK被动断连, 不可以在这里调用耗时较长的阻塞函数 */ message.event.code = AOS_MQTT_DISCONNECT; } break; default: { return; } } if (udata && udata->callback) udata->callback(&message, udata); } int32_t mqtt_client_start(void **handle, aos_mqtt_userdata_t *userdata) { int32_t res = STATE_SUCCESS; void *mqtt_handle = NULL; aos_mqtt_handle_t *aos_mqtt_handle = (aos_mqtt_handle_t *)userdata->handle; char *host = aos_mqtt_handle->host; uint16_t port = aos_mqtt_handle->port; char *clientid = aos_mqtt_handle->clientid; char *username = aos_mqtt_handle->username; char *password = aos_mqtt_handle->password; uint16_t keepaliveSec = aos_mqtt_handle->keepaliveSec; aiot_sysdep_network_cred_t cred; /* 配置SDK的底层依赖 */ aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile); /* 配置SDK的日志输出 */ // aiot_state_set_logcb(demo_state_logcb); /* 创建SDK的安全凭据, 用于建立TLS连接 */ memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t)); cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */ cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */ cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */ cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */ cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */ /* 创建1个MQTT客户端实例并内部初始化默认参数 */ mqtt_handle = aiot_mqtt_init(); if (mqtt_handle == NULL) { amp_error(MOD_STR, "aiot_mqtt_init failed"); amp_free(mqtt_handle); return -1; } aos_mqtt_handle->mqtt_handle = mqtt_handle; /* TODO: 如果以下代码不被注释, 则例程会用TCP而不是TLS连接云平台 */ { memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t)); cred.option = AIOT_SYSDEP_NETWORK_CRED_NONE; } /* 配置MQTT服务器地址 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host); /* 配置MQTT服务器端口 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port); /* 配置设备productKey */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_CLIENTID, (void *)clientid); /* 配置设备deviceName */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_USERNAME, (void *)username); /* 配置设备deviceSecret */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PASSWORD, (void *)password); /* 配置网络连接的安全凭据, 上面已经创建好了 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred); /* 配置MQTT心跳间隔 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_KEEPALIVE_SEC, (void *)&keepaliveSec); /* 配置回调参数 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_USERDATA, userdata); /* 配置MQTT默认消息接收回调函数 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER, (void *)mqtt_recv_handler); /* 配置MQTT事件回调函数 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)mqtt_event_handler); /* 与服务器建立MQTT连接 */ res = aiot_mqtt_connect(mqtt_handle); if (res < STATE_SUCCESS) { /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */ aiot_mqtt_deinit(&mqtt_handle); amp_error(MOD_STR, "aos_mqtt_connect failed: -0x%04X", -res); aos_task_exit(0); return -1; } /* 创建一个单独的线程, 专用于执行aos_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */ mqtt_process_thread_running = 1; *handle = mqtt_handle; aos_task_t user_mqtt_process_task; if (aos_task_new_ext(&user_mqtt_process_task, "user_mqtt_process", mqtt_process_thread, mqtt_handle, 1024 * 4, AOS_DEFAULT_APP_PRI) != 0) { amp_error(MOD_STR, "user mqtt process task create failed!"); aiot_mqtt_deinit(&mqtt_handle); aos_task_exit(0); return NULL; } amp_debug(MOD_STR, "user mqtt process start"); /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */ mqtt_recv_thread_running = 1; aos_task_t user_mqtt_rec_task; if (aos_task_new_ext(&user_mqtt_rec_task, "user_mqtt_recv", mqtt_recv_thread, mqtt_handle, 1024 * 4, AOS_DEFAULT_APP_PRI) != 0) { amp_error(MOD_STR, "user mqtt rec task create failed!"); aiot_mqtt_deinit(&mqtt_handle); aos_task_exit(0); return NULL; } amp_debug(MOD_STR, "user mqtt recv start"); return 0; } /* mqtt stop */ int32_t mqtt_client_stop(void **handle) { int32_t res = STATE_SUCCESS; void *mqtt_handle = NULL; mqtt_handle = *handle; mqtt_process_thread_running = 0; mqtt_recv_thread_running = 0; /* 断开MQTT连接 */ res = aiot_mqtt_disconnect(mqtt_handle); if (res < STATE_SUCCESS) { aiot_mqtt_deinit(&mqtt_handle); amp_error(MOD_STR, "aiot_mqtt_disconnect failed: -0x%04X", -res); return -1; } /* 销毁MQTT实例 */ res = aiot_mqtt_deinit(&mqtt_handle); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "aiot_mqtt_deinit failed: -0x%04X", -res); return -1; } return res; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/network/mqtt/module_mqtt_client.c
C
apache-2.0
11,324
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "aos_system.h" #include "amp_defines.h" #include "aos_network.h" #include "netmgr_wifi.h" #include "amp_task.h" #include "aos/list.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "module_netmgr" #define CONNECT_WAIT_TIME_MS (100 * 1000) #define CHECKIP_INTERVAL_MS 200 typedef JSValue js_cb_ref; typedef struct msg_cb_info { slist_t next; JSValue cb_ref; } msg_cb_info_t; typedef struct wifi_connect_task_params { JSValue cb_ref; netmgr_hdl_t hdl; } netmgr_onConnect_task_params_t; typedef enum { DEV_INVALID, DEV_WIFI, DEV_ETHNET, DEV_MAX } DEV_TYPE; static JSClassID js_netmgr_class_id; static slist_t g_msg_cb_list_head; static int g_checkip_task_run_flag[DEV_MAX] = {0}; static char dev_name[256]; static void js_cb_conn_status(void *pdata) { int ret = -1; netmgr_onConnect_task_params_t *params; netmgr_ifconfig_info_t info; netmgr_hdl_t hdl; JSValue cb_ref; uint32_t value = 0; DEV_TYPE dev_type = DEV_INVALID; if (pdata == NULL) { amp_debug(MOD_STR, "pdata is null"); return ; } params = (netmgr_onConnect_task_params_t *)pdata; hdl = params->hdl; ret = netmgr_get_ifconfig(hdl, &info); if (ret != 0) { amp_warn(MOD_STR, "get ifconfig info failed"); } if (get_hdl_type(hdl) == NETMGR_TYPE_WIFI) { dev_type = DEV_WIFI; } else if (get_hdl_type(hdl) == NETMGR_TYPE_ETH) { dev_type = DEV_ETHNET; } else { amp_warn(MOD_STR, "unkown type"); return; } if (g_checkip_task_run_flag[dev_type] != 1) { amp_warn(MOD_STR, "g_checkip_task_run_flag[%d] is 0", dev_type); return; } JSContext *ctx = js_get_context(); JSValue args; if (strcmp(info.ip_addr, "0.0.0.0") != 0) { args = JS_NewString(ctx, "CONNECTED"); amp_warn(MOD_STR, "CONNECTED"); } else { args = JS_NewString(ctx, "DISCONNECT"); amp_warn(MOD_STR, "DISCONNECT"); } JSValue val = JS_Call(ctx, params->cb_ref, JS_UNDEFINED, 1, &args); JS_FreeValue(ctx, args); if (JS_IsException(val)) { amp_info(MOD_STR, "netmgr connect callback error %d ", __LINE__); } JS_FreeValue(ctx, params->cb_ref); JS_FreeValue(ctx, val); } static void check_ip_task(void *arg) { int ret = -1; int count = 0; DEV_TYPE dev_type = DEV_INVALID; netmgr_ifconfig_info_t info = {0}; netmgr_onConnect_task_params_t *params; netmgr_hdl_t hdl; JSContext *ctx = js_get_context(); if (arg == NULL) { amp_warn(MOD_STR, "check ip task arg is null"); return ; } params = (netmgr_onConnect_task_params_t *) arg; hdl = params->hdl; if (get_hdl_type(hdl) == NETMGR_TYPE_WIFI) { dev_type = DEV_WIFI; } else if (get_hdl_type(hdl) == NETMGR_TYPE_ETH) { dev_type = DEV_ETHNET; } else { amp_warn(MOD_STR, "unkown type"); return; } strcpy(info.ip_addr, "0.0.0.0"); while (g_checkip_task_run_flag[dev_type]) { ret = netmgr_get_ifconfig(hdl, &info); if (ret != 0) { amp_warn(MOD_STR, "get ifconfig info failed"); } if ((strcmp(info.ip_addr, "0.0.0.0") != 0) || (count > CONNECT_WAIT_TIME_MS / CHECKIP_INTERVAL_MS)) { amp_task_schedule_call(js_cb_conn_status, arg); break; } aos_msleep(CHECKIP_INTERVAL_MS); count++; } return; } static JSValue native_netmgr_service_init(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret; ret = event_service_init(NULL); if (ret != 0) { amp_error(MOD_STR, "netmgr service init failed"); goto out; } ret = netmgr_service_init(NULL); if (ret != 0) { amp_error(MOD_STR, "netmgr service init failed"); goto out; } out: return JS_NewInt32(ctx, ret); } static JSValue native_netmgr_service_deinit(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { netmgr_hdl_t hdl; int ret = -1; if (!JS_IsNumber(argv[0])) { amp_warn(MOD_STR, "parameter must be number\n"); goto out; } JS_ToInt32(ctx, &hdl, argv[0]); netmgr_service_deinit(hdl); ret = 0; out: return JS_NewInt32(ctx, ret); } static JSValue native_netmgr_add_dev(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char *name; int ret = -1; if (!JS_IsString(argv[0])) { amp_warn(MOD_STR, "parameter must be string\n"); goto out; } name = JS_ToCString(ctx, argv[0]); ret = netmgr_add_dev(name); if (ret != 0) { amp_debug(MOD_STR, "netmgr add dev failed"); } JS_FreeCString(ctx, name); out: return JS_NewInt32(ctx, ret); } static JSValue native_netmgr_get_dev(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char *name; int ret = -1; if (!JS_IsString(argv[0])) { amp_warn(MOD_STR, "parameter must be string\n"); goto out; } name = JS_ToCString(ctx, argv[0]); if (name != NULL) { memset(dev_name, 0, sizeof(dev_name)); strcpy(dev_name, name); } ret = netmgr_get_dev(name); if (ret == -1) { amp_error(MOD_STR, "netmgr get %s dev failed\n", name); } amp_debug(MOD_STR, "native_netmgr_get_dev hdl: %d\n", ret); JS_FreeCString(ctx, name); out: return JS_NewInt32(ctx, ret); } static JSValue native_netmgr_set_auto_reconnect(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; netmgr_hdl_t hdl; int enable; if (!JS_IsNumber(argv[0]) || !JS_IsNumber(argv[1])) { amp_warn(MOD_STR, "parameter must be number and number\n"); goto out; } JS_ToInt32(ctx, &hdl, argv[0]); JS_ToInt32(ctx, &enable, argv[1]); if (enable == 1) { netmgr_set_auto_reconnect(hdl, true); ret = 0; } else if (enable == 0) { netmgr_set_auto_reconnect(hdl, false); ret = 0; } out: return JS_NewInt32(ctx, ret); } static netmgr_onConnect_task_params_t onConnect_task_params; static JSValue native_netmgr_connect(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; aos_task_t netmgr_connect_task; netmgr_hdl_t hdl; netmgr_connect_params_t params; JSValue cb_ref; char *ssid = NULL; char *password = NULL; char *bssid = NULL; int timeout_ms = 0; DEV_TYPE dev_type; JS_ToInt32(ctx, &hdl, argv[0]); if (get_hdl_type(hdl) == NETMGR_TYPE_WIFI) { if (!JS_IsNumber(argv[0]) || !JS_IsObject(argv[1]) || !JS_IsFunction(ctx, argv[2])) { amp_warn(MOD_STR, "parameter must be number, object and function\n"); goto out; } JSValue js_ssid = JS_GetPropertyStr(ctx, argv[1], "ssid"); if (!JS_IsString(js_ssid)) { amp_error(MOD_STR, "request ssid is invalid"); goto out; } ssid = JS_ToCString(ctx, js_ssid); JS_FreeValue(ctx, js_ssid); JSValue js_password = JS_GetPropertyStr(ctx, argv[1], "password"); if (!JS_IsString(js_password)) { amp_error(MOD_STR, "request password is invalid"); goto out; } password = JS_ToCString(ctx, js_password); JS_FreeValue(ctx, js_password); JSValue js_bssid = JS_GetPropertyStr(ctx, argv[1], "bssid"); if (!JS_IsString(js_bssid)) { amp_error(MOD_STR, "request bssid is invalid"); goto out; } bssid = JS_ToCString(ctx, js_bssid); JS_FreeValue(ctx, js_bssid); JSValue js_timeout_ms = JS_GetPropertyStr(ctx, argv[1], "timeout_ms"); if (!JS_IsString(js_timeout_ms)) { JS_ToInt32(ctx, &timeout_ms, js_timeout_ms); } JS_FreeValue(ctx, js_timeout_ms); memset(&params, 0, sizeof(netmgr_connect_params_t)); params.type = NETMGR_TYPE_WIFI; strncpy(params.params.wifi_params.ssid, ssid, sizeof(params.params.wifi_params.ssid) - 1); strncpy(params.params.wifi_params.pwd, password, sizeof(params.params.wifi_params.pwd) - 1); params.params.wifi_params.timeout = timeout_ms; ret = netmgr_connect(hdl, &params); if (ret != 0) { amp_warn(MOD_STR, "netmgr connect failed\n"); goto out; } dev_type = DEV_WIFI; cb_ref = argv[2]; if (!JS_IsFunction(ctx, cb_ref)) { return JS_ThrowTypeError(ctx, "not a function"); } } else if (get_hdl_type(hdl) == NETMGR_TYPE_ETH) { if (!JS_IsNumber(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be number and function\n"); goto out; } dev_type = DEV_ETHNET; cb_ref = argv[1]; if (!JS_IsFunction(ctx, cb_ref)) { return JS_ThrowTypeError(ctx, "not a function"); } } else { amp_error(MOD_STR, "unkown device!"); return JS_ThrowTypeError(ctx, "unkown device!"); } memset(&onConnect_task_params, 0, sizeof(onConnect_task_params)); onConnect_task_params.cb_ref = JS_DupValue(ctx, cb_ref); onConnect_task_params.hdl = hdl; g_checkip_task_run_flag[dev_type] = 1; ret = aos_task_new_ext(&netmgr_connect_task, "netmgr connect task", check_ip_task, (void *)&onConnect_task_params, 1024 * 2, ADDON_TSK_PRIORRITY); if (ret != 0) { amp_warn(MOD_STR, "jse_osal_create_task failed\n"); JS_FreeValue(ctx, cb_ref); } out: if (ssid != NULL) { JS_FreeCString(ctx, ssid); } if (password != NULL) { JS_FreeCString(ctx, password); } if (bssid != NULL) { JS_FreeCString(ctx, bssid); } return JS_NewInt32(ctx, ret); } /***************************************************************************** * Function: native_netmgr_disconnect * Description: js native addon for WIFI.getssid() * Called by: js api * Input: no input * Output: return a string object to js api what the mac is *****************************************************************************/ static JSValue native_netmgr_disconnect(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; netmgr_hdl_t hdl; if (!JS_IsNumber(argv[0])) { amp_warn(MOD_STR, "parameter must be number\n"); goto out; } JS_ToInt32(ctx, &hdl, argv[0]); ret = netmgr_disconnect(hdl); if (ret != 0) { amp_debug(MOD_STR, "netmgr disconnect failed"); goto out; } out: return JS_NewInt32(ctx, ret); } /***************************************************************************** * Function: native_netmgr_get_state * Description: js native addon for NETMGR.getState() * Called by: js api * Input: no input * Output: return a string object to js api what the mac is *****************************************************************************/ static JSValue native_netmgr_get_state(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; netmgr_hdl_t hdl; if (!JS_IsNumber(argv[0])) { amp_warn(MOD_STR, "parameter must be number\n"); goto out; } JS_ToInt32(ctx, &hdl, argv[0]); ret = netmgr_get_state(hdl); out: return JS_NewInt32(ctx, ret); } static JSValue native_netmgr_save_config(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; netmgr_hdl_t hdl; if (!JS_IsNumber(argv[0])) { amp_warn(MOD_STR, "parameter must be number\n"); goto out; } JS_ToInt32(ctx, &hdl, argv[0]); ret = netmgr_save_config(hdl); if (ret != 0) { amp_debug(MOD_STR, "netmgr get state failed"); goto out; } out: return JS_NewInt32(ctx, ret); } static JSValue native_netmgr_get_config(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; //TODO out: return JS_NewInt32(ctx, ret); } static JSValue native_netmgr_del_config(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; //TODO out: return JS_NewInt32(ctx, ret); } /***************************************************************************** * Function: native_netmgr_set_ifconfig * Description: js native addon for NETMGR.setIconfig() * Called by: js api * Input: no input * Output: return a string object to js api,if it is NULL means can't get *ip *****************************************************************************/ static JSValue native_netmgr_set_ifconfig(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; netmgr_hdl_t hdl; netmgr_ifconfig_info_t info = {0}; char *ip_addr = NULL; char *mask = NULL; char *gw = NULL; char *dns_server = NULL; char *mac = NULL; if (!JS_IsNumber(argv[0]) || !JS_IsObject(argv[1])) { amp_warn(MOD_STR, "parameter must be number and object\n"); goto out; } JS_ToInt32(ctx, &hdl, argv[0]); /* get device certificate */ info.dhcp_en = QUICKJS_GET_PROPERTY_BOOL(ctx, argv[1], "dhcp_en"); ip_addr = QUICKJS_GET_PROPERTY_STR(ctx, argv[1], "ip_addr"); mask = QUICKJS_GET_PROPERTY_STR(ctx, argv[1], "mask"); gw = QUICKJS_GET_PROPERTY_STR(ctx, argv[1], "gw"); dns_server = QUICKJS_GET_PROPERTY_STR(ctx, argv[1], "dns_server"); mac = QUICKJS_GET_PROPERTY_STR(ctx, argv[1], "mac"); memcpy(info.ip_addr, ip_addr, strlen(ip_addr)); memcpy(info.mask, mask, strlen(mask)); memcpy(info.gw, gw, strlen(gw)); memcpy(info.dns_server, dns_server, strlen(dns_server)); memcpy(info.mac, mac, strlen(mac)); amp_debug(MOD_STR, "info.dhcp_en is %d", info.dhcp_en); amp_debug(MOD_STR, "info.ip_addr is %s", info.ip_addr); amp_debug(MOD_STR, "info.gw is %s", info.gw); ret = netmgr_set_ifconfig(hdl, &info); if (ret != 0) { amp_debug(MOD_STR, "set ifconfig failed"); } out: if (ip_addr != NULL) { JS_FreeCString(ctx, ip_addr); } if (mask != NULL) { JS_FreeCString(ctx, mask); } if (gw != NULL) { JS_FreeCString(ctx, gw); } if (dns_server != NULL) { JS_FreeCString(ctx, dns_server); } if (mac != NULL) { JS_FreeCString(ctx, mac); } return JS_NewInt32(ctx, ret); } /***************************************************************************** * Function: native_netmgr_get_ifconfig * Description: js native addon for NETMGR.getIfconfig() * Called by: js api * Input: no input * Output: return a string object to js api,if it is NULL means can't get *ip *****************************************************************************/ static JSValue native_netmgr_get_ifconfig(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; netmgr_hdl_t hdl; netmgr_ifconfig_info_t info = {0}; JSValue obj = JS_NewObject(ctx); if (!JS_IsNumber(argv[0])) { amp_warn(MOD_STR, "parameter must be number and object\n"); goto out; } JS_ToInt32(ctx, &hdl, argv[0]); ret = netmgr_get_ifconfig(hdl, &info); if (ret != 0) { amp_debug(MOD_STR, "get ifconfig failed"); goto out; } const bool dhcp_en = info.dhcp_en; const char *ip_addr = info.ip_addr; const char *mask = info.mask; const char *gw = info.gw; const char *dns_server = info.dns_server; const char *mac = info.mac; const int rssi = info.rssi; JS_SetPropertyStr(ctx, obj, "dhcp_en", JS_NewInt32(ctx, dhcp_en)); JS_SetPropertyStr(ctx, obj, "ip_addr", JS_NewString(ctx, ip_addr)); JS_SetPropertyStr(ctx, obj, "mask", JS_NewString(ctx, mask)); JS_SetPropertyStr(ctx, obj, "gw", JS_NewString(ctx, gw)); JS_SetPropertyStr(ctx, obj, "dns_server", JS_NewString(ctx, dns_server)); JS_SetPropertyStr(ctx, obj, "mac", JS_NewString(ctx, mac)); JS_SetPropertyStr(ctx, obj, "rssi", JS_NewInt32(ctx, rssi)); out: return obj; } static int set_msg_cb(netmgr_msg_t *msg) { msg_cb_info_t *info; JSContext *ctx = js_get_context(); JSValue args; slist_for_each_entry(&g_msg_cb_list_head, info, msg_cb_info_t, next) { switch (msg->id) { case NETMGR_MSGID_WIFI_STATUS: JS_SetPropertyStr(ctx, args, "msgid", JS_NewInt32(ctx, msg->id)); JS_SetPropertyStr(ctx, args, "data", JS_NewString(ctx, msg->data.network_status_change)); break; case NETMGR_MSGID_WIFI_STATUS_FROM_IMPL: JS_SetPropertyStr(ctx, args, "msgid", JS_NewInt32(ctx, msg->id)); JS_SetPropertyStr(ctx, args, "data", JS_NewString(ctx, msg->data.status)); break; case NETMGR_MSGID_WIFI_TRACE_FROM_IMPL: case NETMGR_MSGID_NETWORK_STATUS: case NETMGR_MSGID_ETH_STATUS_FROM_IMPL: default: return -1; } JSValue val = JS_Call(ctx, info->cb_ref, JS_UNDEFINED, 1, &args); JS_FreeValue(ctx, args); if (JS_IsException(val)) { amp_info(MOD_STR, "netmgr connect callback error"); } JS_FreeValue(ctx, val); } return 0; } static JSValue native_netmgr_set_msg_cb(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { netmgr_hdl_t hdl; int ret = -1; JSValue msg_cb_ref; msg_cb_info_t *info; if (!JS_IsNumber(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be number and function\n"); goto out; } JS_ToInt32(ctx, &hdl, argv[0]); JSValue msg_cb = argv[1]; if (!JS_IsFunction(ctx, msg_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } msg_cb_ref = JS_DupValue(ctx, msg_cb); info = (msg_cb_info_t *)aos_malloc(sizeof(msg_cb_info_t)); if (info != NULL) { if (slist_empty(&g_msg_cb_list_head)) { ret = netmgr_set_msg_cb(hdl, set_msg_cb); } memset(info, 0, sizeof(msg_cb_info_t)); info->cb_ref = msg_cb_ref; slist_add(&(info->next), &g_msg_cb_list_head); ret = 0; } out: return JS_NewInt32(ctx, ret); } static JSValue native_netmgr_del_msg_cb(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { netmgr_hdl_t hdl; msg_cb_info_t *info; JSValue msg_cb_ref; int ret = -1; if (!JS_IsNumber(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be number and object\n"); goto out; } JS_ToInt32(ctx, &hdl, argv[0]); JSValue msg_cb = argv[1]; if (!JS_IsFunction(ctx, msg_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } slist_for_each_entry(&g_msg_cb_list_head, info, msg_cb_info_t, next) { if (JS_VALUE_GET_PTR(msg_cb) == JS_VALUE_GET_PTR(info->cb_ref)) { slist_del(&(info->next), &g_msg_cb_list_head); ret = 0; aos_free(info); JS_FreeValue(ctx, msg_cb); break; } } if (slist_empty(&g_msg_cb_list_head)) { ret = netmgr_del_msg_cb(hdl, set_msg_cb); } out: return JS_NewInt32(ctx, ret); } static void module_netmgr_source_clean(void) { JSContext *ctx = js_get_context(); netmgr_hdl_t hdl; DEV_TYPE dev_type = DEV_INVALID; amp_error(MOD_STR, "module_netmgr_source_clean"); if (get_hdl_type(hdl) == NETMGR_TYPE_WIFI) { dev_type = DEV_WIFI; } else if (get_hdl_type(hdl) == NETMGR_TYPE_ETH) { dev_type = DEV_ETHNET; } else { amp_warn(MOD_STR, "unkown type"); return; } g_checkip_task_run_flag[dev_type] = 0; aos_msleep(CHECKIP_INTERVAL_MS); hdl = netmgr_get_dev(dev_name); netmgr_disconnect(hdl); //netmgr_wifi_deinit(hdl); netmgr_service_deinit(); memset(dev_name, 0, sizeof(dev_name)); amp_debug(MOD_STR, "module_netmgr_register deinit"); } static JSClassDef js_netmgr_class = { "NETMGR", }; static const JSCFunctionListEntry js_netmgr_funcs[] = { JS_CFUNC_DEF("serviceInit", 0, native_netmgr_service_init), JS_CFUNC_DEF("serviceDeinit", 1, native_netmgr_service_deinit), JS_CFUNC_DEF("addDev", 1, native_netmgr_add_dev), JS_CFUNC_DEF("getDev", 1, native_netmgr_get_dev), JS_CFUNC_DEF("setAutoReconnect", 2, native_netmgr_set_auto_reconnect), JS_CFUNC_DEF("connect", 3, native_netmgr_connect), JS_CFUNC_DEF("disconnect", 1, native_netmgr_disconnect), JS_CFUNC_DEF("getState", 1, native_netmgr_get_state), JS_CFUNC_DEF("saveConfig", 1, native_netmgr_save_config), JS_CFUNC_DEF("getConfig", 2, native_netmgr_get_config), JS_CFUNC_DEF("delConfig", 2, native_netmgr_del_config), JS_CFUNC_DEF("setIfConfig", 2, native_netmgr_set_ifconfig), JS_CFUNC_DEF("getIfConfig", 2, native_netmgr_get_ifconfig), JS_CFUNC_DEF("setMsgCb", 2, native_netmgr_set_msg_cb), JS_CFUNC_DEF("delMsgCb", 2, native_netmgr_del_msg_cb) }; static int js_netmgr_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_netmgr_class_id); JS_NewClass(JS_GetRuntime(ctx), js_netmgr_class_id, &js_netmgr_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_netmgr_funcs, countof(js_netmgr_funcs)); JS_SetClassProto(ctx, js_netmgr_class_id, proto); return JS_SetModuleExportList(ctx, m, js_netmgr_funcs, countof(js_netmgr_funcs)); } JSModuleDef *js_init_module_netmgr(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_netmgr_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_netmgr_funcs, countof(js_netmgr_funcs)); return m; } void module_netmgr_register(void) { amp_debug(MOD_STR, "module_netmgr_register"); JSContext *ctx = js_get_context(); amp_module_free_register(module_netmgr_source_clean); js_init_module_netmgr(ctx, "NETMGR"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/network/netmgr/module_netmgr.c
C
apache-2.0
22,271
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "amp_platform.h" #include "amp_defines.h" #include "amp_task.h" #include "amp_memory.h" #include "aos_system.h" #include "aos_tcp.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "TCP" #define MAX_TCP_RECV_LEN 256 #define MAX_TCP_RECV_TIMEOUT 200 typedef struct { int sock_id; char *msg; int msg_len; JSValue js_cb_ref; } tcp_send_param_t; typedef struct { int ret; JSValue js_cb_ref; } tcp_send_notify_param_t; typedef struct { int sock_id; JSValue js_cb_ref; } tcp_recv_param_t; typedef struct { char *host; int port; JSValue js_cb_ref; } tcp_create_param_t; typedef struct { int ret; JSValue js_cb_ref; } tcp_create_notify_param_t; typedef struct { char buf[MAX_TCP_RECV_LEN]; int recv_len; JSValue js_cb_ref; } tcp_recv_notify_param_t; static char g_tcp_close_flag = 0; static char g_tcp_recv_flag = 0; static aos_sem_t g_tcp_close_sem = NULL; static JSClassID js_tcp_class_id; static void tcp_create_notify(void *pdata) { tcp_create_notify_param_t *p = (tcp_create_notify_param_t *)pdata; JSContext *ctx = js_get_context(); JSValue args = JS_NewInt32(ctx, p->ret); JSValue val = JS_Call(ctx, p->js_cb_ref, JS_UNDEFINED, 1, &args); JS_FreeValue(ctx, args); if (JS_IsException(val)) { js_std_dump_error(ctx); } JS_FreeValue(ctx, val); JS_FreeValue(ctx, p->js_cb_ref); amp_free(p); } static int tcp_create_routine(tcp_create_param_t *create_param) { int ret = -1; JSContext *ctx = js_get_context(); tcp_create_notify_param_t *p = amp_calloc(1, sizeof(tcp_create_notify_param_t)); if (!p) { amp_warn(MOD_STR, "allocate memory failed"); JS_FreeValue(ctx, create_param->js_cb_ref); goto out; } ret = aos_tcp_establish(create_param->host, create_param->port); if (ret < 0) { amp_warn(MOD_STR, "tcp establish failed"); amp_free(p); JS_FreeValue(ctx, create_param->js_cb_ref); goto out; } amp_debug(MOD_STR, "sock_id = %d", ret); p->js_cb_ref = create_param->js_cb_ref; p->ret = ret; amp_task_schedule_call(tcp_create_notify, p); out: JS_FreeCString(ctx, create_param->host); amp_free(create_param); return ret; } /************************************************************************************* * Function: native_udp_create_socket * Description: js native addon for TCP.createSocket(); * Called by: js api * Input: none * Output: return socket fd when create socket success, * return error number when create socket fail **************************************************************************************/ static JSValue native_tcp_create_socket(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int err; int ret = -1; int port = 0; char *host = NULL; tcp_create_param_t *create_param = NULL; amp_debug(MOD_STR, "native_tcp_create_socket"); if (!JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be (object, function)"); goto out; } JSValue j_host = JS_GetPropertyStr(ctx, argv[0], "host"); host = JS_ToCString(ctx, j_host); JS_FreeValue(ctx, j_host); JSValue j_port = JS_GetPropertyStr(ctx, argv[0], "port"); JS_ToInt32(ctx, &port, j_port); JS_FreeValue(ctx, j_port); amp_debug(MOD_STR, "host: %s, port: %d", host, port); create_param = (tcp_create_param_t *)amp_malloc(sizeof(*create_param)); if (!create_param) { amp_error(MOD_STR, "allocate memory failed"); JS_FreeCString(ctx, host); goto out; } create_param->host = host; create_param->port = port; create_param->js_cb_ref = JS_DupValue(ctx, argv[1]); ret = tcp_create_routine(create_param); if (ret < 0) { amp_warn(MOD_STR, "tcp create socket failed"); goto out; } out: return JS_NewInt32(ctx, ret); } static void tcp_send_notify(void *pdata) { tcp_send_notify_param_t *p = (tcp_send_notify_param_t *)pdata; JSContext *ctx = js_get_context(); JSValue args = JS_NewInt32(ctx, p->ret); JSValue val = JS_Call(ctx, p->js_cb_ref, JS_UNDEFINED, 1, &args); if (JS_IsException(val)) { js_std_dump_error(ctx); } JS_FreeValue(ctx, args); JS_FreeValue(ctx, val); JS_FreeValue(ctx, p->js_cb_ref); amp_free(p); } /************************************************************************************* * Function: udp_send_routin * Description: create a task for blocking sendto call * Called by: **************************************************************************************/ static int tcp_send_routine(tcp_send_param_t *send_param) { JSContext *ctx = js_get_context(); int sock_id = send_param->sock_id; int ret = aos_tcp_write(sock_id, send_param->msg, send_param->msg_len, 0); if (ret < 0) { JS_FreeValue(ctx, send_param->js_cb_ref); goto out; } tcp_send_notify_param_t *p = amp_calloc(1, sizeof(tcp_send_notify_param_t)); if (!p) { amp_warn(MOD_STR, "allocate memory failed"); JS_FreeValue(ctx, send_param->js_cb_ref); goto out; } p->js_cb_ref = send_param->js_cb_ref; p->ret = ret; amp_task_schedule_call(tcp_send_notify, p); ret = 0; out: JS_FreeCString(ctx, send_param->msg); amp_free(send_param); return ret; } /************************************************************************************* * Function: native_udp_sendto * Description: js native addon for *TCP.send(sock_id,option,buffer_array,function(ret){}) Called by: js api * Input: sock_id: interger * options: is a object include options.ip and options.port * buffer_array: is a array which include message to send * function(ret): is the callback function which has a ret input *param Output: return send msg length when send success return error *number when send fail **************************************************************************************/ static JSValue native_tcp_send(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int sock_id; int i; int msg_len; char *msg; if (!JS_IsNumber(argv[0]) || !JS_IsString(argv[1]) || !JS_IsFunction(ctx, argv[2])) { amp_warn(MOD_STR, "parameter must be (number, string, function)"); goto out; } JS_ToInt32(ctx, &sock_id, argv[0]); if (sock_id <= 0) { amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id); goto out; } msg = JS_ToCString(ctx, argv[1]); msg_len = strlen(msg); amp_debug(MOD_STR, "msg is:%s, length is: %d", msg, msg_len); tcp_send_param_t *send_param = (tcp_send_param_t *)amp_malloc(sizeof(*send_param)); if (!send_param) { amp_error(MOD_STR, "allocate memory failed"); JS_FreeCString(ctx, msg); goto out; } send_param->sock_id = sock_id; send_param->msg = msg; send_param->msg_len = msg_len; send_param->js_cb_ref = JS_DupValue(ctx, argv[2]); tcp_send_routine(send_param); out: return JS_NewInt32(ctx, ret); } static void tcp_recv_notify(void *pdata) { int i = 0; tcp_recv_notify_param_t *p = (tcp_recv_notify_param_t *)pdata; JSContext *ctx = js_get_context(); JSValue args[2]; args[0] = JS_NewInt32(ctx, p->recv_len); args[1] = JS_NewStringLen(ctx, p->buf, p->recv_len); JSValue val = JS_Call(ctx, p->js_cb_ref, JS_UNDEFINED, 2, args); JS_FreeValue(ctx, args[0]); JS_FreeValue(ctx, args[1]); if (JS_IsException(val)) { js_std_dump_error(ctx); } JS_FreeValue(ctx, val); } /************************************************************************************* * Function: udp_recv_routine * Description: create a task for blocking recvfrom call * Called by: **************************************************************************************/ static void tcp_recv_routine(void *arg) { tcp_recv_param_t *recv_param = (tcp_recv_param_t *)arg; int sock_id; JSContext *ctx = js_get_context(); g_tcp_recv_flag = 1; sock_id = recv_param->sock_id; tcp_recv_notify_param_t *p = amp_calloc(1, sizeof(*p)); if (!p) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } p->js_cb_ref = recv_param->js_cb_ref; while (1) { p->recv_len = aos_tcp_read(sock_id, p->buf, sizeof(p->buf), MAX_TCP_RECV_TIMEOUT); if (p->recv_len > 0) { amp_task_schedule_call(tcp_recv_notify, p); } if (p->recv_len < 0) { amp_warn(MOD_STR, "connection closed: %d", p->recv_len); break; } if (g_tcp_close_flag) { amp_warn(MOD_STR, "close tcp connect"); break; } } aos_tcp_destroy(sock_id); out: JS_FreeValue(ctx, recv_param->js_cb_ref); amp_free(recv_param); if (p) amp_free(p); g_tcp_recv_flag = 0; aos_sem_signal(&g_tcp_close_sem); aos_task_exit(0); return; } /************************************************************************************* * Function: native_udp_recvfrom * Description: js native addon for * TCP.recv(sock_id,function(length, buffer_array, src_ip, *src_port){}) Called by: js api Input: sock_id: interger * function(length, buffer_array, src_ip, src_port): the callback *function length: the recv msg length buffer_array: the recv msg buffer src_ip: *the peer ip string src_port: the peer port which is a interger * * Output: return 0 when TCP.recv call ok * return error number TCP.recv call fail **************************************************************************************/ static JSValue native_tcp_receive(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int sock_id = 0; aos_task_t tcp_recv_task; tcp_recv_param_t *recv_param; if (!JS_IsNumber(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be number and function"); goto out; } JS_ToInt32(ctx, &sock_id, argv[0]); if (sock_id < 0) { amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id); goto out; } amp_debug(MOD_STR, "sock_id: %d", sock_id); recv_param = (tcp_recv_param_t *)amp_calloc(1, sizeof(*recv_param)); if (!recv_param) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } recv_param->sock_id = sock_id; recv_param->js_cb_ref = JS_DupValue(ctx, argv[1]); ret = aos_task_new_ext(&tcp_recv_task, "amp_tcp_recv_task", tcp_recv_routine, recv_param, 1024 * 4, ADDON_TSK_PRIORRITY); if (ret != 0) { amp_warn(MOD_STR, "tcp recv task error"); goto out; } out: return JS_NewInt32(ctx, ret); } /************************************************************************************* * Function: native_tcp_close * Description: js native addon for * TCP.close(sock_id) * Called by: js api * Input: sock_id: interger * * Output: return 0 when TCP.close call ok * return error number TCP.close call fail **************************************************************************************/ static JSValue native_tcp_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int sock_id = 0; if ((argc < 1) || (!JS_IsNumber(argv[0]))) { amp_warn(MOD_STR, "parameter must be number"); goto out; } JS_ToInt32(ctx, &sock_id, argv[0]); if (sock_id <= 0) { amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id); goto out; } g_tcp_close_flag = 1; aos_sem_wait(&g_tcp_close_sem, MAX_TCP_RECV_TIMEOUT + 50); g_tcp_close_flag = 0; ret = 0; out: return JS_NewInt32(ctx, ret); } static void module_tcp_source_clean(void) { if (g_tcp_recv_flag) { g_tcp_close_flag = 1; aos_sem_wait(&g_tcp_close_sem, MAX_TCP_RECV_TIMEOUT + 50); g_tcp_close_flag = 0; } } static JSClassDef js_tcp_class = { "TCP", }; static const JSCFunctionListEntry js_tcp_funcs[] = { JS_CFUNC_DEF("createSocket", 2, native_tcp_create_socket), JS_CFUNC_DEF("send", 3, native_tcp_send), JS_CFUNC_DEF("recv", 2, native_tcp_receive), JS_CFUNC_DEF("close", 1, native_tcp_close) }; static int js_tcp_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_tcp_class_id); JS_NewClass(JS_GetRuntime(ctx), js_tcp_class_id, &js_tcp_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_tcp_funcs, countof(js_tcp_funcs)); JS_SetClassProto(ctx, js_tcp_class_id, proto); return JS_SetModuleExportList(ctx, m, js_tcp_funcs, countof(js_tcp_funcs)); } JSModuleDef *js_init_module_tcp(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_tcp_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_tcp_funcs, countof(js_tcp_funcs)); return m; } void module_tcp_register(void) { amp_debug(MOD_STR, "module_tcp_register"); JSContext *ctx = js_get_context(); if (!g_tcp_close_sem) { if (aos_sem_new(&g_tcp_close_sem, 0) != 0) { amp_error(MOD_STR, "create tcp sem fail"); return; } } amp_module_free_register(module_tcp_source_clean); js_init_module_tcp(ctx, "TCP"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/network/tcp/module_tcp.c
C
apache-2.0
13,822
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_config.h" #include "amp_platform.h" #include "aos_system.h" #include "amp_utils.h" #include "amp_task.h" #include "amp_defines.h" #include "aos_udp.h" #include "quickjs.h" #include "quickjs_addon_common.h" #ifndef INET_ADDRSTRLEN #define INET_ADDRSTRLEN 16 #endif #define MOD_STR "UDP" #define MAX_UDP_RECV_LEN 256 #define MAX_UDP_RECV_TIMEOUT 200 typedef struct { char ip[INET_ADDRSTRLEN]; int port; char *msg; } udp_options_t; typedef struct { int sock_id; char *msg; int msg_len; udp_options_t options; JSValue js_cb_ref; } udp_send_param_t; typedef struct { int ret; JSValue js_cb_ref; } udp_send_notify_param_t; typedef struct { int sock_id; udp_options_t options; JSValue js_cb_ref; } udp_recv_param_t; typedef struct { char buf[MAX_UDP_RECV_LEN]; int recv_len; char src_ip[INET_ADDRSTRLEN]; unsigned short src_port; JSValue js_cb_ref; } udp_recv_notify_param_t; /* udp socket close request flag*/ static char volatile g_udp_close_flag = 0; static char g_udp_recv_flag = 0; static aos_sem_t g_udp_close_sem = NULL; static JSClassID js_udp_class_id; /************************************************************************************* * Function: native_udp_create_socket * Description: js native addon for UDP.createSocket(); * Called by: js api * Input: none * Output: return socket fd when create socket success, * return error number when create socket fail **************************************************************************************/ static JSValue native_udp_create_socket(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int sock_id = 0; sock_id = aos_udp_socket_create(); if (sock_id < 0) { amp_warn(MOD_STR, "create socket error!"); goto out; } amp_debug(MOD_STR, "sock_id = %d", sock_id); out: return JS_NewInt32(ctx, sock_id); } /************************************************************************************* * Function: native_udp_bind * Description: js native addon for UDP.bind(sock_id,"ip",port) * Called by: js api * Input: UDP.bind(sock_id,"ip",port): * sock_id: is a iterger * ip: is a ip stirng like "192.168.1.1" * port: is a iterger port * Output: return 0 when bind successed * return error number when bind fail **************************************************************************************/ static JSValue native_udp_bind(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int port = 0; int sock_id; if (!JS_IsNumber(argv[0]) || !JS_IsNumber(argv[1])) { amp_warn(MOD_STR, "parameter must be (number, number)"); goto out; } JS_ToInt32(ctx, &sock_id, argv[0]); if (sock_id < 0) { amp_error(MOD_STR, "socket id[%d] error", sock_id); goto out; } JS_ToInt32(ctx, &port, argv[1]); if (port < 0) { amp_error(MOD_STR, "port[%d] error", port); goto out; } amp_debug(MOD_STR, "udp bind socket id=%d, port=%d", sock_id, port); ret = aos_udp_socket_bind(sock_id, port); if (ret < 0) { amp_error(MOD_STR, "udp bind error"); goto out; } out: return JS_NewInt32(ctx, ret); } static void udp_send_notify(void *pdata) { udp_send_notify_param_t *notify = (udp_send_notify_param_t *)pdata; JSContext *ctx = js_get_context(); JSValue args; args = JS_NewInt32(ctx, notify->ret); JSValue val = JS_Call(ctx, notify->js_cb_ref, JS_UNDEFINED, 1, &args); if (JS_IsException(val)) { js_std_dump_error(ctx); amp_error(MOD_STR, "udp_send_notify, call error"); } JS_FreeValue(ctx, args); JS_FreeValue(ctx, val); JS_FreeValue(ctx, notify->js_cb_ref); amp_free(notify); } /************************************************************************************* * Function: udp_send_routin * Description: create a task for blocking sendto call * Called by: **************************************************************************************/ static int udp_send_routine(udp_send_param_t *send_param) { int ret = -1; int sock_id; udp_options_t udp_options; udp_send_notify_param_t *p; JSContext *ctx = js_get_context(); sock_id = send_param->sock_id; ret = aos_udp_sendto(sock_id, &(send_param->options), send_param->msg, send_param->msg_len, 0); p = amp_calloc(1, sizeof(udp_send_notify_param_t)); if (!p) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } p->js_cb_ref = send_param->js_cb_ref; p->ret = ret; amp_task_schedule_call(udp_send_notify, p); ret = 0; out: amp_free(send_param->msg); amp_free(send_param); return ret; } /************************************************************************************* * Function: native_udp_sendto * Description: js native addon for *UDP.send(sock_id,option,buffer_array,function(ret){}) Called by: js api * Input: sock_id: interger * options: is a object include options.ip and options.port * buffer_array: is a array which include message to send * function(ret): is the callback function which has a ret input *param Output: return send msg length when send success return error *number when send fail **************************************************************************************/ static JSValue native_udp_sendto(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; udp_options_t options; int sock_id; int i; int msg_len; char *msg; const char *buf; char *str; if (!JS_IsNumber(argv[0]) || !JS_IsObject(argv[1]) || !JS_IsFunction(ctx, argv[2])) { amp_warn(MOD_STR, "parameter must be (number, string, function)"); goto out; } JS_ToInt32(ctx, &sock_id, argv[0]); if (sock_id <= 0) { amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id); goto out; } memset(&options, 0, sizeof(udp_options_t)); /* options.port */ JSValue j_port = JS_GetPropertyStr(ctx, argv[1], "port"); if (JS_IsException(j_port) || JS_IsUndefined(j_port)) { amp_warn(MOD_STR, "port not specify"); goto out; } JS_ToInt32(ctx, &options.port, j_port); JS_FreeValue(ctx, j_port); /* options.address */ JSValue j_host = JS_GetPropertyStr(ctx, argv[1], "address"); if (JS_IsException(j_host) || JS_IsUndefined(j_host)) { amp_warn(MOD_STR, "ip not specify"); goto out; } str = JS_ToCString(ctx, j_host); memset(options.ip, 0, INET_ADDRSTRLEN); memcpy(options.ip, str, strlen(str)); JS_FreeValue(ctx, j_host); /* options.message */ JSValue j_message = JS_GetPropertyStr(ctx, argv[1], "message"); if (JS_IsException(j_message) || JS_IsUndefined(j_message)) { amp_warn(MOD_STR, "message not specify"); goto out; } if (JS_IsString(j_message)) { buf = JS_ToCString(ctx, j_message); msg_len = strlen(buf); } else { buf = JS_GetArrayBuffer(ctx, &msg_len, j_message); if (!buf) { amp_warn(MOD_STR, "parameter buffer is invalid, size: %d", msg_len); goto out; } } msg = (char *)amp_malloc(msg_len + 1); if (!msg) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } memcpy(msg, buf, msg_len); msg[msg_len] = 0; if (JS_IsString(j_message)) { JS_FreeCString(ctx, buf); } else { JS_FreeValue(ctx, buf); } amp_debug(MOD_STR, "msg is:%s, length is: %d", msg, msg_len); udp_send_param_t *send_param = (udp_send_param_t *)amp_malloc(sizeof(*send_param)); if (!send_param) { amp_error(MOD_STR, "allocate memory failed"); amp_free(msg); goto out; } send_param->sock_id = sock_id; send_param->js_cb_ref = JS_DupValue(ctx, argv[2]); send_param->msg = msg; send_param->msg_len = msg_len; memcpy(&(send_param->options), &options, sizeof(udp_options_t)); amp_debug(MOD_STR, "sockid:%d ip:%s port:%d msg:%s msg_len:%d", sock_id, options.ip, options.port, msg, msg_len); udp_send_routine(send_param); out: return JS_NewInt32(ctx, ret); } static void udp_recv_notify(void *pdata) { int i = 0; udp_recv_notify_param_t *notify = (udp_recv_notify_param_t *)pdata; JSContext *ctx = js_get_context(); JSValue args[3]; JSValue host, port; if (notify->recv_len > 0) { args[0] = JS_NewArrayBufferCopy(ctx, notify->buf, notify->recv_len); args[1] = JS_NewObject(ctx); host = JS_NewStringLen(ctx, notify->src_ip, INET_ADDRSTRLEN); port = JS_NewInt32(ctx, notify->src_port); JS_SetPropertyStr(ctx, args[1], "host", host); JS_SetPropertyStr(ctx, args[1], "port", port); } args[2] = JS_NewInt32(ctx, notify->recv_len); JSValue val = JS_Call(ctx, notify->js_cb_ref, JS_UNDEFINED, 3, args); JS_FreeValue(ctx, args[2]); if (notify->recv_len > 0) { JS_FreeValue(ctx, port); JS_FreeCString(ctx, host); JS_FreeValue(ctx, args[0]); JS_FreeValue(ctx, args[1]); } if (JS_IsException(val)) { js_std_dump_error(ctx); amp_error(MOD_STR, "udp_send_notify, call error"); } JS_FreeValue(ctx, val); } /************************************************************************************* * Function: udp_recv_routine * Description: create a task for blocking recvfrom call * Called by: **************************************************************************************/ static void udp_recv_routine(void *arg) { udp_recv_param_t *recv_param = (udp_recv_param_t *)arg; int sock_id; aos_networkAddr addr_info; udp_recv_notify_param_t *p; JSContext *ctx = js_get_context(); sock_id = recv_param->sock_id; p = amp_calloc(1, sizeof(udp_recv_notify_param_t)); if (!p) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } g_udp_recv_flag = 1; while (1) { p->recv_len = aos_udp_recvfrom(sock_id, &addr_info, p->buf, sizeof(p->buf), MAX_UDP_RECV_TIMEOUT); if (p->recv_len > 0) { memcpy(p->src_ip, addr_info.addr, INET_ADDRSTRLEN); p->src_port = addr_info.port; p->js_cb_ref = recv_param->js_cb_ref; amp_task_schedule_call(udp_recv_notify, p); } if (p->recv_len < 0) { // connection closed amp_error(MOD_STR, "connection closed:%d", p->recv_len); break; } if (g_udp_close_flag) { amp_warn(MOD_STR, "close udp connect"); break; } } aos_udp_close_without_connect(sock_id); out: JS_FreeValue(ctx, recv_param->js_cb_ref); amp_free(recv_param); if (p) { amp_free(p); } g_udp_recv_flag = 0; aos_sem_signal(&g_udp_close_sem); aos_task_exit(0); return; } /************************************************************************************* * Function: native_udp_recvfrom * Description: js native addon for * UDP.recv(sock_id,function(length, buffer_array, src_ip, *src_port){}) Called by: js api Input: sock_id: interger * function(length, buffer_array, src_ip, src_port): the callback *function length: the recv msg length buffer_array: the recv msg buffer src_ip: *the peer ip string src_port: the peer port which is a interger * * Output: return 0 when UDP.recv call ok * return error number UDP.recv call fail **************************************************************************************/ static JSValue native_udp_recvfrom(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int sock_id = 0; aos_task_t udp_recv_task; udp_recv_param_t *recv_param; if (!JS_IsNumber(argv[0]) || !JS_IsFunction(ctx, argv[1])) { amp_warn(MOD_STR, "parameter must be number and function"); goto out; } JS_ToInt32(ctx, &sock_id, argv[0]); if (sock_id < 0) { amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id); goto out; } amp_debug(MOD_STR, "sock_id: %d", sock_id); recv_param = (udp_recv_param_t *)amp_calloc(1, sizeof(*recv_param)); if (!recv_param) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } recv_param->sock_id = sock_id; recv_param->js_cb_ref = JS_DupValue(ctx, argv[1]); ret = aos_task_new_ext(&udp_recv_task, "amp udp recv task", udp_recv_routine, recv_param, 1024 * 4, ADDON_TSK_PRIORRITY); if (ret != 0) { amp_debug(MOD_STR, "udp recv task create faild"); goto out; } out: return JS_NewInt32(ctx, ret); } /************************************************************************************* * Function: native_udp_close_socket * Description: js native addon for * UDP.close(sock_id) * Called by: js api * Input: sock_id: interger * * Output: return 0 when UDP.close call ok * return error number UDP.close call fail **************************************************************************************/ static JSValue native_udp_close_socket(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int sock_id = 0; if ((argc < 1) || (!JS_IsNumber(argv[0]))) { amp_warn(MOD_STR, "parameter must be number"); goto out; } JS_ToInt32(ctx, &sock_id, argv[0]); if (sock_id <= 0) { amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id); goto out; } g_udp_close_flag = 1; aos_sem_wait(&g_udp_close_sem, MAX_UDP_RECV_TIMEOUT + 50); g_udp_close_flag = 0; ret = 0; out: return JS_NewInt32(ctx, ret); } static void module_udp_source_clean(void) { if (g_udp_recv_flag) { g_udp_close_flag = 1; aos_sem_wait(&g_udp_close_sem, MAX_UDP_RECV_TIMEOUT + 50); g_udp_close_flag = 0; } } static JSClassDef js_udp_class = { "UDP", }; static const JSCFunctionListEntry js_udp_funcs[] = { JS_CFUNC_DEF("createSocket", 0, native_udp_create_socket), JS_CFUNC_DEF("bind", 2, native_udp_bind), JS_CFUNC_DEF("sendto", 3, native_udp_sendto), JS_CFUNC_DEF("recvfrom", 2, native_udp_recvfrom), JS_CFUNC_DEF("close", 1, native_udp_close_socket) }; static int js_udp_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_udp_class); JS_NewClass(JS_GetRuntime(ctx), js_udp_class_id, &js_udp_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_udp_funcs, countof(js_udp_funcs)); JS_SetClassProto(ctx, js_udp_class_id, proto); return JS_SetModuleExportList(ctx, m, js_udp_funcs, countof(js_udp_funcs)); } JSModuleDef *js_init_module_udp(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_udp_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_udp_funcs, countof(js_udp_funcs)); return m; } void module_udp_register(void) { amp_debug(MOD_STR, "module_udp_register"); JSContext *ctx = js_get_context(); if (!g_udp_close_sem) { if (aos_sem_new(&g_udp_close_sem, 0) != 0) { amp_error(MOD_STR, "create udp sem fail"); return; } } amp_module_free_register(module_udp_source_clean); js_init_module_udp(ctx, "UDP"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/network/udp/module_udp.c
C
apache-2.0
15,773
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited * * SPDX-License-Identifier: Apache-2.0 * */ #ifndef __AMP_REPL_H #define __AMP_REPL_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #ifdef JSE_HW_ADDON_GPIO void module_gpio_register(void); #endif #ifdef JSE_HW_ADDON_IR void module_ir_register(void); #endif #ifdef JSE_HW_ADDON_PWM void module_pwm_register(void); #endif #ifdef JSE_HW_ADDON_ONEWIRE void module_onewire_register(void); #endif #ifdef JSE_HW_ADDON_RTC void module_rtc_register(void); #endif #ifdef JSE_CORE_ADDON_CRYPTO void module_crypto_register(void); #endif #ifdef JSE_HW_ADDON_WDG void module_wdg_register(void); #endif #ifdef JSE_HW_ADDON_UART void module_uart_register(void); #endif #ifdef JSE_HW_ADDON_SPI void module_spi_register(void); #endif #ifdef JSE_HW_ADDON_ADC void module_adc_register(void); #endif #ifdef JSE_HW_ADDON_TIMER void module_timer_register(void); #endif #ifdef JSE_HW_ADDON_DAC void module_dac_register(void); #endif #ifdef JSE_CORE_ADDON_SYSTIMER void module_systimer_register(void); #endif #ifdef JSE_NET_ADDON_HTTP void module_http_register(void); #endif #ifdef JSE_NET_ADDON_NETMGR void module_netmgr_register(void); #endif #ifdef JSE_CORE_ADDON_SYSTEM void module_system_register(void); #endif #ifdef JSE_ADVANCED_ADDON_OTA void module_app_ota_register(void); #endif #ifdef JSE_ADVANCED_ADDON_UI void page_entry_register(void); void app_entry_register(void); void module_ui_register(void); #endif #ifdef JSE_HW_ADDON_LCD void module_lcd_register(void); #endif #ifdef JSE_HW_ADDON_I2C void module_i2c_register(void); #endif #ifdef JSE_ADVANCED_ADDON_AIOT_DEVICE void module_aiot_device_register(void); #endif #ifdef JSE_ADVANCED_ADDON_AIOT_GATEWAY void module_aiot_gateway_register(void); #endif #ifdef JSE_CORE_ADDON_LOG void module_log_register(void); #endif #ifdef JSE_WIRELESS_ADDON_BT_HOST void module_bt_host_register(void); #endif #ifdef JSE_CORE_ADDON_FS void module_fs_register(void); #endif #ifdef JSE_CORE_ADDON_KV void module_kv_register(void); #endif #ifdef JSE_ADVANCED_ADDON_AUDIOPLAYER void module_audioplayer_register(void); #endif #ifdef JSE_ADVANCED_ADDON_BLECFGNET void module_blecfgnet_register(void); #endif #ifdef __cplusplus } #endif #endif /* __AMP_REPL_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/quickjs_addon.h
C
apache-2.0
2,293
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ /* #define LOG_NDEBUG 0 */ #include <stdint.h> #include "amp_config.h" #include "amp_defines.h" #include "amp_task.h" #include "repl.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "aos_system.h" #define MOD_STR "MODULE_REPL" static JSClassID js_repl_class_id; extern JSContext *js_get_context(void); static uint16_t repl_init_flag = 0; static uint16_t repl_js_cb_flag = 0; static JSValue repl_js_cb_ref = JS_UNDEFINED; static aos_sem_t g_repl_close_sem = NULL; static JSValue native_repl_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { aos_repl_init(NULL); return JS_NewInt32(ctx, 0); } static JSValue native_repl_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = 0; repl_init_flag = 0; aos_sem_wait(&g_repl_close_sem, AOS_WAIT_FOREVER); ret = aos_repl_close(); return JS_NewInt32(ctx, ret); } static JSValue native_repl_puts(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int i = 0; char *msg = NULL; size_t msg_len = 0; JSValue val; const char *buf; if(argc < 1) { amp_warn(MOD_STR, "parameter must be array"); goto out; } if(JS_IsString(argv[0])) { buf = JS_ToCString(ctx, argv[0]); msg_len = strlen(buf); i = 1; } else { buf = JS_GetArrayBuffer(ctx, &msg_len, argv[0]); if(!buf) { amp_warn(MOD_STR, "parameter buffer is invalid, size: %d", msg_len); goto out; } } msg = (char *)aos_malloc(msg_len + 1); if (!msg) { amp_warn(MOD_STR, "allocate memory failed"); goto out; } memcpy(msg, buf, msg_len); msg[msg_len] = 0; ret = aos_repl_write(msg); if (-1 == ret) { amp_error(MOD_STR, "native_repl_write fail!"); } aos_free(msg); out: if(i == 1) { JS_FreeCString(ctx, buf); } return JS_NewInt32(ctx, ret); } static JSValue native_repl_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint32_t max_len = 16; uint32_t recvsize = 0; uint64_t pos, len; size_t size; size_t ret; uint8_t *buf; if (JS_ToIndex(ctx, &pos, argv[1])) return JS_EXCEPTION; if (JS_ToIndex(ctx, &len, argv[2])) return JS_EXCEPTION; buf = JS_GetArrayBuffer(ctx, &size, argv[0]); if (!buf) return JS_EXCEPTION; if ((uint32_t)pos + (uint32_t)len > size) return JS_ThrowRangeError(ctx, "read/write array buffer overflow"); ret = aos_repl_read(buf + (uint32_t)pos, (uint32_t)len, &recvsize); return JS_NewInt32(ctx, ret); } static void repl_read_notify(void *arg) { JSContext *ctx = js_get_context(); if (repl_init_flag) { JSValue val = JS_Call(ctx, repl_js_cb_ref, JS_UNDEFINED, 0, NULL); JS_FreeValue(ctx, val); } } static void repl_task_entry() { aos_printf("repl task begin\n"); while (repl_init_flag) { if(repl_js_cb_flag == 1) { amp_task_schedule_call(repl_read_notify, NULL); } aos_msleep(100); } aos_printf("repl task exited\n"); aos_sem_signal(&g_repl_close_sem); aos_task_exit(0); } void repl_read_task_start(void) { aos_task_t repl_task; if (!repl_init_flag) { repl_init_flag = 1; aos_task_new_ext(&repl_task, "amp repl task", repl_task_entry, NULL, 1024 * 4, AOS_DEFAULT_APP_PRI); } } static JSValue native_repl_setReadHandler(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSValue read_cb = argv[0]; if (!JS_IsFunction(ctx, read_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } repl_js_cb_ref = JS_DupValue(ctx, read_cb); repl_js_cb_flag = 1; return JS_NewInt32(ctx, 0); } static void module_repl_source_clean(void) { JSContext *ctx = js_get_context(); if (repl_js_cb_flag) { JS_FreeValue(ctx, repl_js_cb_ref); } } static JSClassDef js_repl_class = { "REPL", }; static const JSCFunctionListEntry js_repl_funcs[] = { JS_CFUNC_DEF("open", 1, native_repl_open), JS_CFUNC_DEF("read", 0, native_repl_read ), JS_CFUNC_DEF("puts", 1, native_repl_puts ), JS_CFUNC_DEF("exit", 0, native_repl_close ), JS_CFUNC_DEF("setReadHandler", 1, native_repl_setReadHandler ) }; static int js_repl_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_repl_class_id); JS_NewClass(JS_GetRuntime(ctx), js_repl_class_id, &js_repl_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_repl_funcs, countof(js_repl_funcs)); JS_SetClassProto(ctx, js_repl_class_id, proto); return JS_SetModuleExportList(ctx, m, js_repl_funcs, countof(js_repl_funcs)); } JSModuleDef *js_init_module_repl(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_repl_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_repl_funcs, countof(js_repl_funcs)); return m; } void module_repl_register(void) { amp_debug(MOD_STR, "module_repl_register\n"); JSContext *ctx = js_get_context(); if (!g_repl_close_sem) { if (aos_sem_new(&g_repl_close_sem, 0) != 0) { amp_error(MOD_STR, "create repl sem fail"); return; } } amp_module_free_register(module_repl_source_clean); js_init_module_repl(ctx, "REPL"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/repl/module_repl.c
C
apache-2.0
5,748
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <stdarg.h> #include <string.h> #include "amp_config.h" #include "aos_system.h" #include "amp_task.h" #include "amp_defines.h" #include "aos_hal_uart.h" #include "quickjs.h" #include "repl.h" #ifdef AOS_COMP_CLI #include "aos/cli.h" #endif #define MOD_STR "REPL" int g_repl_config = 0; static uart_dev_t g_repl_uart; static char g_repl_tag[64] = {0}; static uint8_t g_repl_tag_len = 0; static char repl_message[REPL_OUTBUF_SIZE] = {0}; int aos_repl_read(char *inbuf, uint32_t expected_length, uint32_t *recv_size) { int32_t ret = REPL_OK; ret = aos_hal_uart_recv_II(&g_repl_uart, inbuf, expected_length, recv_size, 100); if (ret == 0) { return *recv_size; } else { return 0; } } static int32_t repl_putstr(char *msg) { if (msg[0] != 0) { aos_hal_uart_send(&g_repl_uart, (void *)msg, strlen(msg), 0xFFFFFFFFU); } return REPL_OK; } int32_t repl_printf(const char *buffer, ...) { va_list ap; int32_t sz, len; char *pos = NULL; memset(repl_message, 0, REPL_OUTBUF_SIZE); sz = 0; if (g_repl_tag_len > 0) { len = strlen(g_repl_tag); strncpy(repl_message, g_repl_tag, len); sz = len; } pos = repl_message + sz; va_start(ap, buffer); len = vsnprintf(pos, REPL_OUTBUF_SIZE - sz, buffer, ap); va_end(ap); if (len <= 0) { return REPL_OK; } len = strlen(repl_message); repl_putstr(repl_message); if(repl_message[len-1] == '\n') { repl_putstr("\r"); } return REPL_OK; } int aos_repl_write(char *str) { repl_printf("%s", str); return 0; } static int32_t repl_init(void) { g_repl_uart.port = AMP_REPL_UART_PORT; g_repl_uart.config.baud_rate = AMP_REPL_UART_BAUDRATE; g_repl_uart.config.data_width = DATA_WIDTH_8BIT; g_repl_uart.config.flow_control = FLOW_CONTROL_DISABLED; g_repl_uart.config.mode = MODE_TX_RX; g_repl_uart.config.parity = NO_PARITY; g_repl_uart.config.stop_bits = STOP_BITS_1; aos_hal_uart_init(&g_repl_uart); repl_read_task_start(); amp_debug(MOD_STR, "REPL Enabled\r\n"); return 0; } void aos_repl_init(void *arg) { #ifdef AOS_COMP_CLI repl_printf("cli suspend\n"); aos_cli_suspend(); repl_printf("repl init\r\n"); #endif repl_init(); return ; } int32_t aos_repl_close() { #ifdef AOS_COMP_CLI repl_printf("cli resume\n"); aos_cli_resume(); #endif return 0; } #ifdef AOS_COMP_CLI void jsrepl_startup() { aos_task_t repl_task; aos_task_new_ext(&repl_task, "amp init task", aos_repl_init, NULL, 1024 * 4, AOS_DEFAULT_APP_PRI); } /* reg args: fun, cmd, description*/ ALIOS_CLI_CMD_REGISTER(jsrepl_startup, jsrepl, "start js amp repl") #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/repl/repl.c
C
apache-2.0
2,872
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef __AMP_REPL_H #define __AMP_REPL_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define REPL_OK 0 #define REPL_ERR_NOMEM -10000 #define REPL_ERR_DENIED -10001 #define REPL_ERR_INVALID -10002 #define REPL_ERR_BADCMD -10003 #define REPL_ERR_SYNTAX -10004 /* repl task stack size */ #ifndef AMP_REPL_STACK_SIZE #define REPL_STACK_SIZE 1024*4 #else #define REPL_STACK_SIZE AMP_REPL_STACK_SIZE #endif #define REPL_INBUF_SIZE 256 #define REPL_OUTBUF_SIZE 1024 int32_t repl_printf(const char *buffer, ...); int aos_repl_read(char *inbuf, uint32_t expected_length, uint32_t *recv_size); int aos_repl_write(char *str); void repl_read_task_start(void); void aos_repl_init(void *arg); #ifdef __cplusplus } #endif #endif /* __AMP_REPL_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/repl/repl.h
C
apache-2.0
822
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "amp_platform.h" #include "aos/kernel.h" #include "aos/vfs.h" #include "aos_fs.h" #include "amp_config.h" #include "amp_defines.h" #include "aos_system.h" #include "aos_fs.h" #include "board_mgr.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "BUILTIN" #define GLOBAL_APPCONFIG_STRING_1 "Object.defineProperty(this, 'appConfig', { value: " #define GLOBAL_APPCONFIG_STRING_2 ", writable: true, configurable: true, enumerable: true});" /* export appConfig */ static void native_add_global_appconfig(JSContext *ctx) { char json_dir[128] = {0}; char *json = NULL; void *json_data = NULL; uint32_t len = 0; uint32_t global_config_len = 0; int json_fd = -1; snprintf(json_dir, sizeof(json_dir), AMP_APP_MAIN_JSON); if ((json_fd = aos_open(json_dir, O_RDONLY)) < 0) { amp_error(MOD_STR, "open:%s fail", json_dir); return; } len = aos_lseek(json_fd, 0, SEEK_END); global_config_len = len + strlen(GLOBAL_APPCONFIG_STRING_1) + strlen(GLOBAL_APPCONFIG_STRING_2) + 1; if ((json_data = aos_calloc(1, global_config_len)) == NULL) { aos_close(json_fd); amp_error(MOD_STR, "memory overflow"); return; } aos_lseek(json_fd, 0, SEEK_SET); strncpy(json_data, GLOBAL_APPCONFIG_STRING_1, global_config_len); aos_read(json_fd, json_data + strlen(GLOBAL_APPCONFIG_STRING_1), len); strcpy(json_data + strlen(GLOBAL_APPCONFIG_STRING_1) + len, GLOBAL_APPCONFIG_STRING_2); JSValue val = JS_Eval(ctx, json_data, strlen(json_data), "appconfig", JS_EVAL_TYPE_GLOBAL); if (JS_IsException(val)) { aos_printf("global.createInstance eval jsbundle exec error\n"); qjs_std_dump_error(ctx); } JS_FreeValue(ctx, val); amp_debug(MOD_STR, "export appConfig"); aos_close(json_fd); aos_free(json_data); } void module_builtin_register(void) { amp_debug(MOD_STR, "module_builtin_register"); JSContext *ctx = js_get_context(); /* export appConfig */ native_add_global_appconfig(ctx); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/builtin/module_builtin.c
C
apache-2.0
2,227
/* aes_decrypt.c - TinyCrypt implementation of AES decryption procedure */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/aes.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> static const uint8_t inv_sbox[256] = { 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k) { return tc_aes128_set_encrypt_key(s, k); } #define mult8(a)(_double_byte(_double_byte(_double_byte(a)))) #define mult9(a)(mult8(a)^(a)) #define multb(a)(mult8(a)^_double_byte(a)^(a)) #define multd(a)(mult8(a)^_double_byte(_double_byte(a))^(a)) #define multe(a)(mult8(a)^_double_byte(_double_byte(a))^_double_byte(a)) static inline void mult_row_column(uint8_t *out, const uint8_t *in) { out[0] = multe(in[0]) ^ multb(in[1]) ^ multd(in[2]) ^ mult9(in[3]); out[1] = mult9(in[0]) ^ multe(in[1]) ^ multb(in[2]) ^ multd(in[3]); out[2] = multd(in[0]) ^ mult9(in[1]) ^ multe(in[2]) ^ multb(in[3]); out[3] = multb(in[0]) ^ multd(in[1]) ^ mult9(in[2]) ^ multe(in[3]); } static inline void inv_mix_columns(uint8_t *s) { uint8_t t[Nb*Nk]; mult_row_column(t, s); mult_row_column(&t[Nb], s+Nb); mult_row_column(&t[2*Nb], s+(2*Nb)); mult_row_column(&t[3*Nb], s+(3*Nb)); (void)_copy(s, sizeof(t), t, sizeof(t)); } static inline void add_round_key(uint8_t *s, const unsigned int *k) { s[0] ^= (uint8_t)(k[0] >> 24); s[1] ^= (uint8_t)(k[0] >> 16); s[2] ^= (uint8_t)(k[0] >> 8); s[3] ^= (uint8_t)(k[0]); s[4] ^= (uint8_t)(k[1] >> 24); s[5] ^= (uint8_t)(k[1] >> 16); s[6] ^= (uint8_t)(k[1] >> 8); s[7] ^= (uint8_t)(k[1]); s[8] ^= (uint8_t)(k[2] >> 24); s[9] ^= (uint8_t)(k[2] >> 16); s[10] ^= (uint8_t)(k[2] >> 8); s[11] ^= (uint8_t)(k[2]); s[12] ^= (uint8_t)(k[3] >> 24); s[13] ^= (uint8_t)(k[3] >> 16); s[14] ^= (uint8_t)(k[3] >> 8); s[15] ^= (uint8_t)(k[3]); } static inline void inv_sub_bytes(uint8_t *s) { unsigned int i; for (i = 0; i < (Nb*Nk); ++i) { s[i] = inv_sbox[s[i]]; } } /* * This inv_shift_rows also implements the matrix flip required for * inv_mix_columns, but performs it here to reduce the number of memory * operations. */ static inline void inv_shift_rows(uint8_t *s) { uint8_t t[Nb*Nk]; t[0] = s[0]; t[1] = s[13]; t[2] = s[10]; t[3] = s[7]; t[4] = s[4]; t[5] = s[1]; t[6] = s[14]; t[7] = s[11]; t[8] = s[8]; t[9] = s[5]; t[10] = s[2]; t[11] = s[15]; t[12] = s[12]; t[13] = s[9]; t[14] = s[6]; t[15] = s[3]; (void)_copy(s, sizeof(t), t, sizeof(t)); } int tc_aes_decrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) { uint8_t state[Nk*Nb]; unsigned int i; if (out == (uint8_t *) 0) { return TC_CRYPTO_FAIL; } else if (in == (const uint8_t *) 0) { return TC_CRYPTO_FAIL; } else if (s == (TCAesKeySched_t) 0) { return TC_CRYPTO_FAIL; } (void)_copy(state, sizeof(state), in, sizeof(state)); add_round_key(state, s->words + Nb*Nr); for (i = Nr - 1; i > 0; --i) { inv_shift_rows(state); inv_sub_bytes(state); add_round_key(state, s->words + Nb*i); inv_mix_columns(state); } inv_shift_rows(state); inv_sub_bytes(state); add_round_key(state, s->words); (void)_copy(out, sizeof(state), state, sizeof(state)); /*zeroing out the state buffer */ _set(state, TC_ZERO_BYTE, sizeof(state)); return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/aes_decrypt.c
C
apache-2.0
6,348
/* aes_encrypt.c - TinyCrypt implementation of AES encryption procedure */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/aes.h> #include <tinycrypt/utils.h> #include <tinycrypt/constants.h> static const uint8_t sbox[256] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; static inline unsigned int rotword(unsigned int a) { return (((a) >> 24)|((a) << 8)); } #define subbyte(a, o)(sbox[((a) >> (o))&0xff] << (o)) #define subword(a)(subbyte(a, 24)|subbyte(a, 16)|subbyte(a, 8)|subbyte(a, 0)) int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k) { const unsigned int rconst[11] = { 0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000 }; unsigned int i; unsigned int t; if (s == (TCAesKeySched_t) 0) { return TC_CRYPTO_FAIL; } else if (k == (const uint8_t *) 0) { return TC_CRYPTO_FAIL; } for (i = 0; i < Nk; ++i) { s->words[i] = (k[Nb*i]<<24) | (k[Nb*i+1]<<16) | (k[Nb*i+2]<<8) | (k[Nb*i+3]); } for (; i < (Nb * (Nr + 1)); ++i) { t = s->words[i-1]; if ((i % Nk) == 0) { t = subword(rotword(t)) ^ rconst[i/Nk]; } s->words[i] = s->words[i-Nk] ^ t; } return TC_CRYPTO_SUCCESS; } static inline void add_round_key(uint8_t *s, const unsigned int *k) { s[0] ^= (uint8_t)(k[0] >> 24); s[1] ^= (uint8_t)(k[0] >> 16); s[2] ^= (uint8_t)(k[0] >> 8); s[3] ^= (uint8_t)(k[0]); s[4] ^= (uint8_t)(k[1] >> 24); s[5] ^= (uint8_t)(k[1] >> 16); s[6] ^= (uint8_t)(k[1] >> 8); s[7] ^= (uint8_t)(k[1]); s[8] ^= (uint8_t)(k[2] >> 24); s[9] ^= (uint8_t)(k[2] >> 16); s[10] ^= (uint8_t)(k[2] >> 8); s[11] ^= (uint8_t)(k[2]); s[12] ^= (uint8_t)(k[3] >> 24); s[13] ^= (uint8_t)(k[3] >> 16); s[14] ^= (uint8_t)(k[3] >> 8); s[15] ^= (uint8_t)(k[3]); } static inline void sub_bytes(uint8_t *s) { unsigned int i; for (i = 0; i < (Nb * Nk); ++i) { s[i] = sbox[s[i]]; } } #define triple(a)(_double_byte(a)^(a)) static inline void mult_row_column(uint8_t *out, const uint8_t *in) { out[0] = _double_byte(in[0]) ^ triple(in[1]) ^ in[2] ^ in[3]; out[1] = in[0] ^ _double_byte(in[1]) ^ triple(in[2]) ^ in[3]; out[2] = in[0] ^ in[1] ^ _double_byte(in[2]) ^ triple(in[3]); out[3] = triple(in[0]) ^ in[1] ^ in[2] ^ _double_byte(in[3]); } static inline void mix_columns(uint8_t *s) { uint8_t t[Nb*Nk]; mult_row_column(t, s); mult_row_column(&t[Nb], s+Nb); mult_row_column(&t[2 * Nb], s + (2 * Nb)); mult_row_column(&t[3 * Nb], s + (3 * Nb)); (void) _copy(s, sizeof(t), t, sizeof(t)); } /* * This shift_rows also implements the matrix flip required for mix_columns, but * performs it here to reduce the number of memory operations. */ static inline void shift_rows(uint8_t *s) { uint8_t t[Nb * Nk]; t[0] = s[0]; t[1] = s[5]; t[2] = s[10]; t[3] = s[15]; t[4] = s[4]; t[5] = s[9]; t[6] = s[14]; t[7] = s[3]; t[8] = s[8]; t[9] = s[13]; t[10] = s[2]; t[11] = s[7]; t[12] = s[12]; t[13] = s[1]; t[14] = s[6]; t[15] = s[11]; (void) _copy(s, sizeof(t), t, sizeof(t)); } int tc_aes_encrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) { uint8_t state[Nk*Nb]; unsigned int i; if (out == (uint8_t *) 0) { return TC_CRYPTO_FAIL; } else if (in == (const uint8_t *) 0) { return TC_CRYPTO_FAIL; } else if (s == (TCAesKeySched_t) 0) { return TC_CRYPTO_FAIL; } (void)_copy(state, sizeof(state), in, sizeof(state)); add_round_key(state, s->words); for (i = 0; i < (Nr - 1); ++i) { sub_bytes(state); shift_rows(state); mix_columns(state); add_round_key(state, s->words + Nb*(i+1)); } sub_bytes(state); shift_rows(state); add_round_key(state, s->words + Nb*(i+1)); (void)_copy(out, sizeof(state), state, sizeof(state)); /* zeroing out the state buffer */ _set(state, TC_ZERO_BYTE, sizeof(state)); return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/aes_encrypt.c
C
apache-2.0
6,897
/* cbc_mode.c - TinyCrypt implementation of CBC mode encryption & decryption */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/cbc_mode.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> int utils_tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched) { uint8_t buffer[TC_AES_BLOCK_SIZE]; unsigned int n, m; /* input sanity check: */ if (out == (uint8_t *) 0 || in == (const uint8_t *) 0 || sched == (TCAesKeySched_t) 0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 || outlen != inlen + TC_AES_BLOCK_SIZE) { return TC_CRYPTO_FAIL; } /* copy iv to the buffer */ (void)_copy(buffer, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE); /* copy iv to the output buffer */ (void)_copy(out, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE); out += TC_AES_BLOCK_SIZE; for (n = m = 0; n < inlen; ++n) { buffer[m++] ^= *in++; if (m == TC_AES_BLOCK_SIZE) { (void)tc_aes_encrypt(buffer, buffer, sched); (void)_copy(out, TC_AES_BLOCK_SIZE, buffer, TC_AES_BLOCK_SIZE); out += TC_AES_BLOCK_SIZE; m = 0; } } return TC_CRYPTO_SUCCESS; } int utils_tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched) { uint8_t buffer[TC_AES_BLOCK_SIZE]; const uint8_t *p; unsigned int n, m; /* sanity check the inputs */ if (out == (uint8_t *) 0 || in == (const uint8_t *) 0 || sched == (TCAesKeySched_t) 0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 || outlen != inlen) { return TC_CRYPTO_FAIL; } /* * Note that in == iv + ciphertext, i.e. the iv and the ciphertext are * contiguous. This allows for a very efficient decryption algorithm * that would not otherwise be possible. */ p = iv; for (n = m = 0; n < inlen; ++n) { if ((n % TC_AES_BLOCK_SIZE) == 0) { (void)tc_aes_decrypt(buffer, in, sched); in += TC_AES_BLOCK_SIZE; m = 0; } *out++ = buffer[m++] ^ *p++; } return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/cbc_mode.c
C
apache-2.0
3,816
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "stdio.h" #include "stdint.h" #include "stdbool.h" #include "string.h" #include "crypto_adapter.h" #include "tinycrypt/aes.h" #include "tinycrypt/constants.h" #include "tinycrypt/cbc_mode.h" const uint8_t aes_iv[16] = { 0x31, 0x32, 0x33, 0x61, 0x71, 0x77, 0x65, 0x64, 0x23, 0x2a, 0x24, 0x21, 0x28, 0x34, 0x6a, 0x75 }; int crypto_adapter_encrypt_cbc(uint8_t *in, uint16_t inlen, uint8_t *out, uint16_t *outlen, uint8_t *key) { uint8_t *encrypt_buff = NULL; struct tc_aes_key_sched_struct key_sched; uint8_t fill = 16 - (inlen) % 16; uint8_t *fill_buff; int ret; uint16_t enc_len; fill_buff = (uint8_t *)aos_malloc(inlen + fill); if (fill_buff == NULL) { return -1; } memcpy(fill_buff, in, inlen); for (int i = 0; i < fill; i++) { fill_buff[inlen + i] = fill; } enc_len = inlen+fill; encrypt_buff = (uint8_t *)aos_malloc(enc_len + TC_AES_BLOCK_SIZE); if (encrypt_buff == NULL) { aos_free(fill_buff); return -1; } if (key != NULL) { (void)tc_aes128_set_encrypt_key(&key_sched, key); } ret = utils_tc_cbc_mode_encrypt(encrypt_buff, enc_len + TC_AES_BLOCK_SIZE, fill_buff, enc_len, aes_iv, &key_sched); aos_free(fill_buff); if (ret != TC_CRYPTO_SUCCESS) { aos_free(encrypt_buff); return -1; } if (out != NULL) { memcpy(out, encrypt_buff + TC_AES_BLOCK_SIZE, enc_len); } aos_free(encrypt_buff); if (outlen) { *outlen = enc_len; } return 0; } uint8_t *crypto_adapter_decrypt_cbc(const uint8_t *in, uint16_t inlen, uint8_t *out, uint16_t *out_len, uint8_t *key) { uint8_t fill; uint8_t *encrypt_data; struct tc_aes_key_sched_struct key_sched; int ret; if (key != NULL) { (void)tc_aes128_set_encrypt_key(&key_sched, key); } encrypt_data = (uint8_t *)aos_malloc(inlen + TC_AES_BLOCK_SIZE); if (encrypt_data == NULL) { return -1; } // TinyCrypt CBC decryption assumes that the iv and the ciphertext are contiguous memcpy(encrypt_data, aes_iv, TC_AES_BLOCK_SIZE); memcpy(encrypt_data + TC_AES_BLOCK_SIZE, in, inlen); ret = utils_tc_cbc_mode_decrypt(out, inlen, encrypt_data+TC_AES_BLOCK_SIZE, inlen, encrypt_data, &key_sched); aos_free(encrypt_data); if (ret != TC_CRYPTO_SUCCESS) { return -1; } fill = out[inlen - 1]; *out_len = inlen - fill; return 0; } int crypto_adapter_encrypt(Encrypt_mode mode, uint8_t *in, uint16_t inlen, uint8_t *out, uint16_t *outlen, uint8_t *key) { switch (mode) { case Encrypt_mode_AES_CBC: return crypto_adapter_encrypt_cbc(in, inlen, out, outlen, key); break; default: break; } return -1; } int crypto_adapter_decrypt(Encrypt_mode mode, uint8_t *in, uint16_t inlen, uint8_t *out, uint16_t *outlen, uint8_t *key) { switch (mode) { case Encrypt_mode_AES_CBC: return crypto_adapter_decrypt_cbc(in, inlen, out, outlen, key); break; default: break; } return -1; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/crypto_adapter.c
C
apache-2.0
3,313
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef _CRYPTO_ADAPTER_ #define _CRYPTO_ADAPTER_ #define ENC_KEY_SIZE 16 typedef enum{ Encrypt_mode_AES_CBC, Encrypt_mode_AES_CCM, }Encrypt_mode; #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/crypto_adapter.h
C
apache-2.0
252
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "amp_config.h" #include "amp_defines.h" #include "amp_utils.h" //#include "be_inl.h" #include "mbedtls/md5.h" #include "quickjs.h" #include "crypto_adapter.h" #include "quickjs_addon_common.h" #define MOD_STR "CRYPTO" #define DEBUG_HEX_DUMP(str, buff, len) hexdump(str, buff, len) // #define DEBUG_HEX_DUMP(str, buff, len) static JSClassID js_crypto_class_id; #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif static int crypto_char2hex(char c, char *x) { if (c >= '0' && c <= '9') { *x = c - '0'; } else if (c >= 'a' && c <= 'f') { *x = c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { *x = c - 'A' + 10; } else { return -1; } return 0; } static int crypto_hex2bin(char *hex, uint8_t *buf) { char dec; int hexlen, i; hexlen = strlen(hex); if (hexlen == 0) { return 0; } /* if hexlen is uneven, return failed */ if (hexlen % 2) { return 0; } /* regular hex conversion */ for (i = 0; i < hexlen/2; i++) { if (crypto_char2hex(hex[2 * i], &dec) < 0) { return 0; } buf[i] = dec << 4; if (crypto_char2hex(hex[2 * i + 1], &dec) < 0) { return 0; } buf[i] += dec; } return hexlen/2; } static int crypto_bin2hex(char *hex, uint8_t *buf, uint8_t buf_len) { int i; if (hex == NULL) return 0; hex[0] = 0; for (i = 0; i < buf_len; i++) { sprintf(hex+strlen(hex), "%02x", buf[i]); } return buf_len*2; } static JSValue native_crypto_encrypt(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char *crypt_mode = NULL, *aes_type = NULL, *aes_padding = NULL; char *key = NULL; char *in = NULL; char *out = NULL; unsigned char *out_bin, *in_bin; unsigned char key_bin[ENC_KEY_SIZE]; uint16_t in_length, out_length; int ret; JSValue JSret; JSValue JS_crypt_mode, JS_key, JS_in; JS_crypt_mode = JS_GetPropertyStr(ctx, argv[0], "crypt_mode"); crypt_mode = JS_ToCString(ctx, JS_crypt_mode); if (strcasecmp(crypt_mode, "aes_cbc") != 0) { amp_error(MOD_STR, "not supported crypt_mode: %s", crypt_mode); goto out; /* now just support aes encryption */ } /* input.key */ JS_key = JS_GetPropertyStr(ctx, argv[1], "key"); key = JS_ToCString(ctx, JS_key); if (key == NULL) { amp_warn(MOD_STR, "key not specify"); goto out; } amp_info(MOD_STR, "key is %s", key); crypto_hex2bin(key, key_bin); /* input.in */ JS_in = JS_GetPropertyStr(ctx, argv[1], "in"); in = JS_ToCString(ctx, JS_in); if (in == NULL) { amp_warn(MOD_STR, "in not specify"); goto out; } amp_info(MOD_STR, "in is %s", in); in_length = strlen(in); in_length /= 2; in_bin = aos_malloc(in_length+3); out_bin = aos_malloc(in_length+16); crypto_hex2bin(in, in_bin); ret = crypto_adapter_encrypt(Encrypt_mode_AES_CBC, in_bin, in_length, out_bin, &out_length, key_bin); if (ret != 0) { amp_warn(MOD_STR, "encrypt failed"); aos_free(in_bin); aos_free(out_bin); goto out; } out = aos_malloc(out_length*2+1); crypto_bin2hex(out, out_bin, out_length); amp_info(MOD_STR, "encrypted leng = %d, %s", out_length, out); JSret = JS_NewString(ctx, out); aos_free(out); return JSret; out: return JS_NewString(ctx, ""); } static JSValue native_crypto_decrypt(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char *crypt_mode = NULL, *aes_type = NULL, *aes_padding = NULL; char *key = NULL; char *in = NULL; char *out = NULL; unsigned char *out_bin, *in_bin; unsigned char key_bin[ENC_KEY_SIZE]; uint16_t in_length, out_length; int ret; JSValue JSret; JSValue JS_crypt_mode, JS_key, JS_in; JS_crypt_mode = JS_GetPropertyStr(ctx, argv[0], "crypt_mode"); crypt_mode = JS_ToCString(ctx, JS_crypt_mode); if (strcasecmp(crypt_mode, "aes_cbc") != 0) { amp_error(MOD_STR, "not supprted crypte_mode"); goto out; /* now just support aes encryption */ } /* input.key */ JS_key = JS_GetPropertyStr(ctx, argv[1], "key"); key = JS_ToCString(ctx, JS_key); if (key == NULL) { amp_warn(MOD_STR, "key not specify"); goto out; } amp_info(MOD_STR, "key is %s", key); crypto_hex2bin(key, key_bin); /* input.in */ JS_in = JS_GetPropertyStr(ctx, argv[1], "in"); in = JS_ToCString(ctx, JS_in); if (in == NULL) { amp_warn(MOD_STR, "in not specify"); goto out; } amp_info(MOD_STR, "in is %s", in); in_length = strlen(in); in_length /= 2; in_bin = aos_malloc(in_length+3); out_bin = aos_malloc(in_length+16); crypto_hex2bin(in, in_bin); ret = crypto_adapter_decrypt(Encrypt_mode_AES_CBC, in_bin, in_length, out_bin, &out_length, key_bin); if (ret != 0) { amp_warn(MOD_STR, "decrypt failed"); aos_free(in_bin); aos_free(out_bin); goto out; } out = aos_malloc(out_length*2+1); crypto_bin2hex(out, out_bin, out_length); amp_info(MOD_STR, "decrypted len = %d, %s", out_length, out); JSret = JS_NewString(ctx, out); aos_free(out); return JSret; out: return JS_NewString(ctx, ""); } static JSClassDef js_crypto_class = { "CRYPTO", }; static const JSCFunctionListEntry js_crypto_funcs[] = { JS_CFUNC_DEF("encrypt", 2, native_crypto_encrypt ), JS_CFUNC_DEF("decrypt", 2, native_crypto_decrypt ), }; static int js_crypto_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_crypto_class_id); JS_NewClass(JS_GetRuntime(ctx), js_crypto_class_id, &js_crypto_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_crypto_funcs, countof(js_crypto_funcs)); JS_SetClassProto(ctx, js_crypto_class_id, proto); return JS_SetModuleExportList(ctx, m, js_crypto_funcs, countof(js_crypto_funcs)); } JSModuleDef *js_init_module_crypto(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_crypto_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_crypto_funcs, countof(js_crypto_funcs)); return m; } void module_crypto_register(void) { amp_debug(MOD_STR, "module_crypto_register"); JSContext *ctx = js_get_context(); aos_printf("module crypto register\n"); js_init_module_crypto(ctx, "CRYPTO"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/module_crypto.c
C
apache-2.0
6,804
/* aes.h - TinyCrypt interface to an AES-128 implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief -- Interface to an AES-128 implementation. * * Overview: AES-128 is a NIST approved block cipher specified in * FIPS 197. Block ciphers are deterministic algorithms that * perform a transformation specified by a symmetric key in fixed- * length data sets, also called blocks. * * Security: AES-128 provides approximately 128 bits of security. * * Usage: 1) call tc_aes128_set_encrypt/decrypt_key to set the key. * * 2) call tc_aes_encrypt/decrypt to process the data. */ #ifndef __TC_AES_H__ #define __TC_AES_H__ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define Nb (4) /* number of columns (32-bit words) comprising the state */ #define Nk (4) /* number of 32-bit words comprising the key */ #define Nr (10) /* number of rounds */ #define TC_AES_BLOCK_SIZE (Nb*Nk) #define TC_AES_KEY_SIZE (Nb*Nk) typedef struct tc_aes_key_sched_struct { unsigned int words[Nb*(Nr+1)]; } *TCAesKeySched_t; /** * @brief Set AES-128 encryption key * Uses key k to initialize s * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: s == NULL or k == NULL * @note This implementation skips the additional steps required for keys * larger than 128 bits, and must not be used for AES-192 or * AES-256 key schedule -- see FIPS 197 for details * @param s IN/OUT -- initialized struct tc_aes_key_sched_struct * @param k IN -- points to the AES key */ int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k); /** * @brief AES-128 Encryption procedure * Encrypts contents of in buffer into out buffer under key; * schedule s * @note Assumes s was initialized by aes_set_encrypt_key; * out and in point to 16 byte buffers * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: out == NULL or in == NULL or s == NULL * @param out IN/OUT -- buffer to receive ciphertext block * @param in IN -- a plaintext block to encrypt * @param s IN -- initialized AES key schedule */ int tc_aes_encrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s); /** * @brief Set the AES-128 decryption key * Uses key k to initialize s * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: s == NULL or k == NULL * @note This is the implementation of the straightforward inverse cipher * using the cipher documented in FIPS-197 figure 12, not the * equivalent inverse cipher presented in Figure 15 * @warning This routine skips the additional steps required for keys larger * than 128, and must not be used for AES-192 or AES-256 key * schedule -- see FIPS 197 for details * @param s IN/OUT -- initialized struct tc_aes_key_sched_struct * @param k IN -- points to the AES key */ int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k); /** * @brief AES-128 Encryption procedure * Decrypts in buffer into out buffer under key schedule s * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: out is NULL or in is NULL or s is NULL * @note Assumes s was initialized by aes_set_encrypt_key * out and in point to 16 byte buffers * @param out IN/OUT -- buffer to receive ciphertext block * @param in IN -- a plaintext block to encrypt * @param s IN -- initialized AES key schedule */ int tc_aes_decrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s); #ifdef __cplusplus } #endif #endif /* __TC_AES_H__ */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/tinycrypt/aes.h
C
apache-2.0
5,330
/* cbc_mode.h - TinyCrypt interface to a CBC mode implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to a CBC mode implementation. * * Overview: CBC (for "cipher block chaining") mode is a NIST approved mode of * operation defined in SP 800-38a. It can be used with any block * cipher to provide confidentiality of strings whose lengths are * multiples of the block_size of the underlying block cipher. * TinyCrypt hard codes AES as the block cipher. * * Security: CBC mode provides data confidentiality given that the maximum * number q of blocks encrypted under a single key satisfies * q < 2^63, which is not a practical constraint (it is considered a * good practice to replace the encryption when q == 2^56). CBC mode * provides NO data integrity. * * CBC mode assumes that the IV value input into the * tc_cbc_mode_encrypt is randomly generated. The TinyCrypt library * provides HMAC-PRNG module, which generates suitable IVs. Other * methods for generating IVs are acceptable, provided that the * values of the IVs generated appear random to any adversary, * including someone with complete knowledge of the system design. * * The randomness property on which CBC mode's security depends is * the unpredictability of the IV. Since it is unpredictable, this * means in practice that CBC mode requires that the IV is stored * somehow with the ciphertext in order to recover the plaintext. * * TinyCrypt CBC encryption prepends the IV to the ciphertext, * because this affords a more efficient (few buffers) decryption. * Hence tc_cbc_mode_encrypt assumes the ciphertext buffer is always * 16 bytes larger than the plaintext buffer. * * Requires: AES-128 * * Usage: 1) call tc_cbc_mode_encrypt to encrypt data. * * 2) call tc_cbc_mode_decrypt to decrypt data. * */ #ifndef __TC_CBC_MODE_H__ #define __TC_CBC_MODE_H__ #include <tinycrypt/aes.h> #ifdef __cplusplus extern "C" { #endif /** * @brief CBC encryption procedure * CBC encrypts inlen bytes of the in buffer into the out buffer * using the encryption key schedule provided, prepends iv to out * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * out == NULL or * in == NULL or * ctr == NULL or * sched == NULL or * inlen == 0 or * (inlen % TC_AES_BLOCK_SIZE) != 0 or * (outlen % TC_AES_BLOCK_SIZE) != 0 or * outlen != inlen + TC_AES_BLOCK_SIZE * @note Assumes: - sched has been configured by aes_set_encrypt_key * - iv contains a 16 byte random string * - out buffer is large enough to hold the ciphertext + iv * - out buffer is a contiguous buffer * - in holds the plaintext and is a contiguous buffer * - inlen gives the number of bytes in the in buffer * @param out IN/OUT -- buffer to receive the ciphertext * @param outlen IN -- length of ciphertext buffer in bytes * @param in IN -- plaintext to encrypt * @param inlen IN -- length of plaintext buffer in bytes * @param iv IN -- the IV for the this encrypt/decrypt * @param sched IN -- AES key schedule for this encrypt */ int utils_tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched); /** * @brief CBC decryption procedure * CBC decrypts inlen bytes of the in buffer into the out buffer * using the provided encryption key schedule * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * out == NULL or * in == NULL or * sched == NULL or * inlen == 0 or * outlen == 0 or * (inlen % TC_AES_BLOCK_SIZE) != 0 or * (outlen % TC_AES_BLOCK_SIZE) != 0 or * outlen != inlen + TC_AES_BLOCK_SIZE * @note Assumes:- in == iv + ciphertext, i.e. the iv and the ciphertext are * contiguous. This allows for a very efficient decryption * algorithm that would not otherwise be possible * - sched was configured by aes_set_decrypt_key * - out buffer is large enough to hold the decrypted plaintext * and is a contiguous buffer * - inlen gives the number of bytes in the in buffer * @param out IN/OUT -- buffer to receive decrypted data * @param outlen IN -- length of plaintext buffer in bytes * @param in IN -- ciphertext to decrypt, including IV * @param inlen IN -- length of ciphertext buffer in bytes * @param iv IN -- the IV for the this encrypt/decrypt * @param sched IN -- AES key schedule for this decrypt * */ int utils_tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched); #ifdef __cplusplus } #endif #endif /* __TC_CBC_MODE_H__ */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/tinycrypt/cbc_mode.h
C
apache-2.0
6,858
/* constants.h - TinyCrypt interface to constants */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief -- Interface to constants. * */ #ifndef __TC_CONSTANTS_H__ #define __TC_CONSTANTS_H__ #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #ifndef NULL #define NULL ((void *)0) #endif #define TC_CRYPTO_SUCCESS 1 #define TC_CRYPTO_FAIL 0 #define TC_ZERO_BYTE 0x00 #ifdef __cplusplus } #endif #endif /* __TC_CONSTANTS_H__ */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/tinycrypt/constants.h
C
apache-2.0
2,024
/* utils.h - TinyCrypt interface to platform-dependent run-time operations */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to platform-dependent run-time operations. * */ #ifndef __TC_UTILS_H__ #define __TC_UTILS_H__ #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /** * @brief Copy the the buffer 'from' to the buffer 'to'. * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * from_len > to_len. * * @param to OUT -- destination buffer * @param to_len IN -- length of destination buffer * @param from IN -- origin buffer * @param from_len IN -- length of origin buffer */ unsigned int _copy(uint8_t *to, unsigned int to_len, const uint8_t *from, unsigned int from_len); /** * @brief Set the value 'val' into the buffer 'to', 'len' times. * * @param to OUT -- destination buffer * @param val IN -- value to be set in 'to' * @param len IN -- number of times the value will be copied */ void _set(void *to, uint8_t val, unsigned int len); /* * @brief AES specific doubling function, which utilizes * the finite field used by AES. * @return Returns a^2 * * @param a IN/OUT -- value to be doubled */ uint8_t _double_byte(uint8_t a); /* * @brief Constant-time algorithm to compare if two sequences of bytes are equal * @return Returns 0 if equal, and non-zero otherwise * * @param a IN -- sequence of bytes a * @param b IN -- sequence of bytes b * @param size IN -- size of sequences a and b */ int _compare(const uint8_t *a, const uint8_t *b, size_t size); #ifdef __cplusplus } #endif #endif /* __TC_UTILS_H__ */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/crypto/tinycrypt/utils.h
C
apache-2.0
3,233
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "aos/kernel.h" #include "aos/vfs.h" #include "aos_system.h" #include "amp_platform.h" #include "amp_config.h" #include "aos_fs.h" #include "amp_defines.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "FS" static JSClassID js_fs_class_id; static int check_fs_is_support() { int ret; int fp; const char *string = "test if fs mount ok"; char testfile[64] = {0}; snprintf(testfile, sizeof(testfile), AMP_FS_ROOT_DIR"/%s", "testfile.txt"); fp = aos_open(testfile, O_RDWR | O_CREAT | O_TRUNC); if (fp < 0) { amp_warn(MOD_STR, "check_fs_is_support open fail\n"); return 0; } ret = aos_write(fp, (char *)string, strlen(string)); if (ret <= 0) { amp_warn(MOD_STR, "check_fs_is_support write fail\n"); aos_close(fp); return 0; } aos_close(fp); ret = aos_remove(testfile); if (ret) { amp_warn(MOD_STR, "check_fs_is_support sync fail\n"); return 0; } return 1; } /***************************************************************************** * Function: native_fs_issupport * Description: js native addon for FILE.issupport() * check if the js FILE object is support * Called by: js api * Input: none * Output: 1 :support ,0 :not support *****************************************************************************/ static JSValue native_fs_is_support(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret; ret = check_fs_is_support(); return JS_NewInt32(ctx, ret); } /***************************************************************************** * Function: native_fs_read * Description: js native addon for FILE.read(filepath) * read the file content * Called by: js api * Input: filepath : string * Output: a String object which the file content is *****************************************************************************/ static JSValue native_fs_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fp = -1; int len = 0; int size = 0; const char *path; char *buf = NULL; JSValue response = JS_UNDEFINED; if (!JS_IsString(argv[0])) { amp_error(MOD_STR, "parameter must be [string]\n"); goto out; } path = JS_ToCString(ctx, argv[0]); if (path == NULL) { amp_error(MOD_STR, "get path fail!"); goto out; } fp = aos_open(path, O_RDONLY); if (fp < 0) { amp_warn(MOD_STR, "aos_open %s failed\n", path); goto out; } size = aos_lseek(fp, 0, HAL_SEEK_END); aos_lseek(fp, 0, HAL_SEEK_SET); buf = (char *)aos_malloc(size + 1); if (!buf) { amp_warn(MOD_STR, "malloc failed\n"); aos_close(fp); goto out; } len = aos_read(fp, buf, size); if (len > 0) { buf[len] = 0; amp_debug(MOD_STR, "read data: %s\n", buf); } aos_close(fp); out: if (path != NULL) { JS_FreeCString(ctx, path); } if (len > 0) { response = JS_NewStringLen(ctx, buf, len); } if (buf != NULL) { aos_free(buf); } return response; } /***************************************************************************** * Function: native_fs_write * Description: js native addon for FILE.write(filepath,buffer,mode) * write the content to the file * Called by: js api * Input: filepath : string ; * buffer: the content buffer which is a String object * mode: could be "w","r","w+","r+","a","a+" * Output: 0 write ok ;other write fail *****************************************************************************/ static JSValue native_fs_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int fp = -1; size_t str_len = 0; size_t nwrite = 0; const char *path; const char *content; const char *flag, *flag_s; JSValue obj; int aos_flag = 0, m = 0; path = JS_ToCString(ctx, argv[0]); if (path == NULL) { amp_error(MOD_STR, "get fs path fail!"); goto out; } content = JS_ToCStringLen(ctx, &str_len, argv[1]); if (content == NULL) { amp_error(MOD_STR, "get fs content fail!"); goto out; } /* get option */ obj = JS_GetPropertyStr(ctx, argv[2], "flag"); if (JS_IsException(obj)) { amp_error(MOD_STR, "Parameter must be an object like {flag: string}"); goto out; } flag = JS_ToCString(ctx, obj); flag_s = flag; if (flag == NULL) { amp_error(MOD_STR, "get fs flag fail!"); goto out; } /* transfor flag to aos_flag */ switch (flag[0]) { case 'r': m = O_RDONLY; aos_flag = 0; break; case 'w': m = O_WRONLY; aos_flag = O_CREAT | O_TRUNC; break; case 'a': m = O_WRONLY; aos_flag = O_CREAT | O_APPEND; break; default: return -1; goto out; } while (*++flag) { switch (*flag) { case '+': m = (m & ~O_ACCMODE) | O_RDWR; break; default: break; } } aos_flag = m | aos_flag; fp = aos_open(path, aos_flag); if (fp < 0) { amp_error(MOD_STR, "be_osal_open fail\n"); goto out; } nwrite = aos_write(fp, (char *)content, str_len); if (nwrite <= 0) { amp_error(MOD_STR, "be_osal_write fail\n"); aos_close(fp); goto out; } amp_debug(MOD_STR, "FS.write(%s,%s,%s);\n", path, content, flag_s); aos_sync(fp); aos_close(fp); ret = (nwrite == str_len) ? 0 : -1; out: if (path != NULL) { JS_FreeCString(ctx, path); } if (content != NULL) { JS_FreeCString(ctx, content); } if (flag_s != NULL) { JS_FreeCString(ctx, flag_s); } return JS_NewInt32(ctx, ret); } /***************************************************************************** * Function: native_fs_delete * Description: js native addon for FILE.delete(filepath) * delete the file * Called by: js api * Input: filepath : string * Output: 0 delete ok ;other delete fail *****************************************************************************/ static JSValue native_fs_delete(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; const char *path; if (!JS_IsString(argv[0])) { amp_warn(MOD_STR, "parameter must be [string]\n"); goto out; } path = JS_ToCString(ctx, argv[0]); if (path == NULL) { amp_error(MOD_STR, "get path fail!"); goto out; } ret = aos_remove(path); out: if (path != NULL) { JS_FreeCString(ctx, path); } return JS_NewInt32(ctx, ret); } /***************************************************************************** * Function: native_fs_totalsize * Description: js native addon for FILE.totalsize() * get file system total size in bytes * Called by: js api * Output: file system total size in bytes; negative if failed. *****************************************************************************/ static JSValue native_fs_totalsize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int size; struct aos_statfs buf; aos_statfs(AMP_FS_ROOT_DIR, &buf); size = buf.f_bsize * buf.f_blocks; if (size < 0) { amp_error(MOD_STR, "get fs totalsize fail"); goto out; } ret = size; out: return JS_NewInt32(ctx, ret); } /***************************************************************************** * Function: native_fs_usedsize * Description: js native addon for FILE.usedsize() * get file system used size in bytes * Called by: js api * Output: file system used size in bytes; negative if failed. *****************************************************************************/ static JSValue native_fs_usedsize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int size; struct aos_statfs buf; aos_statfs(AMP_FS_ROOT_DIR, &buf); size = buf.f_bsize * buf.f_blocks - buf.f_bsize * buf.f_bavail; if (size < 0) { amp_error(MOD_STR, "get fs usedsize fail"); goto out; } ret = size; out: return JS_NewInt32(ctx, ret); } /***************************************************************************** * Function: native_fs_freesize * Description: js native addon for FILE.freesize() * get file system free size in bytes * Called by: js api * Output: file system free size in bytes; negative if failed. *****************************************************************************/ static JSValue native_fs_freesize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int size; struct aos_statfs buf; aos_statfs(AMP_FS_ROOT_DIR, &buf); size = buf.f_bsize * buf.f_bavail; if (size < 0) { amp_error(MOD_STR, "get fs freesize fail"); goto out; } ret = size; out: return JS_NewInt32(ctx, ret); } static JSClassDef js_fs_class = { "FS", }; static const JSCFunctionListEntry js_fs_funcs[] = { JS_CFUNC_DEF("read", 1, native_fs_read), JS_CFUNC_DEF("write", 2, native_fs_write), JS_CFUNC_DEF("delete", 1, native_fs_delete), JS_CFUNC_DEF("totalSize", 1, native_fs_totalsize), JS_CFUNC_DEF("usedSize", 1, native_fs_usedsize), JS_CFUNC_DEF("freeSize", 1, native_fs_freesize), }; static int js_fs_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_fs_class_id); JS_NewClass(JS_GetRuntime(ctx), js_fs_class_id, &js_fs_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_fs_funcs, countof(js_fs_funcs)); JS_SetClassProto(ctx, js_fs_class_id, proto); return JS_SetModuleExportList(ctx, m, js_fs_funcs, countof(js_fs_funcs)); } JSModuleDef *js_init_module_fs(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_fs_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_fs_funcs, countof(js_fs_funcs)); return m; } void module_fs_register(void) { amp_debug(MOD_STR, "module_fs_register"); JSContext *ctx = js_get_context(); aos_printf("module fs register\n"); js_init_module_fs(ctx, "FS"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/fs/module_fs.c
C
apache-2.0
11,041
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_config.h" #include "aos/kv.h" #include "amp_defines.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "aos_system.h" #define MOD_STR "KV" #define KV_BUFFER_MAX_LEN 256 static JSClassID js_kv_class_id; static JSValue native_kv_setStorage(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; int32_t value_len = 0; const char *key = NULL; const char *value = NULL; key = JS_ToCString(ctx, argv[0]); if (key == NULL) { amp_error(MOD_STR, "get kv key fail!"); goto out; } value = JS_ToCString(ctx, argv[1]); if (value == NULL) { amp_error(MOD_STR, "get kv value fail!"); goto out; } value_len = strlen(value); ret = aos_kv_set(key, value, value_len, 1); if (ret != 0) { amp_warn(MOD_STR, "kv set storage failed"); } out: if (key != NULL) { JS_FreeCString(ctx, key); } if (value != NULL) { JS_FreeCString(ctx, value); } return JS_NewInt32(ctx, ret); } static JSValue native_kv_getStorage(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; int32_t value_len = KV_BUFFER_MAX_LEN; const char *key = NULL; char *value = NULL; JSValue obj = JS_UNDEFINED; key = JS_ToCString(ctx, argv[0]); if (key == NULL) { amp_error(MOD_STR, "get kv key fail!"); goto out; } value = (char *)aos_malloc(KV_BUFFER_MAX_LEN); if (value == NULL) { amp_warn(MOD_STR, "allocate memory failed\n"); goto out; } ret = aos_kv_get(key, value, &value_len); if (ret != 0) { amp_warn(MOD_STR, "kv get storage failed"); goto out; } obj = JS_NewStringLen(ctx, value, value_len); out: if (key != NULL) { JS_FreeCString(ctx, key); } if (value != NULL) { aos_free(value); } return obj; } static JSValue native_kv_removeStorage(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; const char *key = NULL; key = JS_ToCString(ctx, argv[0]); if (key == NULL) { amp_error(MOD_STR, "get kv key fail!"); goto out; } ret = aos_kv_del(key); if (ret != 0) { amp_warn(MOD_STR, "kv delete item failed"); } out: if (key != NULL) { JS_FreeCString(ctx, key); } return JS_NewInt32(ctx, ret); } static JSClassDef js_kv_class = { "KV", }; static const JSCFunctionListEntry js_kv_funcs[] = { JS_CFUNC_DEF("setStorageSync", 2, native_kv_setStorage), JS_CFUNC_DEF("getStorageSync", 1, native_kv_getStorage), JS_CFUNC_DEF("removeStorageSync", 1, native_kv_removeStorage), }; static int js_kv_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_kv_class_id); JS_NewClass(JS_GetRuntime(ctx), js_kv_class_id, &js_kv_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_kv_funcs, countof(js_kv_funcs)); JS_SetClassProto(ctx, js_kv_class_id, proto); return JS_SetModuleExportList(ctx, m, js_kv_funcs, countof(js_kv_funcs)); } JSModuleDef *js_init_module_kv(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_kv_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_kv_funcs, countof(js_kv_funcs)); return m; } void module_kv_register(void) { amp_debug(MOD_STR, "module_kv_register"); JSContext *ctx = js_get_context(); aos_printf("module kv register\n"); js_init_module_kv(ctx, "kv"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/kv/module_kv.c
C
apache-2.0
3,864
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "amp_config.h" #include "amp_defines.h" #include "aos_system.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "LOG" #define SCRIPT "JSLOG" #define LOG_LEVEL_DEBUG "debug" #define LOG_LEVEL_INFO "info" #define LOG_LEVEL_WARN "warning" #define LOG_LEVEL_ERROR "error" #define LOG_LEVEL_FATAL "fatal" #define LOG_LEVEL_NONE "none" static JSClassID js_gpio_class_id; static int native_get_log_level(const char *pclevel, aos_log_level_t *paos_log_level) { if (NULL == pclevel || NULL == paos_log_level) { amp_error(MOD_STR, "invalid input\n"); return -1; } if (strncmp(pclevel, LOG_LEVEL_DEBUG, strlen(LOG_LEVEL_DEBUG)) == 0) { *paos_log_level = AOS_LL_DEBUG; } else if (strncmp(pclevel, LOG_LEVEL_INFO, strlen(LOG_LEVEL_INFO)) == 0) { *paos_log_level = AOS_LL_INFO; } else if (strncmp(pclevel, LOG_LEVEL_WARN, strlen(LOG_LEVEL_WARN)) == 0) { *paos_log_level = AOS_LL_WARN; } else if (strncmp(pclevel, LOG_LEVEL_ERROR, strlen(LOG_LEVEL_ERROR)) == 0) { *paos_log_level = AOS_LL_ERROR; } else if (strncmp(pclevel, LOG_LEVEL_FATAL, strlen(LOG_LEVEL_FATAL)) == 0) { *paos_log_level = AOS_LL_FATAL; } else if (strncmp(pclevel, LOG_LEVEL_NONE, strlen(LOG_LEVEL_NONE)) == 0) { *paos_log_level = AOS_LL_NONE; } else { amp_error(MOD_STR, "invalid log level %s", pclevel); return -1; } return 0; } static JSValue native_set_stdlog_level(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = 0; aos_log_level_t log_level; const char *pclevel = JS_ToCString(ctx, argv[0]); if (NULL == pclevel) { amp_warn(MOD_STR, "invalid parameter\n"); return JS_NewInt32(ctx, -1); } ret = native_get_log_level(pclevel, &log_level); if (ret) { amp_warn(MOD_STR, "invalid loglevel %s\n", pclevel); return JS_NewInt32(ctx, -1); } ret = aos_set_log_level(log_level); return JS_NewInt32(ctx, 0); } static JSValue native_set_popcloud_log_level(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = 0; aos_log_level_t log_level; const char *pclevel = JS_ToCString(ctx, argv[0]); if (NULL == pclevel) { amp_warn(MOD_STR, "invalid parameter\n"); return JS_NewInt32(ctx, -1); } ret = native_get_log_level(pclevel, &log_level); if (ret) { amp_warn(MOD_STR, "invalid log level %s\n", pclevel); return JS_NewInt32(ctx, -1); } ret = aos_set_popcloud_log_level(log_level); return JS_NewInt32(ctx, 0); } static JSValue native_set_popfs_log_level(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = 0; aos_log_level_t log_level; const char *pclevel = JS_ToCString(ctx, argv[0]); if (NULL == pclevel) { amp_warn(MOD_STR, "invalid parameter\n"); return JS_NewInt32(ctx, -1); } ret = native_get_log_level(pclevel, &log_level); if (ret) { amp_warn(MOD_STR, "invalid loglevel %s\n", pclevel); return JS_NewInt32(ctx, -1); } ret = aos_set_popfs_log_level(log_level); return JS_NewInt32(ctx, 0); } static JSValue native_set_log_file_path(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = 0; const char *path = JS_ToCString(ctx, argv[0]); if (NULL == path) { amp_warn(MOD_STR, "invalid parameter\n"); return JS_NewInt32(ctx, -1); } ret = ulog_fs_log_file_path(path); if (ret) { amp_warn(MOD_STR, "fail to set log file path %s\n", path); return JS_NewInt32(ctx, -1); } return JS_NewInt32(ctx, 0); } static JSValue native_set_log_file_size(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; unsigned int filesize = 0; if (!JS_IsNumber(argv[0])) { amp_warn(MOD_STR, "parameter must be [number]\n"); return JS_NewInt32(ctx, -1); } JS_ToInt32(ctx, &filesize, argv[0]); /*TODO : limit the biggist file size*/ ret = ulog_fs_log_file_size(filesize); if (ret) { amp_warn(MOD_STR, "fail to set log file size %d\n", filesize); return JS_NewInt32(ctx, -1); } return JS_NewInt32(ctx, 0); } static const char *ulog_get_output_format_msg(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int i; const char *str; size_t len; for(i = 0; i < argc; i++) { str = JS_ToCStringLen(ctx, &len, argv[i]); if (!str) return NULL; JS_FreeCString(ctx, str); } return str; } static JSValue native_debug_log_out(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *msg = ulog_get_output_format_msg(ctx, this_val, argc, argv); if (NULL == msg) { amp_error(MOD_STR, "ulog fail to get output format msg"); return JS_NewInt32(ctx, -1); } ulog(AOS_LL_DEBUG, SCRIPT, NULL, 0, msg); return JS_NewInt32(ctx, 0); } static JSValue native_info_log_out(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *msg = ulog_get_output_format_msg(ctx, this_val, argc, argv); if (NULL == msg) { amp_error(MOD_STR, "ulog fail to get output format msg"); return JS_NewInt32(ctx, -1); } ulog(AOS_LL_INFO, SCRIPT, NULL, 0, msg); return JS_NewInt32(ctx, 0); } static JSValue native_warn_log_out(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *msg = ulog_get_output_format_msg(ctx, this_val, argc, argv); if (NULL == msg) { amp_error(MOD_STR, "ulog fail to get output format msg"); return JS_NewInt32(ctx, -1); } ulog(AOS_LL_WARN, SCRIPT, NULL, 0, msg); return JS_NewInt32(ctx, 0); } static JSValue native_error_log_out(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *msg = ulog_get_output_format_msg(ctx, this_val, argc, argv); if (NULL == msg) { amp_error(MOD_STR, "ulog fail to get output format msg"); return JS_NewInt32(ctx, -1); } ulog(AOS_LL_ERROR, SCRIPT, NULL, 0, msg); return JS_NewInt32(ctx, 0); } static JSValue native_fatal_log_out(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *msg = ulog_get_output_format_msg(ctx, this_val, argc, argv); if (NULL == msg) { amp_error(MOD_STR, "ulog fail to get output format msg"); return JS_NewInt32(ctx, -1); } ulog(AOS_LL_FATAL, SCRIPT, NULL, 0, msg); return JS_NewInt32(ctx, 0); } static JSClassDef js_log_class = { "ulog", }; static const JSCFunctionListEntry js_log_funcs[] = { JS_CFUNC_DEF("debug", 0, native_debug_log_out ), JS_CFUNC_DEF("info", 0, native_info_log_out ), JS_CFUNC_DEF("warn", 0, native_warn_log_out ), JS_CFUNC_DEF("error", 0, native_error_log_out), JS_CFUNC_DEF("fatal", 0, native_fatal_log_out), JS_CFUNC_DEF("stdloglevel", 1, native_set_stdlog_level ), JS_CFUNC_DEF("cloudloglevel", 1, native_set_popcloud_log_level ), JS_CFUNC_DEF("fsloglevel", 1, native_set_popfs_log_level ), JS_CFUNC_DEF("setlogfilepath", 1, native_set_log_file_path ), JS_CFUNC_DEF("setlogfilesize", 1, native_set_log_file_size ), }; static int js_log_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_gpio_class_id); JS_NewClass(JS_GetRuntime(ctx), js_gpio_class_id, &js_log_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_log_funcs, countof(js_log_funcs)); JS_SetClassProto(ctx, js_gpio_class_id, proto); return JS_SetModuleExportList(ctx, m, js_log_funcs, countof(js_log_funcs)); } JSModuleDef *js_init_module_log(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_log_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_log_funcs, countof(js_log_funcs)); return m; } void module_log_register(void) { amp_debug(MOD_STR, "module_log_register"); JSContext *ctx = js_get_context(); js_init_module_log(ctx, "ulog"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/log/module_log.c
C
apache-2.0
8,727
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "amp_config.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" #include "amp_utils.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "SYSTEM" extern const char *aos_userjs_version_get(void); static JSClassID js_system_class_id; static JSValue native_module_versions(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSValue t = JS_NewObject(ctx); const char *version = aos_kernel_version_get(); JS_SetPropertyStr(ctx, t, "module", JS_NewStringLen(ctx, version, strlen(version))); return t; } static JSValue native_system_version(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *version = aos_system_version_get(); return JS_NewStringLen(ctx, version, strlen(version)); } static JSValue native_system_userjs_version(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *version = aos_userjs_version_get(); return JS_NewStringLen(ctx, version, strlen(version)); } static JSValue native_get_system_info(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSValue t = JS_NewObject(ctx); const char *userjs_version = aos_userjs_version_get(); const char *app_version = aos_app_version_get(); const char *kernel_version = aos_kernel_version_get(); const char *system_version = aos_system_version_get(); const char *build_time = aos_system_build_time(); const char *module_hardware = aos_hardware_version_get(); JS_SetPropertyStr(ctx, t, "userjsVersion", JS_NewStringLen(ctx, userjs_version, strlen(userjs_version))); JS_SetPropertyStr(ctx, t, "appVersion", JS_NewStringLen(ctx, app_version, strlen(app_version))); JS_SetPropertyStr(ctx, t, "kernelVersion", JS_NewStringLen(ctx, kernel_version, strlen(kernel_version))); JS_SetPropertyStr(ctx, t, "systemVersion", JS_NewStringLen(ctx, system_version, strlen(system_version))); JS_SetPropertyStr(ctx, t, "buildTime", JS_NewStringLen(ctx, build_time, strlen(build_time))); JS_SetPropertyStr(ctx, t, "hardwareVersion", JS_NewStringLen(ctx, module_hardware, strlen(module_hardware))); return t; } static JSValue native_system_platform(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *p = aos_get_platform_type(); if (strlen(p) == 0) p = "null"; return JS_NewStringLen(ctx, p, strlen(p)); } static JSValue native_system_uptime(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return JS_NewInt64(ctx, aos_now_ms()); } static JSValue native_system_memory(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; amp_heap_info_t heap_info; ret = amp_heap_memory_info(&heap_info); if (ret != 0) { amp_warn(MOD_STR, "get heap memory failed"); goto out; } JSValue t = JS_NewObject(ctx); JS_SetPropertyStr(ctx, t, "heapTotal", JS_NewInt32(ctx, heap_info.heap_total)); JS_SetPropertyStr(ctx, t, "heapUsed", JS_NewInt32(ctx, heap_info.heap_used)); JS_SetPropertyStr(ctx, t, "heapFree", JS_NewInt32(ctx, heap_info.heap_free)); amp_memmgt_mem_show_rec(); return t; out: return JS_NewInt32(ctx, ret); } static JSValue native_system_gc(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return JS_NewInt32(ctx, 1); } static JSValue native_system_reboot(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { aos_printf("system will reboot !!! \n"); aos_reboot(); return JS_NewInt32(ctx, 1); } static JSClassDef js_system_class = { "SYSTEM", }; static int js_system_init(JSContext *ctx) { JSValue proto; JS_NewClassID(&js_system_class_id); JS_NewClass(JS_GetRuntime(ctx), js_system_class_id, &js_system_class); proto = JS_NewObject(ctx); JS_SetClassProto(ctx, js_system_class_id, proto); return 0; } void module_system_register(void) { amp_debug(MOD_STR, "module_system_register"); JSContext *ctx = js_get_context(); aos_printf("module system register\n"); js_system_init(ctx); JSValue global_obj, system; /* XXX: should these global definitions be enumerable? */ global_obj = JS_GetGlobalObject(ctx); system = JS_NewObject(ctx); JS_SetPropertyStr(ctx, system, "versions", JS_NewCFunction(ctx, native_module_versions, "versions", 0)); JS_SetPropertyStr(ctx, system, "version", JS_NewCFunction(ctx, native_system_version, "version", 0)); JS_SetPropertyStr(ctx, system, "appversion", JS_NewCFunction(ctx, native_system_userjs_version, "appversion", 0)); JS_SetPropertyStr(ctx, system, "getSystemInfo", JS_NewCFunction(ctx, native_get_system_info, "getSystemInfo", 0)); JS_SetPropertyStr(ctx, system, "platform", JS_NewCFunction(ctx, native_system_platform, "platform", 0)); JS_SetPropertyStr(ctx, system, "uptime", JS_NewCFunction(ctx, native_system_uptime, "uptime", 0)); JS_SetPropertyStr(ctx, system, "memory", JS_NewCFunction(ctx, native_system_memory, "memory", 0)); JS_SetPropertyStr(ctx, system, "gc", JS_NewCFunction(ctx, native_system_gc, "gc", 0)); JS_SetPropertyStr(ctx, system, "reboot", JS_NewCFunction(ctx, native_system_reboot, "reboot", 0)); JS_SetPropertyStr(ctx, global_obj, "system", system); JS_FreeValue(ctx, global_obj); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/system/module_system.c
C
apache-2.0
6,029
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "amp_config.h" #include "amp_defines.h" #include "aos_system.h" #include "amp_task.h" #include "board_mgr.h" #include "amp_task.h" #include "aos/list.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "SYSTIMER" #define MAGIC 0x55ff0055 typedef struct timer_wrap { int magic; JSValue js_cb_ref; int repeat; aos_timer_t *timer_id; } timer_wrap_t; typedef struct { aos_timer_t *timer_id; timer_wrap_t *t; dlist_t node; void *timer_msg; } timer_link_t; static dlist_t g_systimer_list = AOS_DLIST_HEAD_INIT(g_systimer_list); static JSClassID js_systimer_class_id; static void clear_timer(timer_wrap_t *t); static void timer_action(void *arg) { timer_wrap_t *t = (timer_wrap_t *)arg; JSValue fun = t->js_cb_ref; JSContext *ctx = js_get_context(); /* Is the timer has been cleared? */ if (t->magic != MAGIC) { // amp_error(MOD_STR, "Timer has been cleared"); return; } if (t->repeat) { fun = JS_DupValue(ctx, t->js_cb_ref); } JSValue value = JS_NewInt32(ctx, 0); JSValue val = JS_Call(ctx, fun, JS_UNDEFINED, 1, &value); JS_FreeValue(ctx, value); JS_FreeValue(ctx, val); /* Note when clearInterval is called within the callback function */ if (!t->repeat) { if (t->magic != MAGIC) { amp_warn(MOD_STR, "timer wrap handle has be cleared"); return; } // t->magic = 0; clear_timer(t); } } static timer_wrap_t *setup_timer(JSValue js_cb_ref, long ms, int repeat) { timer_link_t *timer_link; timer_wrap_t *t = (timer_wrap_t *)amp_malloc(sizeof(*t)); void *timer_msg = NULL; t->magic = MAGIC; t->js_cb_ref = js_cb_ref; t->repeat = repeat; t->timer_id = amp_task_timer_action(ms, timer_action, t, repeat, &timer_msg); if (t->timer_id) { timer_link = amp_malloc(sizeof(timer_link_t)); if (timer_link) { timer_link->timer_id = t->timer_id; timer_link->t = t; timer_link->timer_msg = timer_msg; dlist_add_tail(&timer_link->node, &g_systimer_list); } } return t; } static void cancel_timer(void *timerid) { timer_link_t *timer_node; if (!timerid) { return; } dlist_for_each_entry(&g_systimer_list, timer_node, timer_link_t, node) { if (timer_node->timer_id == timerid) { aos_timer_stop((aos_timer_t *)timerid); aos_timer_free((aos_timer_t *)timerid); amp_free((void *)timerid); dlist_del(&timer_node->node); if (timer_node->timer_msg) { amp_free(timer_node->timer_msg); timer_node->timer_msg = NULL; } amp_free(timer_node); timer_node = NULL; break; } } } static void clear_timer(timer_wrap_t *t) { JSContext *ctx = js_get_context(); if (!t) { amp_warn(MOD_STR, "timer wrap handle is null"); return; } if (t->magic != MAGIC) { amp_warn(MOD_STR, "timer wrap handle has be cleared"); return; } JS_FreeValue(ctx, t->js_cb_ref); cancel_timer(t->timer_id); t->magic = 0; amp_free(t); } static JSValue native_setTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { long ms; JSValue irq_cb = argv[0]; if (!JS_IsFunction(ctx, irq_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } JSValue js_cb_ref = JS_DupValue(ctx, irq_cb); JS_ToInt32(ctx, &ms, argv[1]); timer_wrap_t *t = setup_timer(js_cb_ref, ms, 0); JSValue obj; obj = JS_NewObjectClass(ctx, js_systimer_class_id); JS_SetOpaque(obj, (void *)t); return obj; } static JSValue native_clearTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { timer_wrap_t *t = JS_GetOpaque2(ctx, argv[0], js_systimer_class_id); clear_timer(t); return JS_NewInt32(ctx, 0); } static JSValue native_setInterval(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { long ms; JSValue irq_cb = argv[0]; if (!JS_IsFunction(ctx, irq_cb)) { return JS_ThrowTypeError(ctx, "not a function"); } JSValue js_cb_ref = JS_DupValue(ctx, irq_cb); JS_ToInt32(ctx, &ms, argv[1]); timer_wrap_t *t = setup_timer(js_cb_ref, ms, 1); JSValue obj; obj = JS_NewObjectClass(ctx, js_systimer_class_id); JS_SetOpaque(obj, (void *)t); return obj; } static JSValue native_clearInterval(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { timer_wrap_t *t = JS_GetOpaque2(ctx, argv[0], js_systimer_class_id); clear_timer(t); return JS_NewInt32(ctx, 0); } static JSValue native_sleepMs(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int32_t ret = -1; uint32_t ms = 0; JS_ToInt32(ctx, &ms, argv[0]); // amp_debug(MOD_STR, "system delay %d ms", ms); aos_msleep(ms); return JS_NewInt32(ctx, 0); out: return JS_NewInt32(ctx, -1); } static void module_systimer_source_clean(void) { dlist_t *temp; timer_link_t *timer_node; dlist_for_each_entry_safe(&g_systimer_list, temp, timer_node, timer_link_t, node) { clear_timer(timer_node->t); } } static JSClassDef js_systimer_class = { "SYSTIMER", }; static int js_timer_init(JSContext *ctx) { JSValue proto; JS_NewClassID(&js_systimer_class_id); JS_NewClass(JS_GetRuntime(ctx), js_systimer_class_id, &js_systimer_class); proto = JS_NewObject(ctx); JS_SetClassProto(ctx, js_systimer_class_id, proto); return 0; } void module_systimer_register(void) { amp_debug(MOD_STR, "module_systimer_register"); JSContext *ctx = js_get_context(); amp_module_free_register(module_systimer_source_clean); js_timer_init(ctx); QUICKJS_GLOBAL_FUNC("setTimeout", native_setTimeout); QUICKJS_GLOBAL_FUNC("clearTimeout", native_clearTimeout); QUICKJS_GLOBAL_FUNC("setInterval", native_setInterval); QUICKJS_GLOBAL_FUNC("clearInterval", native_clearInterval); QUICKJS_GLOBAL_FUNC("sleepMs", native_sleepMs); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/systimer/module_systimer.c
C
apache-2.0
6,293
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifdef AMP_ADVANCED_ADDON_UI #include "aos_fs.h" #include "aos_system.h" #include "amp_config.h" #include "amp_defines.h" #include "amp_task.h" #include "board_mgr.h" #include "quickjs.h" #include "cJSON.h" #include "app_entry.h" #include "quickjs_addon_common.h" #define MOD_STR "APPENTRY" app_options_t app_options; static JSClassID js_app_entry_class_id; /* App(Object options) entry */ static JSValue native_app_entry(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int i; JSValue irq_cb = argv[0]; /* check paramters */ if (!JS_IsObject(irq_cb)) { return JS_ThrowTypeError(ctx, "not a object"); } memset(&app_options, 0, sizeof(app_options_t)); /* get options object */ app_options.object = JS_DupValue(ctx, irq_cb); /* find globalData */ if (JS_GetPropertyStr(ctx, argv[0], "globalData")) { amp_debug(MOD_STR, "find app#globalData()"); app_options.global_data = JS_DupValue(ctx, irq_cb); } /* find onLaunch() */ if (JS_GetPropertyStr(ctx, argv[0], "onLaunch")) { amp_debug(MOD_STR, "find app#onLaunch()"); app_options.on_launch = JS_DupValue(ctx, irq_cb); } /* find onError() */ if (JS_GetPropertyStr(ctx, argv[0], "onError")) { amp_debug(MOD_STR, "find app#onError()"); app_options.on_error = JS_DupValue(ctx, irq_cb); } /* find onExit() */ if (JS_GetPropertyStr(ctx, argv[0], "onExit")) { amp_debug(MOD_STR, "find app#onExit()"); app_options.on_exit = JS_DupValue(ctx, irq_cb); } amp_task_schedule_call(app_entry, NULL); return 1; /* one return value */ } void app_entry(void *data) { JSContext *ctx = js_get_context(); /* onLaunch hook */ uint32_t value = 0; JSValue val = JS_Call(ctx, app_options.on_launch, JS_UNDEFINED, 1, &value); JS_FreeValue(ctx, val); } static JSClassDef js_app_entry_class = { "APPENTRY", }; static int js_app_entry_init(JSContext *ctx) { JSValue proto; JS_NewClassID(&js_app_entry_class_id); JS_NewClass(JS_GetRuntime(ctx), js_app_entry_class_id, &js_app_entry_class); proto = JS_NewObject(ctx); JS_SetClassProto(ctx, js_app_entry_class_id, proto); return; } void app_entry_register(void) { amp_debug(MOD_STR, "module_app_entry_register"); JSContext *ctx = js_get_context(); aos_printf("module app_entry register\n"); js_app_entry_init(ctx); QUICKJS_GLOBAL_FUNC("App", native_app_entry); } #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/ui/app_entry.c
C
apache-2.0
2,624
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef __APP_ENTRY_H #define __APP_ENTRY_H #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { /* options object */ int object; /* ref of globalData */ int global_data; /* ref of onLaunch() */ int on_launch; /* ref of onError() */ int on_error; /* ref of onExit() */ int on_exit; }app_options_t; extern void app_entry_register(void); extern void app_entry(void* data); #endif /* __APP_ENTRY_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/ui/app_entry.h
C
apache-2.0
527
#ifdef AMP_ADVANCED_ADDON_UI #include "model_bind.h" #define MODEL_BUFF_LEN 256 #define MODEL_STR_HEAD "var model = require('model'); model.setData({" #define MODEL_STR_DELIMITER ":" #define MODEL_STR_TAIL "});" static model_bind_proc_t g_model_bind_proc = {0}; vm_msg_type_e g_msg_type = msg_invalid; int model_data_bind_init(MODEL_DATA_SEND_TO_VM_F send) { if (send == NULL) { amp_error(UI_MOD_STR, "data bind cb is null"); return -1; } g_model_bind_proc.send = send; g_model_bind_proc.flag = true; return 0; } int model_data_bind_deinit(void) { memset(&g_model_bind_proc, 0, sizeof(g_model_bind_proc)); return 0; } int model_data_send_to_vm(vm_msg_t *msg, int len) { if (msg == NULL) { amp_error(UI_MOD_STR, "msg is null"); return -1; } if (len == 0) { amp_error(UI_MOD_STR, "len is %d", len); return -1; } if (g_model_bind_proc.flag != true) { amp_error(UI_MOD_STR, "model bind proc is uninited"); return -1; } if (g_model_bind_proc.send == NULL) { amp_error(UI_MOD_STR, "model bind send cb is null"); return -1; } return g_model_bind_proc.send(msg, len); } JSValue native_model_setdata(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { vm_data_type_t data; vm_msg_t msg; int arr_idx = 0; int len = 0; int i, j; model_array_t *array; widget_desc_t* widget = NULL; page_desc_t *page; if (!JS_IsObject(argv[0])) { amp_error(UI_MOD_STR, "ctx is invalid, %d", ctx); goto done; } duk_enum(ctx, 0 ,0); page = &g_app.page[g_app.cur_page]; if (page == NULL) { goto done; } while (duk_next(ctx, -1, 1)) { if (!duk_is_string(ctx, -2)) { amp_error(UI_MOD_STR, "para name is not string"); duk_pop_2(ctx); continue; } msg.type = msg_model_to_vm; memset(&data, 0, sizeof(data)); if (duk_is_string(ctx, -1)) { data.val_str = duk_safe_to_string(ctx, -1); data.type = vm_data_str; amp_debug(UI_MOD_STR, "para name: %s, str para: %s", duk_safe_to_string(ctx, -2), duk_safe_to_string(ctx, -1)); } else if (duk_is_boolean(ctx, -1)) { data.val_bool = duk_to_boolean(ctx, -1); data.type = vm_data_bool; amp_debug(UI_MOD_STR, "para name: %s, bool para: %d", duk_safe_to_string(ctx, -2), duk_to_boolean(ctx, -1)); } else if (duk_is_number(ctx, -1)) { data.val_double = duk_to_number(ctx, -1); data.type = vm_data_double; amp_debug(UI_MOD_STR, "para name: %s, float para: %f", duk_safe_to_string(ctx, -2), duk_to_boolean(ctx, -1)); } else if (duk_is_array(ctx, -1)) { arr_idx = duk_normalize_index(ctx, -1); len = duk_get_length(ctx, arr_idx); for (i = 0; i < page->total_num; i++) { if(page->widgets[i] == NULL) { continue; } if (page->widgets[i]->array_parent != list_parent) { continue; } if (page->widgets[i]->array == NULL) { continue; } if (widget_str_equal(page->widgets[i]->array->name, duk_safe_to_string(ctx, -2))) { array = page->widgets[i]->array; widget = page->widgets[i]; break; } } if (i == page->total_num) { continue; } for(j = 0; j < array->ele_num; j++) { array->array_len = duk_get_length(ctx, arr_idx); array->element[j].data = aos_malloc(sizeof(vm_data_type_t) * array->array_len); if (array->element[j].data == NULL) { amp_error(UI_MOD_STR, "array->element->data aos_malloc fail,array->array_len = %d", array->array_len); amp_error(UI_MOD_STR, "array->element->data aos_malloc fail,size = %d", sizeof(vm_data_type_t) * array->array_len); goto done; } } for (i = 0; i < len; i++) { duk_get_prop_index(ctx, arr_idx, i); if (!duk_is_object(ctx, -1)) { amp_warn(UI_MOD_STR, "data is not number, index: %d", i); duk_pop(ctx); } else { amp_warn(UI_MOD_STR, "object, index: %d", i); } for (j = 0; j < array->ele_num; j++) { duk_get_prop_string(ctx, -1, array->element[j].name); amp_warn(UI_MOD_STR, "array->element[%d].data[%d].val_str: %s",j, i, duk_safe_to_string(ctx, -1)); if (duk_is_string(ctx, -1)) { array->element[j].data[i].val_str = duk_safe_to_string(ctx, -1); array->element[j].data[i].type = vm_data_str; amp_warn(UI_MOD_STR, "data is not number, array->element[%d].data[%d].val_str: %s",j, i, array->element[j].data[i].val_str); } else if (duk_is_number(ctx, -1)) { array->element[j].data[i].val_double = duk_to_number(ctx, -1); array->element[j].data[i].type = vm_data_double; } duk_pop(ctx); } } msg.type = msg_list_to_vm; //data.type = vm_data_pointer; msg.payload.widget = widget; } else { continue; } msg.payload.name = duk_safe_to_string(ctx, -2); memcpy(&msg.payload.data, &data, sizeof(data)); model_data_send_to_vm(&msg, sizeof(msg)); if (msg_invalid == g_msg_type) { msg.type = msg_on_load_ret; model_data_send_to_vm(&msg, sizeof(msg)); g_msg_type = msg_on_load_ret; } duk_pop_2(ctx); } amp_debug(UI_MOD_STR, "native_model_setdata success"); done: return 1; } int model_eval_str(char *name, vm_data_type_t* data) { JSContext *ctx = NULL; char buffer[MODEL_BUFF_LEN]; if (name == NULL) { amp_error(UI_MOD_STR, "name is null"); return -1; } if (data == NULL) { amp_error(UI_MOD_STR, "name is null"); return -1; } ctx = js_get_context(); switch(data->type) { case vm_data_uint: memset(buffer, 0, sizeof(buffer)); snprintf(buffer, MODEL_BUFF_LEN - 1, "%s%s%s%u%s", MODEL_STR_HEAD, name, MODEL_STR_DELIMITER, data->val_uint, MODEL_STR_TAIL); duk_eval_string(ctx, buffer); amp_debug(UI_MOD_STR, "name: %s, code: %f", name, buffer); break; case vm_data_int: memset(buffer, 0, sizeof(buffer)); snprintf(buffer, MODEL_BUFF_LEN - 1, "%s%s%s%d%s", MODEL_STR_HEAD, name, MODEL_STR_DELIMITER, data->val_int, MODEL_STR_TAIL); duk_eval_string(ctx, buffer); amp_debug(UI_MOD_STR, "name: %s, code: %f", name, buffer); break; case vm_data_double: memset(buffer, 0, sizeof(buffer)); snprintf(buffer, MODEL_BUFF_LEN - 1, "%s%s%s%f%s", MODEL_STR_HEAD, name, MODEL_STR_DELIMITER, data->val_double, MODEL_STR_TAIL); duk_eval_string(ctx, buffer); amp_debug(UI_MOD_STR, "name: %s, code: %f", name, buffer); break; case vm_data_str: memset(buffer, 0, sizeof(buffer)); snprintf(buffer, MODEL_BUFF_LEN - 1, "%s%s%s%s%s", MODEL_STR_HEAD, name, MODEL_STR_DELIMITER, data->val_str, MODEL_STR_TAIL); duk_eval_string(ctx, buffer); amp_debug(UI_MOD_STR, "name: %s, code: %f", name, buffer); break; case vm_data_bool: memset(buffer, 0, sizeof(buffer)); snprintf(buffer, MODEL_BUFF_LEN - 1, "%s%s%s%s%s", MODEL_STR_HEAD, name, MODEL_STR_DELIMITER, data->val_bool == 0 ? "false" : "true", MODEL_STR_TAIL); duk_eval_string(ctx, buffer); amp_debug(UI_MOD_STR, "name: %s, code: %f", name, buffer); break; default : break; } return 0; } #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/ui/model_bind.c
C
apache-2.0
8,511
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifdef AMP_ADVANCED_ADDON_UI #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "aos_system.h" #include "aos_network.h" #include "amp_defines.h" #include "aos_network.h" #include "amp_task.h" #include "quickjs.h" #include "quickjs_addon_common.h" #define MOD_STR "UI" static JSClassID js_ui_class_id; char g_app_path[128]; extern void amp_page_changed_set(void); JSValue native_ui_redirect(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char *path; if (!JS_IsString(argv[0])) { amp_warn(MOD_STR, "invalid parameter\n"); goto done; } path = JS_ToCString(ctx, argv[0]); if (path != NULL) { memset(&g_app_path[0], 0, sizeof(g_app_path)); snprintf(&g_app_path[0],128,"%s",path); amp_page_changed_set(); } amp_debug(MOD_STR, "native_ui_redirect success"); done: return 1; } /* void module_ui_register(void) { JSContext *ctx = js_get_context(); duk_push_object(ctx); duk_push_c_function(ctx, native_ui_redirect, 1); duk_put_prop_string(ctx, -2, "redirectTo"); duk_put_prop_string(ctx, -2, "UI"); } */ static JSClassDef js_vm_class = { "UI", }; static const JSCFunctionListEntry js_ui_funcs[] = { JS_CFUNC_DEF("redirectTo", 1, native_ui_redirect ), }; static int js_ui_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_ui_class_id); JS_NewClass(JS_GetRuntime(ctx), js_ui_class_id, &js_vm_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_ui_funcs, countof(js_ui_funcs)); JS_SetClassProto(ctx, js_ui_class_id, proto); return JS_SetModuleExportList(ctx, m, js_ui_funcs, countof(js_ui_funcs)); } JSModuleDef *js_init_module_ui(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_ui_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_ui_funcs, countof(js_ui_funcs)); return m; } void module_ui_register(void) { amp_debug(MOD_STR, "module_ui_register"); JSContext *ctx = js_get_context(); aos_printf("module ui register\n"); js_init_module_ui(ctx, "UI"); } #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/ui/module_ui.c
C
apache-2.0
2,389
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "aos_system.h" #include "aos_network.h" #include "amp_defines.h" #include "aos_network.h" #include "amp_task.h" #include "be_inl.h" #define MOD_STR "MODEL" static JSClassID js_vm_class_id; JSValue native_model_setdata(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); /*void module_vm_register(void) { JSContext *ctx = js_get_context(); duk_push_object(ctx); duk_push_c_function(ctx, native_model_setdata, 1); duk_put_prop_string(ctx, -2, "setData"); duk_put_prop_string(ctx, -2, "VM"); }*/ static JSClassDef js_vm_class = { "VM", }; static const JSCFunctionListEntry js_vm_funcs[] = { JS_CFUNC_DEF("setData", 1, native_model_setdata ), }; static int js_vm_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_vm_class_id); JS_NewClass(JS_GetRuntime(ctx), js_vm_class_id, &js_vm_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_vm_funcs, countof(js_vm_funcs)); JS_SetClassProto(ctx, js_vm_class_id, proto); return JS_SetModuleExportList(ctx, m, js_vm_funcs, countof(js_vm_funcs)); } JSModuleDef *js_init_module_vm(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_vm_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_vm_funcs, countof(js_vm_funcs)); return m; } void module_vm_register(void) { amp_debug(MOD_STR, "module_vm_register"); JSContext *ctx = js_get_context(); aos_printf("module vm register\n"); js_init_module_vm(ctx, "VM"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/ui/module_vm.c
C
apache-2.0
1,851
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifdef AMP_ADVANCED_ADDON_UI #include "aos_fs.h" #include "aos_system.h" #include "amp_config.h" #include "amp_defines.h" #include "amp_task.h" #include "board_mgr.h" #include "quickjs.h" #include "cJSON.h" #include "page_entry.h" #include "render.h" #include "quickjs_addon_common.h" #define MOD_STR "APPENTRY" //static dlist_t g_pages_list; static JSClassID js_page_entry_class_id; extern char g_app_path[128]; extern amp_app_desc_t g_app; char app_file_path[128]; int search_js_page_entry(amp_app_desc_t *app) { int i; int size; cJSON *root = NULL; cJSON *item = NULL; cJSON *temp = NULL; void *json_data = NULL; void * js_app_fd = NULL; int file_len = 0; int json_fd = -1; page_desc_t *page; if (app == NULL) { return -1; } snprintf(app_file_path, 128, AMP_APP_MAIN_JSON); /* cannot find the index.js int current dir */ if ((json_fd = aos_open(app_file_path, O_RDONLY)) < 0) { amp_error(MOD_STR, "cannot find the file :%s", app_file_path); return -1; } /* read package config file to json_data buffer */ file_len = aos_lseek(json_fd, 0, SEEK_END); printf("%s %d\r\n", __func__, file_len); json_data = aos_calloc(1, sizeof(char) * (file_len + 1)); if (NULL == json_data) { aos_close(json_fd); json_fd = -1; return -1; } aos_lseek(json_fd, 0, SEEK_SET); aos_read(json_fd, json_data, file_len); aos_close(json_fd); /* parser the package json data */ root = cJSON_Parse(json_data); if (NULL == root) { aos_free(json_data); amp_error(MOD_STR, "cJSON_Parse failed"); return -1; } item = cJSON_GetObjectItem(root, "pages"); if (item == NULL) { return -1; } size = cJSON_GetArraySize(item); app->page = aos_malloc(sizeof(page_desc_t) * size); if (NULL == app->page) { return -1; } memset(app->page, 0, sizeof(page_desc_t) * size); app->num = size; app->cur_page = 0; for (i = 0; i < size; i++) { page = &app->page[i]; page->index = i; temp = cJSON_GetArrayItem(item, i); if(NULL == temp ) { continue; } //strncpy(page->path, temp->valuestring, 64); //printf("temp->valuestring == %s\n\r",temp->valuestring); snprintf(page->path, 64, "%s", temp->valuestring); snprintf(page->css_file, 128, "%s%s", temp->valuestring, ".css"); snprintf(page->xml_file, 128, "%s%s", temp->valuestring, ".xml"); snprintf(page->js_file, 128, "%s%s", temp->valuestring, ".js"); } aos_free(json_data); cJSON_Delete(root); return 0; } void page_config_parse() { memset(&g_app, 0, sizeof(g_app)); search_js_page_entry(&g_app); } page_options_t* page_get_cur_options(void) { int index; if (g_app.cur_page >= g_app.num) { return NULL; } index = g_app.cur_page; return &(g_app.page[index].options); } static int page_add_options(page_options_t *options) { int index; if (options == NULL) { return -1; } if (g_app.cur_page >= g_app.num) { return -1; } index = g_app.cur_page; g_app.page[index].options.object = options->object; g_app.page[index].options.data = options->data; g_app.page[index].options.on_show = options->on_show; g_app.page[index].options.on_update = options->on_update; g_app.page[index].options.on_exit = options->on_exit; return 0; } /* App(Object options) entry */ static JSValue native_page_entry(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int i; int ret; page_options_t page_options; JSValue irq_cb = argv[0]; /* check paramters */ if (!JS_IsObject(irq_cb)) { return JS_ThrowTypeError(ctx, "not a object"); } memset(&page_options, 0, sizeof(page_options_t)); /* get options object */ //duk_dup(ctx, -1); page_options.object = JS_DupValue(ctx, irq_cb); /* find data */ if (JS_GetPropertyStr(ctx, argv[0], "data")) { amp_debug(MOD_STR, "find Page#data()"); page_options.data = JS_DupValue(ctx, irq_cb); } /* find onShow() */ //if (duk_get_prop_string(ctx, 0, "onShow")) if (JS_GetPropertyStr(ctx, argv[0], "onShow")) { amp_debug(MOD_STR, "find Page#onShow()"); page_options.on_show = JS_DupValue(ctx, irq_cb); } /* find onUpdate() */ if (JS_GetPropertyStr(ctx, argv[0], "onUpdate")) { amp_debug(MOD_STR, "find Page#onUpdate()"); page_options.on_update = JS_DupValue(ctx, irq_cb); } /* find onExit() */ if (JS_GetPropertyStr(ctx, argv[0], "onExit")) { amp_debug(MOD_STR, "find Page#onExit()"); page_options.on_exit = JS_DupValue(ctx, irq_cb); } /* one-by-one insert into page list */ ret = page_add_options(&page_options); // amp_task_schedule_call(page_entry, NULL); return 1; } void page_entry(void *para) { page_options_t *options; JSContext *ctx = js_get_context(); options = page_get_cur_options(); if (options == NULL) { return; } /* onShow hook */ uint32_t value = 0; JSValue val = JS_Call(ctx, options->on_show, JS_UNDEFINED, 1, &value); JS_FreeValue(ctx, val); } void page_exit(void *para) { page_options_t *options; JSContext *ctx = js_get_context(); options = page_get_cur_options(); if (options == NULL) { amp_debug("page", "%s : %d---------------------------------", __func__, __LINE__); return; } /* onShow hook */ uint32_t value = 0; JSValue val = JS_Call(ctx, options->on_exit, JS_UNDEFINED, 1, &value); JS_FreeValue(ctx, val); JS_FreeValue(ctx, options->object); } void page_update(void *para) { page_options_t *options; JSContext *ctx = js_get_context(); options = page_get_cur_options(); if (options == NULL) { return; } /* onShow hook */ uint32_t value = 0; JSValue val = JS_Call(ctx, options->on_update, JS_UNDEFINED, 1, &value); JS_FreeValue(ctx, val); } static JSClassDef js_page_entry_class = { "APPENTRY", }; static int js_page_entry_init(JSContext *ctx) { JSValue proto; JS_NewClassID(&js_page_entry_class_id); JS_NewClass(JS_GetRuntime(ctx), js_page_entry_class_id, &js_page_entry_class); proto = JS_NewObject(ctx); JS_SetClassProto(ctx, js_page_entry_class_id, proto); return; } void page_entry_register(void) { amp_debug(MOD_STR, "module_page_entry_register"); JSContext *ctx = js_get_context(); aos_printf("module page_entry register\n"); js_page_entry_init(ctx); QUICKJS_GLOBAL_FUNC("Page", native_page_entry); } #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/ui/page_entry.c
C
apache-2.0
6,939
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef __PAGE_ENTRY_H #define __PAGE_ENTRY_H #include <stdio.h> #include <stdlib.h> #include <string.h> //#include "infra_list.h" #include "render.h" extern void page_list_init(void); extern void page_list_add(const char *route); extern void page_list_dump(void); extern void page_list_free(void); extern void page_entry_register(void); extern void page_entry(void *para); extern void page_exit(void *para); extern void page_update(void *para); #endif /* __PAGE_ENTRY_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/utils/ui/page_entry.h
C
apache-2.0
540
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <aos/errno.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #include <aos/ble.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <atomic.h> #include <work.h> #include <aos/gatt.h> #include <bluetooth/gatt.h> #include <bluetooth/uuid.h> #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" //#include "be_inl.h" #include "aiot_state_api.h" #include "bt_host_adapter.h" #define MOD_STR "BT_GATTS_ADAPTER" size_t g_attr_num = 0; gatt_attr_t *g_attrs_list = NULL; int bt_gatts_adapter_update_user_data(size_t index, uint16_t uuid, uint8_t *data, size_t len); uint16_t get_16bits_hex_from_string(const char *str) { uint16_t ret = 0, tmp = 0, ii = 0, jj = 0; uint32_t sample_len = strlen("0xAABB"); uint8_t seed[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; if (strlen(str) == sample_len) { if (strncmp(str, "0x", 2) && strncmp(str, "0X", 2)) { } else { for (ii = sample_len-1; ii >= sample_len-4; ii--) { // to uppercase if (str[ii] >= 'a') { tmp = str[ii] - ('a'-'A'); } else { tmp = str[ii]; } // char to number for (jj=0; jj<sizeof(seed); jj++) { if (seed[jj] == tmp) { break; } } ret += jj<<((sample_len-1-ii)*4); } } } // amp_debug(MOD_STR, "[%s] %s -> 0x%X", __func__, str, ret); return ret; } gatt_perm_en get_attr_perm_from_string(char *str) { gatt_perm_en ret = GATT_PERM_NONE; if (strstr(str, "R")) { ret |= GATT_PERM_READ; } if (strstr(str, "W")) { ret |= GATT_PERM_WRITE; } return ret; } gatt_prop_en get_char_perm_from_string(char *str) { gatt_prop_en ret = 0; if (strstr(str, "R")) { ret |= GATT_CHRC_PROP_READ; } if (strstr(str, "W")) { ret |= GATT_CHRC_PROP_WRITE; } return ret; } static gatt_service srvc_instance = {0}; uuid_t *bt_gatts_declare_16bits_uuid(uint16_t val) { struct ut_uuid_16 *uuid = (struct ut_uuid_16 *)malloc(sizeof(struct ut_uuid_16)); uuid->uuid.type = UUID_TYPE_16; uuid->val = val; return (uuid_t *)uuid; } void bt_gatts_define_gatt_srvc(gatt_attr_t *out, uint16_t uuid) { amp_debug(MOD_STR, "[%s] declare service uuid 0x%04x", __func__, uuid); out->uuid = bt_gatts_declare_16bits_uuid(0x2800); // UUID_GATT_PRIMARY; out->perm = GATT_PERM_READ; out->read = out->write = NULL; out->user_data = (void *)bt_gatts_declare_16bits_uuid(uuid); } void bt_gatts_define_gatt_char(gatt_attr_t *out, uint16_t uuid, uint8_t perimt) { amp_debug(MOD_STR, "[%s] declare char uuid 0x%04x", __func__, uuid); struct gatt_char_t *data = (struct gatt_char_t *)malloc(sizeof(struct gatt_char_t)); memset(data, 0, sizeof(struct gatt_char_t)); data->uuid= bt_gatts_declare_16bits_uuid(uuid); data->value_handle = 0; data->properties = perimt, out->uuid = bt_gatts_declare_16bits_uuid(0x2803); //UUID_GATT_CHRC; out->perm = GATT_PERM_READ; out->read = out->write = NULL; out->user_data = (void *)data; } void bt_gatts_define_gatt_char_val(gatt_attr_t *out, uint16_t uuid, uint8_t perimt) { amp_debug(MOD_STR, "[%s] declare char val uuid 0x%04x", __func__, uuid); out->uuid = bt_gatts_declare_16bits_uuid(uuid); out->perm = perimt; out->read = out->write = NULL; out->user_data = NULL; } void bt_gatts_define_ccc(gatt_attr_t *out) { amp_debug(MOD_STR, "[%s] declare ccc ...", __func__); struct bt_gatt_ccc_t *ccc = (struct bt_gatt_ccc_t *)malloc(sizeof(struct bt_gatt_ccc_t)); memset(ccc, 0, sizeof(struct bt_gatt_ccc_t)); out->uuid = bt_gatts_declare_16bits_uuid(0x2902); //UUID_GATT_CCC; out->perm = GATT_PERM_READ|GATT_PERM_WRITE; out->read = out->write = NULL; out->user_data = (void *)ccc; } int bt_gatts_adapter_add_service(amp_bt_host_adapter_gatts_srvc_t *srvc) { int ret = 0; amp_bt_host_adapter_gatt_chars_t *char_list = NULL; if (srvc) { g_attrs_list = (gatt_attr_t *)aos_malloc(srvc->attr_cnt * sizeof(gatt_attr_t)); if (!g_attrs_list) { amp_error(MOD_STR, "[%s] memory not enough for g_attrs_list", __func__); return ret; } memset(g_attrs_list, 0, srvc->attr_cnt * sizeof(gatt_attr_t)); char_list = srvc->chars; // declare the service bt_gatts_define_gatt_srvc(&g_attrs_list[g_attr_num++], get_16bits_hex_from_string(srvc->s_uuid)); while(g_attr_num<srvc->attr_cnt) { if (char_list->descr_type) { if (0 == strcmp(char_list->descr_type, "CCC")) { bt_gatts_define_gatt_char(&g_attrs_list[g_attr_num++], get_16bits_hex_from_string(char_list->char_uuid), GATT_CHRC_PROP_NOTIFY | get_char_perm_from_string(char_list->permission)); bt_gatts_define_gatt_char_val(&g_attrs_list[g_attr_num++], get_16bits_hex_from_string(char_list->char_uuid), get_attr_perm_from_string(char_list->permission)); bt_gatts_define_ccc(&g_attrs_list[g_attr_num++]); char_list++; continue; } else { /* CUD, SCC, CPF, CAF*/ amp_warn(MOD_STR, "[%s] unsupported descr type: %s ", __func__, char_list->descr_type); } } bt_gatts_define_gatt_char(&g_attrs_list[g_attr_num++], get_16bits_hex_from_string(char_list->char_uuid), GATT_CHRC_PROP_NOTIFY | get_char_perm_from_string(char_list->permission)); bt_gatts_define_gatt_char_val(&g_attrs_list[g_attr_num++], get_16bits_hex_from_string(char_list->char_uuid), get_attr_perm_from_string(char_list->permission)); char_list++; } amp_debug(MOD_STR, "[%s] declare service done, total attr: %d(%d)", __func__, g_attr_num, srvc->attr_cnt); // >=0: handle, <0: error ret = ble_stack_gatt_registe_service(&srvc_instance, g_attrs_list, srvc->attr_cnt); amp_debug(MOD_STR, "[%s] add service done with ret %d", __func__, ret); } else { amp_error(MOD_STR, "[%s] srvc is null", __func__); } return ret; } int bt_gatts_adapter_update_user_data(size_t index, uint16_t uuid_val, uint8_t *data, size_t len) { int ret = -1; int ii; gatt_attr_t *ptr = NULL; if (index >=0 && index<g_attr_num) { ptr = &(g_attrs_list[index]); } else { for (ii=0; ii<g_attr_num; ii++) { if (((struct ut_uuid_16 *)(g_attrs_list[ii].uuid))->val == uuid_val) { ptr = &(g_attrs_list[ii]); ret = ii; break; } } } if (ptr == NULL) { amp_error(MOD_STR, "[%s] give up updating as uuid not matched!!", __func__); return -1; } amp_bt_gatts_adapter_usr_data_t *old = (amp_bt_gatts_adapter_usr_data_t *)ptr->user_data; amp_bt_gatts_adapter_usr_data_t **new = (amp_bt_gatts_adapter_usr_data_t **)&(ptr->user_data); if (old) { if (old->data) { free(old->data); } else { amp_error(MOD_STR, "[%s] old is avaliable, but data is null. should NOT be here!!", __func__); } free(old); } *new = (amp_bt_gatts_adapter_usr_data_t *)malloc(sizeof(amp_bt_gatts_adapter_usr_data_t)); if (*new) { (*new)->len = len; (*new)->data = (uint8_t *)malloc(sizeof(uint8_t) * len); if ((*new)->data) { memcpy((*new)->data, data, len); amp_debug(MOD_STR, "[%s]update user data:%p -> %p", __func__, old, *new); } else { free(*new); amp_error(MOD_STR, "[%s][%d] memory not enough for new data!", __func__, __LINE__); } } else { amp_error(MOD_STR, "[%s][%d] memory not enough for new data!", __func__, __LINE__); } return ret; } static int bt_gatts_adapter_char_get_desc_idx(int start_idx, int16_t uuid) { int idx = -1; int i; for (i = start_idx; i < g_attr_num; i++) { if (UUID16(g_attrs_list[i].uuid) == uuid) { idx = i; break; } if (UUID16(g_attrs_list[i].uuid) == UUID16(UUID_GATT_CHRC)) { break; } } return idx; } int bt_gatts_adapter_update_chars(char *uuid, uint8_t *data, size_t len) { amp_bt_gatts_adapter_usr_data_t *old_data = NULL; int32_t index, ccc_index; index = bt_gatts_adapter_update_user_data(-1, get_16bits_hex_from_string(uuid), data, len); amp_debug(MOD_STR, "[%s] index = %d, uuid = %s, len = %d", __func__, index, uuid, len); if (index < 0) { return -1; } if(index < g_attr_num) { uint16_t *conn_handle = NULL; struct bt_gatt_ccc_t *ccc; ccc_index = bt_gatts_adapter_char_get_desc_idx(index, UUID16(UUID_GATT_CCC)); if (ccc_index < 0) { amp_error(MOD_STR, "[%s]ccc not found", __func__); return -1; } ccc = (struct bt_gatt_ccc_t *)g_attrs_list[ccc_index].user_data; for (int jj=0; jj< ARRAY_SIZES(ccc->cfg); jj++) { conn_handle = (uint16_t *)bt_conn_lookup_addr_le(ccc->cfg->id, (const bt_addr_le_t *)&ccc->cfg[jj].peer); if (conn_handle > 0) { if (ccc->cfg[0].value) { ble_stack_gatt_notificate(*conn_handle, g_attrs_list[index].handle, data, len); } } } } return 0; } void bt_gatts_dump_hex(uint8_t data[], size_t len) { printf("\t\tDUMP START: "); for (int ii=0; ii<len; ii++) { printf("%02x ", data[ii]); } printf("\n"); } int bt_gatts_adapter_event_callback(ble_event_en event, void *event_data) { switch (event) { case EVENT_GATT_CHAR_READ: { evt_data_gatt_char_read_t *read_data = (evt_data_gatt_char_read_t *)event_data; for (int ii=0; ii<g_attr_num; ii++) { if (g_attrs_list[ii].handle == read_data->char_handle) { amp_debug(MOD_STR, "[%s]read request at handle.%d, uuid:0x%04x, offset:%d", __func__, read_data->char_handle , ((struct ut_uuid_16 *)(g_attrs_list[ii].uuid))->val , read_data->offset); amp_bt_gatts_adapter_usr_data_t *data = (amp_bt_gatts_adapter_usr_data_t *)g_attrs_list[ii].user_data; if (data) { if (data->data && data->len) { bt_gatts_dump_hex(data->data, data->len); read_data->data = data->data; //memcpy(read_data->data, data->data, data->len); read_data->len = data->len; break; } } amp_error(MOD_STR, "[%s][%d] no data to be read!", __func__, __LINE__); } } } break; case EVENT_GATT_CHAR_WRITE: { evt_data_gatt_char_write_t *write_data = (evt_data_gatt_char_write_t *)event_data; for (int ii=0; ii<g_attr_num; ii++) { if (g_attrs_list[ii].handle == write_data->char_handle) { amp_debug(MOD_STR, "[%s]read request at handle.%d, uuid:0x%04x, offset:%d\n" , __func__, write_data->char_handle , ((struct ut_uuid_16 *)(g_attrs_list[ii].uuid))->val , write_data->offset); bt_gatts_adapter_update_user_data(ii, 0, (uint8_t *)write_data->data, write_data->len); amp_bt_gatts_adapter_usr_data_t *data = (amp_bt_gatts_adapter_usr_data_t *)g_attrs_list[ii].user_data; //bt_gatts_dump_hex(data->data, data->len); native_bt_host_gatts_handle_write((uint8_t *)write_data->data, write_data->len); break; } } } break; case EVENT_GATT_CHAR_CCC_CHANGE: { evt_data_gatt_char_ccc_change_t *data = (evt_data_gatt_char_ccc_change_t *)event_data; for (int ii=0; ii<g_attr_num; ii++) { if (g_attrs_list[ii].handle == data->char_handle) { struct bt_gatt_ccc_t *ccc = (struct bt_gatt_ccc_t *)g_attrs_list[ii].user_data; amp_debug(MOD_STR, "[%s]ccc-changed at handle.%d 0x%04x, 0x%04x,\n", __func__, data->char_handle , data->ccc_value, ccc->value); } } } break; default: break; } }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/wireless/bt_host/bt_gatts_adapter.c
C
apache-2.0
13,451
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <aos/ble.h> #include <aos/errno.h> #include <aos/kernel.h> #include <atomic.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/gatt.h> #include <bluetooth/uuid.h> #include <k_api.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <work.h> #include "bt_host_adapter.h" #include "aiot_state_api.h" #include "amp_defines.h" #include "amp_platform.h" #include "amp_task.h" #include "aos/init.h" #include "aos_system.h" #include "board.h" #define MOD_STR "BT_HOST_ADAPTER" static void bt_host_adapter_adv_data_destroy(ad_data_t *ad_data, int ad_num); static int bt_host_adapter_event_callback(ble_event_en event, void *event_data); extern int bt_gatts_adapter_event_callback(ble_event_en event, void *event_data); static ble_event_cb_t bt_host_adapter_ble_cb = { .callback = bt_host_adapter_event_callback, }; static int bt_host_adapter_char2hex(char c, char *x) { if (c >= '0' && c <= '9') { *x = c - '0'; } else if (c >= 'a' && c <= 'f') { *x = c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { *x = c - 'A' + 10; } else { return -1; } return 0; } static int bt_host_adapter_hex2bin(char *hex, uint8_t *buf) { char dec; int hexlen, i; hexlen = strlen(hex); if (hexlen == 0) { return 0; } /* if hexlen is uneven, return failed */ if (hexlen % 2) { return 0; } /* regular hex conversion */ for (i = 0; i < hexlen / 2; i++) { if (bt_host_adapter_char2hex(hex[2 * i], &dec) < 0) { return 0; } buf[i] = dec << 4; if (bt_host_adapter_char2hex(hex[2 * i + 1], &dec) < 0) { return 0; } buf[i] += dec; } return hexlen / 2; } int bt_host_adapter_bin2hex(char *hex, uint8_t *buf, uint8_t buf_len) { int i; if (hex == NULL) return 0; hex[0] = 0; for (i = 0; i < buf_len; i++) { sprintf(hex + strlen(hex), "%02x", buf[i]); } return buf_len * 2; } static int bt_host_adapter_addr2hex(char *hex, uint8_t *addr) { int i; if (hex == NULL) return 0; hex[0] = 0; for (i = 0; i < 6; i++) { sprintf(hex + strlen(hex), "%02x:", addr[5 - i]); } hex[17] = 0; return i * 3 - 1; } static int bt_host_adapter_event_callback(ble_event_en event, void *event_data) { amp_debug(MOD_STR, "%s, event = %x", __func__, event); switch (event) { case EVENT_GAP_CONN_CHANGE: { evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data; int32_t connect; if (e->connected == CONNECTED) { connect = 1; amp_debug(MOD_STR, "Connected"); } else { connect = 0; amp_debug(MOD_STR, "Disconnected"); } native_bt_host_conn_handle(e->conn_handle, connect); } break; case EVENT_GAP_DEV_FIND: { evt_data_gap_dev_find_t *e = (evt_data_gap_dev_find_t *)event_data; char adv_data[63]; char addr[19]; adv_data[0] = 0; bt_host_adapter_bin2hex(adv_data, e->adv_data, e->adv_len); addr[0] = 0; bt_host_adapter_addr2hex(addr, e->dev_addr.val); native_bt_host_scan_handle(addr, e->dev_addr.type, e->adv_type, adv_data, e->rssi); } break; default: bt_gatts_adapter_event_callback(event, event_data); break; } return 0; } static ad_data_t *bt_host_adapter_adv_data_parse(char *adv_data, int8_t *num) { int ad_num; int i, type, len, adv_len; ad_data_t *ad_data; uint8_t adv_bin[31]; if (adv_data == NULL) { return NULL; } adv_len = strlen(adv_data); if (adv_len == 0 || adv_len > 62) { return NULL; } adv_len = bt_host_adapter_hex2bin(adv_data, adv_bin); ad_num = 0; for (i = 0; i < adv_len;) { len = adv_bin[i]; if (i + len >= adv_len) { amp_debug(MOD_STR, "%s, wrong data %s", __func__, adv_data); return NULL; } i += len + 1; ad_num++; } if (ad_num == 0) { return NULL; } ad_data = aos_malloc(ad_num * sizeof(ad_data_t)); if (ad_data == NULL) { return NULL; } memset(ad_data, 0, sizeof(ad_num * sizeof(ad_data_t))); ad_num = 0; for (i = 0; i < adv_len;) { len = adv_bin[i]; ad_data[ad_num].len = len - 1; ad_data[ad_num].type = adv_bin[i + 1]; ad_data[ad_num].data = aos_malloc(len - 1); if (ad_data[ad_num].data == NULL) { bt_host_adapter_adv_data_destroy(ad_data, ad_num); return NULL; } memcpy(ad_data[ad_num].data, adv_bin + i + 2, len - 1); i += len + 1; ad_num++; } if (num) { *num = ad_num; } return ad_data; } static void bt_host_adapter_adv_data_destroy(ad_data_t *ad_data, int ad_num) { int i; for (i = 0; i < ad_num; i++) { if (ad_data[i].data) { aos_free(ad_data[i].data); } } aos_free(ad_data); } int bt_host_adapter_init(amp_bt_host_adapter_init_t *init) { init_param_t param; int ret; param.dev_name = init->dev_name; param.conn_num_max = init->conn_num_max; param.dev_addr = NULL; ret = ble_stack_init(&param); if (ret != BLE_STACK_OK) { return -1; } #if !BOARD_HAAS200 /* HaaS100/EDU WI-FI/蓝牙共存设置 */ extern int netdev_set_epta_params(int wlan_duration, int bt_duration, int hw_epta_enable); netdev_set_epta_params(80000, 20000, 0); #endif ret = ble_stack_event_register(&bt_host_adapter_ble_cb); if (ret) { return -1; } return ret; } int bt_host_adapter_start_adv(amp_bt_host_adapter_adv_start_t *adv_param) { adv_param_t param; int ret; param.type = adv_param->type; param.interval_min = adv_param->interval_min; param.interval_max = adv_param->interval_max; param.channel_map = adv_param->channel_map; param.ad_num = 0; param.sd_num = 0; param.ad = bt_host_adapter_adv_data_parse(adv_param->adv_data, &(param.ad_num)); param.sd = bt_host_adapter_adv_data_parse(adv_param->scan_rsp_data, &(param.sd_num)); param.filter_policy = ADV_FILTER_POLICY_ANY_REQ; memset(&(param.direct_peer_addr), 0, sizeof(dev_addr_t)); amp_debug(MOD_STR, "%s, ble_stack_adv_start, type = %d, min = %d, max = %d, ch = " "%d, ad_num = %d, sd_num = %d, ad[0].type = %d, ad[0].len = %d", __func__, param.type, param.interval_min, param.interval_max, param.channel_map, param.ad_num, param.sd_num, param.ad[0].type, param.ad[0].len); ret = ble_stack_adv_start(&param); amp_debug(MOD_STR, "ble_stack_adv_start ret = %d", ret); if (param.ad) { bt_host_adapter_adv_data_destroy(param.ad, param.ad_num); } if (param.sd) { bt_host_adapter_adv_data_destroy(param.sd, param.sd_num); } if (ret) { return -1; } return ret; } int bt_host_adapter_stop_adv(void) { int ret; ret = ble_stack_adv_stop(); if (ret) { return -1; } return ret; } int bt_host_adapter_start_scan(amp_bt_host_adapter_scan_start_t *scan_param) { scan_param_t param; int ret; param.type = scan_param->type; param.interval = scan_param->interval; param.window = scan_param->window; param.filter_dup = SCAN_FILTER_DUP_DISABLE; param.scan_filter = SCAN_FILTER_POLICY_ANY_ADV; amp_debug(MOD_STR, "%s, ble_stack_scan_start, type = %d, int = %d, win = %d", __func__, param.type, param.interval, param.window); ret = ble_stack_scan_start(&param); amp_debug(MOD_STR, "ble_stack_scan_start ret = %d", ret); if (ret) { return -1; } return ret; } int bt_host_adapter_stop_scan(void) { int ret; ret = ble_stack_scan_stop(); if (ret) { return -1; } return ret; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/wireless/bt_host/bt_host_adapter.c
C
apache-2.0
8,344
#ifndef _BT_HOST_ADAPTER_H_ #define _BT_HOST_ADAPTER_H_ typedef struct { char *dev_name; uint16_t conn_num_max; }amp_bt_host_adapter_init_t; typedef struct { int32_t type; char *adv_data; char *scan_rsp_data; int32_t interval_min; int32_t interval_max; int32_t channel_map; }amp_bt_host_adapter_adv_start_t; typedef struct { int32_t type; uint16_t interval; uint16_t window; }amp_bt_host_adapter_scan_start_t; typedef struct { char *char_uuid; char *permission; char *descr_uuid; char *descr_type; }amp_bt_host_adapter_gatt_chars_t; typedef struct { char *s_uuid; uint32_t attr_cnt; amp_bt_host_adapter_gatt_chars_t *chars; }amp_bt_host_adapter_gatts_srvc_t; typedef struct { size_t len; uint8_t *data; } amp_bt_gatts_adapter_usr_data_t; //GAP int bt_host_adapter_init(amp_bt_host_adapter_init_t *init); int bt_host_adapter_start_adv(amp_bt_host_adapter_adv_start_t *adv_param); int bt_host_adapter_stop_adv(void); int bt_host_adapter_start_scan(amp_bt_host_adapter_scan_start_t *scan_param); int bt_host_adapter_stop_scan(void); void native_bt_host_conn_handle(int32_t conn_handle, int32_t connect); void native_bt_host_scan_handle(char *addr, int32_t addr_type, int32_t adv_type, char *adv_data, int32_t rssi); //GATTS void native_bt_host_gatts_handle_write(uint8_t data[], size_t len); int bt_gatts_adapter_add_service(amp_bt_host_adapter_gatts_srvc_t *srvc); int bt_gatts_adapter_update_chars(char *uuid, uint8_t *data, size_t len); #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/wireless/bt_host/bt_host_adapter.h
C
apache-2.0
1,533
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_task.h" #include "aiot_state_api.h" #include "bt_host_adapter.h" #include "cJSON.h" #include "quickjs.h" #include "quickjs_addon_common.h" #include "quickjs-libc.h" #define MOD_STR "BT_HOST" typedef struct { JSValue scan_js_cb_ref; JSValue conn_js_cb_ref; JSValue gatts_js_cb_ref; }module_bt_host_info; typedef struct { char addr[19]; int32_t addr_type; int32_t adv_type; char adv_data[63]; int32_t rssi; }scan_js_cb_param; typedef struct { int32_t conn_handle; int32_t connect; }conn_js_cb_param; #define GATTS_MAX_DATA_LEN 128 typedef struct { int32_t len; uint8_t data[GATTS_MAX_DATA_LEN*2+1]; }gatts_js_cb_param; static JSClassID js_bt_host_class_id; module_bt_host_info g_module_bt_host_info; extern JSContext *js_get_context(void); extern void js_std_dump_error(JSContext *ctx); int bt_host_adapter_bin2hex(char *hex, uint8_t *buf, uint8_t buf_len); static module_bt_host_info * module_bt_host_get_info(void) { return &g_module_bt_host_info; } static void module_bt_host_clean(void) { } static JSValue native_bt_host_init(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; amp_bt_host_adapter_init_t *adapter_init; char *deviceName; int32_t conn_num_max; JSValue JS_deviceName, JS_conn_num_max; JS_deviceName = JS_GetPropertyStr(ctx, argv[0], "deviceName"); JS_conn_num_max = JS_GetPropertyStr(ctx, argv[0],"conn_num_max"); deviceName = (char *)JS_ToCString(ctx, JS_deviceName); JS_ToInt32(ctx, &conn_num_max, JS_conn_num_max); amp_debug(MOD_STR, "%s: deviceName = %s, conn_num_max = %d", __func__, deviceName, conn_num_max); adapter_init = (amp_bt_host_adapter_init_t *)aos_malloc(sizeof(amp_bt_host_adapter_init_t)); if (!adapter_init) { amp_error(MOD_STR, "allocate memory failed\n"); goto out; } adapter_init->dev_name = deviceName; adapter_init->conn_num_max = conn_num_max; ret = bt_host_adapter_init(adapter_init); amp_debug(MOD_STR, "%s: init ret = %d", __func__, ret); aos_free(adapter_init); out: return JS_NewInt32(ctx, ret); } static JSValue native_bt_host_start_adv(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int32_t type, interval_min, interval_max, channel_map; char *adv_data, *scan_rsp_data; amp_bt_host_adapter_adv_start_t *adapter_start_adv; module_bt_host_info * info = module_bt_host_get_info(); JSValue JStype, JSadv_data, JSscan_rsp_data, JSinterval_min, JSinterval_max, JSchannel_map, JS_cb; amp_debug(MOD_STR, "%s enter", __func__); JStype = JS_GetPropertyStr(ctx, argv[0], "type"); JSadv_data = JS_GetPropertyStr(ctx, argv[0], "adv_data"); JSscan_rsp_data = JS_GetPropertyStr(ctx, argv[0], "scan_rsp_data"); JSinterval_min = JS_GetPropertyStr(ctx, argv[0], "interval_min"); JSinterval_max = JS_GetPropertyStr(ctx, argv[0], "interval_max"); JSchannel_map = JS_GetPropertyStr(ctx, argv[0], "channel_map"); JS_ToInt32(ctx, &type, JStype); adv_data = (char *)JS_ToCString(ctx, JSadv_data); scan_rsp_data = (char *)JS_ToCString(ctx, JSscan_rsp_data); JS_ToInt32(ctx, &interval_min, JSinterval_min); JS_ToInt32(ctx, &interval_max, JSinterval_max); JS_ToInt32(ctx, &channel_map, JSchannel_map); amp_debug(MOD_STR, "%s: type = %d, ad = %s, sd = %s, interval_min = %d, interval_max = %d, channel_map = %d", __func__, type, adv_data, scan_rsp_data, interval_min, interval_max, channel_map); JS_cb = argv[1]; if (!JS_IsFunction(ctx, JS_cb)) { amp_warn(MOD_STR, "native_bt_host_start_adv, not a fun"); return JS_ThrowTypeError(ctx, "not a function"); } info->conn_js_cb_ref = JS_DupValue(ctx, JS_cb); adapter_start_adv = (amp_bt_host_adapter_adv_start_t *)aos_malloc(sizeof(amp_bt_host_adapter_adv_start_t)); if (!adapter_start_adv) { amp_error(MOD_STR, "allocate memory failed\n"); goto out; } adapter_start_adv->type = type; adapter_start_adv->adv_data = adv_data; adapter_start_adv->scan_rsp_data = scan_rsp_data; adapter_start_adv->interval_min = interval_min; adapter_start_adv->interval_max = interval_max; adapter_start_adv->channel_map = channel_map; ret = bt_host_adapter_start_adv(adapter_start_adv); aos_free(adapter_start_adv); out: return JS_NewInt32(ctx, ret); } static JSValue native_bt_host_stop_adv(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; ret = bt_host_adapter_stop_adv(); out: return JS_NewInt32(ctx, ret); } static JSValue native_bt_host_start_scan(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; int32_t type, interval, window; amp_bt_host_adapter_scan_start_t *adapter_start_scan; module_bt_host_info * info = module_bt_host_get_info(); JSValue JStype, JSinterval, JSwindow, JS_cb; amp_debug(MOD_STR, "%s enter", __func__); JStype = JS_GetPropertyStr(ctx, argv[0], "type"); JSinterval = JS_GetPropertyStr(ctx, argv[0], "interval"); JSwindow = JS_GetPropertyStr(ctx, argv[0], "window"); JS_ToInt32(ctx, &type, JStype); JS_ToInt32(ctx, &interval, JSinterval); JS_ToInt32(ctx, &window, JSwindow); JS_cb = argv[1]; if (!JS_IsFunction(ctx, JS_cb)) { amp_warn(MOD_STR, "native_bt_host_start_scan, not a fun"); return JS_ThrowTypeError(ctx, "not a function"); } info->scan_js_cb_ref = JS_DupValue(ctx, JS_cb); amp_debug(MOD_STR, "%s: type = %d, interval = %d, window = %d, channel_map = %d", __func__, type, interval, window); adapter_start_scan = (amp_bt_host_adapter_scan_start_t *)aos_malloc(sizeof(amp_bt_host_adapter_scan_start_t)); if (!adapter_start_scan) { amp_error(MOD_STR, "allocate memory failed\n"); goto out; } adapter_start_scan->type = type; adapter_start_scan->interval = interval; adapter_start_scan->window = window; ret = bt_host_adapter_start_scan(adapter_start_scan); aos_free(adapter_start_scan); out: return JS_NewInt32(ctx, ret); } static JSValue native_bt_host_stop_scan(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1; ret = bt_host_adapter_stop_scan(); out: return JS_NewInt32(ctx, ret); } static JSValue native_bt_host_add_service(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int ret = -1, chars_num = 0; char *attr_uuid = NULL, *attr_permit = NULL, *service_cfg = NULL; cJSON* service_obj = NULL, *chars_list_obj = NULL, *descr_obj = NULL, *elemet = NULL; amp_bt_host_adapter_gatts_srvc_t service = {0}; amp_bt_host_adapter_gatt_chars_t *chars_list; module_bt_host_info * info = module_bt_host_get_info(); JSValue JS_cb; amp_debug(MOD_STR, "%s enter", __func__); service_cfg = (char *)JS_ToCString(ctx, argv[0]); JS_cb = argv[1]; if (!JS_IsFunction(ctx, JS_cb)) { amp_warn(MOD_STR, "native_bt_host_add_service, not a fun"); return JS_ThrowTypeError(ctx, "not a function"); } info->gatts_js_cb_ref = JS_DupValue(ctx, JS_cb); /* eg. { "s_uuid":"0x1A1A", "chars_list":[ { "char_uuid":"0x1B1B", "char_permit":"RW", "char_descr":{ "descr_type":"CCC", "descr_uuid":"0x1C1C" } }, { "char_uuid":"0x1D1D", "char_permit":"R" } ] } */ if (service_cfg) { amp_debug(MOD_STR, "[%s] service_cfg: %s", __func__, service_cfg); service_obj = cJSON_Parse(service_cfg); if (service_obj != NULL && cJSON_IsObject(service_obj)) { service.s_uuid = cJSON_GetStringValue(cJSON_GetObjectItem(service_obj, "s_uuid")); service.attr_cnt ++; // for service declaration if (service.s_uuid) { chars_list_obj = cJSON_GetObjectItem(service_obj, "chars_list"); if (chars_list_obj && cJSON_IsArray(chars_list_obj)) { chars_num = cJSON_GetArraySize(chars_list_obj); if (chars_num) { chars_list = service.chars = (amp_bt_host_adapter_gatt_chars_t *)aos_malloc( chars_num * sizeof(amp_bt_host_adapter_gatt_chars_t)); if (chars_list) { memset(chars_list, 0, chars_num * sizeof(amp_bt_host_adapter_gatt_chars_t)); cJSON_ArrayForEach(elemet, chars_list_obj) { chars_list->char_uuid = cJSON_GetStringValue(cJSON_GetObjectItem(elemet, "char_uuid")); chars_list->permission = cJSON_GetStringValue(cJSON_GetObjectItem(elemet, "char_permit")); descr_obj = cJSON_GetObjectItem(elemet, "char_descr"); if (descr_obj) { chars_list->descr_uuid = cJSON_GetStringValue(cJSON_GetObjectItem(descr_obj, "descr_uuid")); chars_list->descr_type = cJSON_GetStringValue(cJSON_GetObjectItem(descr_obj, "descr_type")); service.attr_cnt += 3; } else { service.attr_cnt += 2; } chars_list ++; } ret = bt_gatts_adapter_add_service(&service); aos_free(service.chars); } else { amp_error(MOD_STR, "[%s] memory not enough for chars_list", __func__); } } else { amp_error(MOD_STR, "[%s] the number of characteristic is invalid", __func__); } } } cJSON_Delete(service_obj); } else { amp_error(MOD_STR, "[%s] failed to parse service_cfg to json object", __func__); } } else { amp_error(MOD_STR, "[%s] service_cfg is null", __func__); } if (ret) { // success amp_debug(MOD_STR, "[%s] add service success", __func__); } return JS_NewInt32(ctx, ret?0:-1); } static JSValue native_bt_host_update_chars(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { size_t vals_len = 0; int ret = -1, index = 0; uint8_t *vals_data = NULL; char *arg_str = NULL, *uuid = NULL; cJSON *root = NULL, *arry = NULL, *elemet = NULL; module_bt_host_info * info = module_bt_host_get_info(); amp_debug(MOD_STR, "%s enter", __func__); arg_str = (char *)JS_ToCString(ctx, argv[0]); amp_debug(MOD_STR, "arg str = %s", arg_str); //{"uuid":0x1000, "value":[1, 2, 3, 4]} if (arg_str) { root = cJSON_Parse(arg_str); if (root && cJSON_IsObject(root)) { uuid = cJSON_GetStringValue(cJSON_GetObjectItem(root, "uuid")); arry = cJSON_GetObjectItem(root, "value"); if (arry && cJSON_IsArray(arry)) { vals_len = cJSON_GetArraySize(arry); vals_data = (uint8_t *)malloc(vals_len * sizeof(uint8_t)); if (vals_data) { memset(vals_data, 0, vals_len * sizeof(uint8_t)); cJSON_ArrayForEach(elemet, arry) { vals_data[index++] = elemet->valueint; } ret = bt_gatts_adapter_update_chars(uuid, vals_data, vals_len); free(vals_data); } } cJSON_Delete(root); } } return JS_NewInt32(ctx, ret); // 0: success, -1: fail } void native_bt_host_conn_handle_js(void *param) { module_bt_host_info * info = module_bt_host_get_info(); JSContext *ctx = js_get_context(); conn_js_cb_param *cb_param; cb_param = (conn_js_cb_param *)param; if (info->conn_js_cb_ref) { JSValue val; JSValue args[2]; if (!JS_IsFunction(ctx, info->conn_js_cb_ref)) { amp_warn(MOD_STR, "native_bt_host_conn_handle, not a fun"); } amp_debug(MOD_STR, "native_bt_host_conn_handle"); args[0] = JS_NewInt32(ctx, cb_param->conn_handle); args[1] = JS_NewInt32(ctx, cb_param->connect); val = JS_Call(ctx, info->conn_js_cb_ref, JS_UNDEFINED, 2, args); JS_FreeValue(ctx, args[0]); JS_FreeValue(ctx, args[1]); aos_free(cb_param); if (JS_IsException(val)) { js_std_dump_error(ctx); } JS_FreeValue(ctx, val); } } void native_bt_host_conn_handle(int32_t conn_handle, int32_t connect) { module_bt_host_info * info = module_bt_host_get_info(); JSContext *ctx = js_get_context(); conn_js_cb_param *cb_param; if (info->conn_js_cb_ref) { conn_js_cb_param *cb_param; cb_param = aos_malloc(sizeof(conn_js_cb_param)); if (!cb_param) return; cb_param->conn_handle = conn_handle; cb_param->connect = connect; amp_task_schedule_call(native_bt_host_conn_handle_js, cb_param); } } void native_bt_host_scan_handle_js(void *param) { module_bt_host_info * info = module_bt_host_get_info(); JSContext *ctx = js_get_context(); scan_js_cb_param *cb_param; cb_param = (scan_js_cb_param *)param; if (info->scan_js_cb_ref) { JSValue val; JSValue args[5]; amp_debug(MOD_STR, "native_bt_host_scan_handle"); if (!JS_IsFunction(ctx, info->scan_js_cb_ref)) { amp_warn(MOD_STR, "native_bt_host_scan_handle, not a fun"); } args[0] = JS_NewString(ctx, cb_param->addr); args[1] = JS_NewInt32(ctx, cb_param->addr_type); args[2] = JS_NewInt32(ctx, cb_param->adv_type); args[3] = JS_NewString(ctx, cb_param->adv_data); args[4] = JS_NewInt32(ctx, cb_param->rssi); val = JS_Call(ctx, info->scan_js_cb_ref, JS_UNDEFINED, 5, args); JS_FreeValue(ctx, args[0]); JS_FreeValue(ctx, args[1]); JS_FreeValue(ctx, args[2]); JS_FreeValue(ctx, args[3]); JS_FreeValue(ctx, args[4]); aos_free(cb_param); if (JS_IsException(val)) { js_std_dump_error(ctx); } JS_FreeValue(ctx, val); } } void native_bt_host_scan_handle(char *addr, int32_t addr_type, int32_t adv_type, char *adv_data, int32_t rssi) { module_bt_host_info * info = module_bt_host_get_info(); if (info->scan_js_cb_ref) { scan_js_cb_param *cb_param; cb_param = aos_malloc(sizeof(scan_js_cb_param)); if (!cb_param) return; strcpy(cb_param->addr, addr); cb_param->addr_type = addr_type; cb_param->adv_type = adv_type; strcpy(cb_param->adv_data, adv_data); cb_param->rssi = rssi; amp_task_schedule_call(native_bt_host_scan_handle_js, cb_param); } } void native_bt_host_gatts_handle_write_js(void *param) { module_bt_host_info * info = module_bt_host_get_info(); JSContext *ctx = js_get_context(); gatts_js_cb_param *cb_param; cb_param = (gatts_js_cb_param *)param; if (info->gatts_js_cb_ref) { JSValue val; JSValue args[2]; amp_debug(MOD_STR, "native_bt_host_gatts_handle_write_js"); if (!JS_IsFunction(ctx, info->gatts_js_cb_ref)) { amp_warn(MOD_STR, "native_bt_host_gatts_handle_write, not a fun"); } args[0] = JS_NewInt32(ctx, cb_param->len); args[1] = JS_NewString(ctx, cb_param->data); val = JS_Call(ctx, info->gatts_js_cb_ref, JS_UNDEFINED, 2, args); JS_FreeValue(ctx, args[0]); JS_FreeValue(ctx, args[1]); aos_free(cb_param); if (JS_IsException(val)) { js_std_dump_error(ctx); } JS_FreeValue(ctx, val); } } void native_bt_host_gatts_handle_write(uint8_t data[], size_t len) { module_bt_host_info * info = module_bt_host_get_info(); if (len > GATTS_MAX_DATA_LEN) { amp_error(MOD_STR, "data too long"); return; } if (info->gatts_js_cb_ref) { gatts_js_cb_param *cb_param; cb_param = aos_malloc(sizeof(gatts_js_cb_param)); if (!cb_param) return; cb_param->len = len; bt_host_adapter_bin2hex(cb_param->data, data, len); amp_task_schedule_call(native_bt_host_gatts_handle_write_js, cb_param); } } static JSClassDef js_bt_host_class = { "BT_HOST", }; static const JSCFunctionListEntry js_bt_host_funcs[] = { JS_CFUNC_DEF("init", 1, native_bt_host_init ), JS_CFUNC_DEF("start_adv", 2, native_bt_host_start_adv ), JS_CFUNC_DEF("stop_adv", 0, native_bt_host_stop_adv ), JS_CFUNC_DEF("start_scan", 2, native_bt_host_start_scan), JS_CFUNC_DEF("stop_scan", 0, native_bt_host_stop_scan), JS_CFUNC_DEF("add_service", 2, native_bt_host_add_service), JS_CFUNC_DEF("update_chars", 1, native_bt_host_update_chars), }; static int js_bt_host_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JS_NewClassID(&js_bt_host_class_id); JS_NewClass(JS_GetRuntime(ctx), js_bt_host_class_id, &js_bt_host_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_bt_host_funcs, countof(js_bt_host_funcs)); JS_SetClassProto(ctx, js_bt_host_class_id, proto); return JS_SetModuleExportList(ctx, m, js_bt_host_funcs, countof(js_bt_host_funcs)); } JSModuleDef *js_init_module_bt_host(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_bt_host_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_bt_host_funcs, countof(js_bt_host_funcs)); return m; } void module_bt_host_register(void) { amp_debug(MOD_STR, "module_bt_host_register"); JSContext *ctx = js_get_context(); amp_module_free_register(module_bt_host_clean); js_init_module_bt_host(ctx, "BT_HOST"); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/addons/wireless/bt_host/module_bt_host.c
C
apache-2.0
18,694
#ifndef AOS_AMP_PORT_H #define AOS_AMP_PORT_H #include "aos_fenv.h" #include "aos_jquick_mutex.h" #include "aos_system.h" #include "amp_memory.h" #define printf(...) aos_printf(__VA_ARGS__) #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/aos_port/aos_amp_port.h
C
apache-2.0
201
#ifndef FENV_AOS_H #define FENV_AOS_H enum { FE_INVALID = 0x01, #define FE_INVALID FE_INVALID __FE_DENORM = 0x02, FE_DIVBYZERO = 0x04, #define FE_DIVBYZERO FE_DIVBYZERO FE_OVERFLOW = 0x08, #define FE_OVERFLOW FE_OVERFLOW FE_UNDERFLOW = 0x10, #define FE_UNDERFLOW FE_UNDERFLOW FE_INEXACT = 0x20 #define FE_INEXACT FE_INEXACT }; enum { FE_TONEAREST = 0, #define FE_TONEAREST FE_TONEAREST FE_DOWNWARD = 0x400, #define FE_DOWNWARD FE_DOWNWARD FE_UPWARD = 0x800, #define FE_UPWARD FE_UPWARD FE_TOWARDZERO = 0xc00 #define FE_TOWARDZERO FE_TOWARDZERO }; #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/aos_port/aos_fenv.h
C
apache-2.0
622
#include <stdlib.h> #include "aos_jquick_mutex.h" #include "aos/kernel.h" #include "ulog/ulog.h" #define MOD_STR "JQUICK_MUTEX" JQuick_Mutex jquick_mutex_create() { aos_mutex_t mutex; if (0 != aos_mutex_new(&mutex)) { return NULL; } return (JQuick_Mutex)mutex; } int jquick_mutex_lock(JQuick_Mutex mutex) { if (!mutex) { LOGE(MOD_STR, "JQuick_Mutex: Mutex is NULL\n"); return -1; } return aos_mutex_lock((aos_mutex_t *)&mutex, AOS_WAIT_FOREVER); } int jquick_mutex_unlock(JQuick_Mutex mutex) { if (!mutex) { LOGE(MOD_STR, "JQuick_Mutex: Mutex is NULL\n"); return -1; } return aos_mutex_unlock((aos_mutex_t *)&mutex); } int jquick_mutex_destroy(JQuick_Mutex mutex) { if (!mutex) { LOGE(MOD_STR, "JQuick_Mutex: Mutex is NULL\n"); return -1; } aos_mutex_free((aos_mutex_t *)&mutex); return 0; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/aos_port/aos_jquick_mutex.c
C
apache-2.0
915
#ifndef __AOS_AMP_JQUICK_MUTEX_H__ #define __AOS_AMP_JQUICK_MUTEX_H__ #ifdef __cplusplus extern "C" { #endif typedef void* JQuick_Mutex; JQuick_Mutex jquick_mutex_create(); int jquick_mutex_lock( JQuick_Mutex m); int jquick_mutex_unlock( JQuick_Mutex m); int jquick_mutex_destroy( JQuick_Mutex m); #ifdef __cplusplus } #endif #endif // __QEMU_FREERTOS_JQUICK_MUTEX_H__
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/aos_port/aos_jquick_mutex.h
C
apache-2.0
403
set(CMAKE_INSTALL_PREFIX ${PRODUCT_DEPLOY_DIR}) add_definitions(-D_GNU_SOURCE) add_definitions(-DCONFIG_VERSION="2020-04-12") #add_definitions(-DCONFIG_BIGNUM) add_definitions(-DCONFIG_LTO) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/) #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0 -pipe -Wno-narrowing -funwind-tables -feliminate-unused-debug-types -fexceptions -fPIC" CACHE INTERNAL "" FORCE) file(GLOB LIBSOURCE "quickjs.c" "libregexp.c" "libunicode.c" "cutils.c" "libbf.c") if(BUILD_JS_EXTENSION_SHARED) add_library(quickjs SHARED ${LIBSOURCE}) target_compile_options(quickjs PRIVATE -fvisibility=default) else() add_library(quickjs STATIC ${LIBSOURCE}) endif() # add_library(quickjs SHARED ${LIBSOURCE}) #add_executable(qjs ${APPSOURCE}) #target_link_libraries(qjs m dl) install(TARGETS RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin" ARCHIVE DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" LIBRARY DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" )
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/CMakeLists.txt
CMake
apache-2.0
1,071
# # QuickJS Javascript Engine # # Copyright (c) 2017-2020 Fabrice Bellard # Copyright (c) 2017-2020 Charlie Gordon # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ifeq ($(shell uname -s),Darwin) CONFIG_DARWIN=y endif # Windows cross compilation from Linux #CONFIG_WIN32=y # use link time optimization (smaller and faster executables but slower build) CONFIG_LTO=y # consider warnings as errors (for development) #CONFIG_WERROR=y # force 32 bit build for some utilities #CONFIG_M32=y ifdef CONFIG_DARWIN # use clang instead of gcc CONFIG_CLANG=y CONFIG_DEFAULT_AR=y endif # installation directory prefix=/usr/local # use the gprof profiler #CONFIG_PROFILE=y # use address sanitizer #CONFIG_ASAN=y # include the code for BigInt/BigFloat/BigDecimal and math mode #CONFIG_BIGNUM=y OBJDIR=.obj ifdef CONFIG_WIN32 CROSS_PREFIX=i686-w64-mingw32- EXE=.exe else CROSS_PREFIX= EXE= endif ifdef CONFIG_CLANG HOST_CC=clang CC=$(CROSS_PREFIX)clang CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d CFLAGS += -Wextra CFLAGS += -Wno-sign-compare CFLAGS += -Wno-missing-field-initializers CFLAGS += -Wundef -Wuninitialized CFLAGS += -Wunused -Wno-unused-parameter CFLAGS += -Wwrite-strings CFLAGS += -Wchar-subscripts -funsigned-char CFLAGS += -MMD -MF $(OBJDIR)/$(@F).d ifdef CONFIG_DEFAULT_AR AR=$(CROSS_PREFIX)ar else ifdef CONFIG_LTO AR=$(CROSS_PREFIX)llvm-ar else AR=$(CROSS_PREFIX)ar endif endif else HOST_CC=gcc CC=$(CROSS_PREFIX)gcc CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d CFLAGS += -Wno-array-bounds -Wno-format-truncation ifdef CONFIG_LTO AR=$(CROSS_PREFIX)gcc-ar else AR=$(CROSS_PREFIX)ar endif endif STRIP=$(CROSS_PREFIX)strip ifdef CONFIG_WERROR CFLAGS+=-Werror endif DEFINES:=-D_GNU_SOURCE -DCONFIG_VERSION=\"$(shell cat VERSION)\" ifdef CONFIG_BIGNUM DEFINES+=-DCONFIG_BIGNUM endif ifdef CONFIG_WIN32 DEFINES+=-D__USE_MINGW_ANSI_STDIO # for standard snprintf behavior endif CFLAGS+=$(DEFINES) CFLAGS_DEBUG=$(CFLAGS) -O0 CFLAGS_SMALL=$(CFLAGS) -Os CFLAGS_OPT=$(CFLAGS) -O2 CFLAGS_NOLTO:=$(CFLAGS_OPT) LDFLAGS=-g ifdef CONFIG_LTO CFLAGS_SMALL+=-flto CFLAGS_OPT+=-flto LDFLAGS+=-flto endif ifdef CONFIG_PROFILE CFLAGS+=-p LDFLAGS+=-p endif ifdef CONFIG_ASAN CFLAGS+=-fsanitize=address -fno-omit-frame-pointer LDFLAGS+=-fsanitize=address -fno-omit-frame-pointer endif ifdef CONFIG_WIN32 LDEXPORT= else LDEXPORT=-rdynamic endif PROGS=qjs$(EXE) qjsc$(EXE) run-test262 ifneq ($(CROSS_PREFIX),) QJSC_CC=gcc QJSC=./host-qjsc PROGS+=$(QJSC) else QJSC_CC=$(CC) QJSC=./qjsc$(EXE) endif ifndef CONFIG_WIN32 PROGS+=qjscalc endif ifdef CONFIG_M32 PROGS+=qjs32 qjs32_s endif PROGS+=libquickjs.a ifdef CONFIG_LTO PROGS+=libquickjs.lto.a endif # examples ifeq ($(CROSS_PREFIX),) ifdef CONFIG_ASAN PROGS+= else PROGS+=examples/hello examples/hello_module examples/test_fib ifndef CONFIG_DARWIN PROGS+=examples/fib.so examples/point.so endif endif endif all: $(OBJDIR) $(OBJDIR)/quickjs.check.o $(OBJDIR)/qjs.check.o $(PROGS) QJS_LIB_OBJS=$(OBJDIR)/quickjs.o $(OBJDIR)/libregexp.o $(OBJDIR)/libunicode.o $(OBJDIR)/cutils.o $(OBJDIR)/quickjs-libc.o QJS_OBJS=$(OBJDIR)/qjs.o $(OBJDIR)/repl.o $(QJS_LIB_OBJS) ifdef CONFIG_BIGNUM QJS_LIB_OBJS+=$(OBJDIR)/libbf.o QJS_OBJS+=$(OBJDIR)/qjscalc.o endif QJS_LIB_OBJS+=$(OBJDIR)/linux_jquick_mutex.o HOST_LIBS=-lm -ldl -lpthread LIBS=-lm ifndef CONFIG_WIN32 LIBS+=-ldl -lpthread endif $(OBJDIR): mkdir -p $(OBJDIR) $(OBJDIR)/examples $(OBJDIR)/tests qjs$(EXE): $(QJS_OBJS) $(CC) $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS) qjs-debug$(EXE): $(patsubst %.o, %.debug.o, $(QJS_OBJS)) $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) qjsc$(EXE): $(OBJDIR)/qjsc.o $(QJS_LIB_OBJS) $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) ifneq ($(CROSS_PREFIX),) $(QJSC): $(OBJDIR)/qjsc.host.o \ $(patsubst %.o, %.host.o, $(QJS_LIB_OBJS)) $(HOST_CC) $(LDFLAGS) -o $@ $^ $(HOST_LIBS) endif #CROSS_PREFIX QJSC_DEFINES:=-DCONFIG_CC=\"$(QJSC_CC)\" -DCONFIG_PREFIX=\"$(prefix)\" ifdef CONFIG_LTO QJSC_DEFINES+=-DCONFIG_LTO endif QJSC_HOST_DEFINES:=-DCONFIG_CC=\"$(HOST_CC)\" -DCONFIG_PREFIX=\"$(prefix)\" $(OBJDIR)/qjsc.o: CFLAGS+=$(QJSC_DEFINES) $(OBJDIR)/qjsc.host.o: CFLAGS+=$(QJSC_HOST_DEFINES) qjs32: $(patsubst %.o, %.m32.o, $(QJS_OBJS)) $(CC) -m32 $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS) qjs32_s: $(patsubst %.o, %.m32s.o, $(QJS_OBJS)) $(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS) @size $@ qjscalc: qjs ln -sf $< $@ ifdef CONFIG_LTO LTOEXT=.lto else LTOEXT= endif libquickjs$(LTOEXT).a: $(QJS_LIB_OBJS) $(AR) rcs $@ $^ ifdef CONFIG_LTO libquickjs.a: $(patsubst %.o, %.nolto.o, $(QJS_LIB_OBJS)) $(AR) rcs $@ $^ endif # CONFIG_LTO repl.c: $(QJSC) repl.js $(QJSC) -c -o $@ -m repl.js qjscalc.c: $(QJSC) qjscalc.js $(QJSC) -fbignum -c -o $@ qjscalc.js ifneq ($(wildcard unicode/UnicodeData.txt),) $(OBJDIR)/libunicode.o $(OBJDIR)/libunicode.m32.o $(OBJDIR)/libunicode.m32s.o \ $(OBJDIR)/libunicode.nolto.o: libunicode-table.h libunicode-table.h: unicode_gen ./unicode_gen unicode $@ endif run-test262: $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS) $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) run-test262-debug: $(patsubst %.o, %.debug.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS)) $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) run-test262-32: $(patsubst %.o, %.m32.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS)) $(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS) # object suffix order: nolto, [m32|m32s] $(OBJDIR)/%.o: %.c | $(OBJDIR) $(CC) $(CFLAGS_OPT) -c -o $@ $< $(OBJDIR)/%.host.o: %.c | $(OBJDIR) $(HOST_CC) $(CFLAGS_OPT) -c -o $@ $< $(OBJDIR)/%.pic.o: %.c | $(OBJDIR) $(CC) $(CFLAGS_OPT) -fPIC -DJS_SHARED_LIBRARY -c -o $@ $< $(OBJDIR)/%.nolto.o: %.c | $(OBJDIR) $(CC) $(CFLAGS_NOLTO) -c -o $@ $< $(OBJDIR)/%.m32.o: %.c | $(OBJDIR) $(CC) -m32 $(CFLAGS_OPT) -c -o $@ $< $(OBJDIR)/%.m32s.o: %.c | $(OBJDIR) $(CC) -m32 $(CFLAGS_SMALL) -c -o $@ $< $(OBJDIR)/%.debug.o: %.c | $(OBJDIR) $(CC) $(CFLAGS_DEBUG) -c -o $@ $< $(OBJDIR)/%.check.o: %.c | $(OBJDIR) $(CC) $(CFLAGS) -DCONFIG_CHECK_JSVALUE -c -o $@ $< regexp_test: libregexp.c libunicode.c cutils.c $(CC) $(LDFLAGS) $(CFLAGS) -DTEST -o $@ libregexp.c libunicode.c cutils.c $(LIBS) jscompress: jscompress.c $(CC) $(LDFLAGS) $(CFLAGS) -o $@ jscompress.c unicode_gen: $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o libunicode.c unicode_gen_def.h $(HOST_CC) $(LDFLAGS) $(CFLAGS) -o $@ $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o clean: rm -f repl.c qjscalc.c out.c rm -f *.a *.o *.d *~ jscompress unicode_gen regexp_test $(PROGS) rm -f hello.c test_fib.c rm -f examples/*.so tests/*.so rm -rf $(OBJDIR)/ *.dSYM/ qjs-debug rm -rf run-test262-debug run-test262-32 install: all mkdir -p "$(DESTDIR)$(prefix)/bin" $(STRIP) qjs qjsc install -m755 qjs qjsc "$(DESTDIR)$(prefix)/bin" ln -sf qjs "$(DESTDIR)$(prefix)/bin/qjscalc" mkdir -p "$(DESTDIR)$(prefix)/lib/quickjs" install -m644 libquickjs.a "$(DESTDIR)$(prefix)/lib/quickjs" ifdef CONFIG_LTO install -m644 libquickjs.lto.a "$(DESTDIR)$(prefix)/lib/quickjs" endif mkdir -p "$(DESTDIR)$(prefix)/include/quickjs" install -m644 quickjs.h quickjs-libc.h "$(DESTDIR)$(prefix)/include/quickjs" ############################################################################### # examples # example of static JS compilation HELLO_SRCS=examples/hello.js HELLO_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \ -fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \ -fno-date -fno-module-loader ifdef CONFIG_BIGNUM HELLO_OPTS+=-fno-bigint endif hello.c: $(QJSC) $(HELLO_SRCS) $(QJSC) -e $(HELLO_OPTS) -o $@ $(HELLO_SRCS) ifdef CONFIG_M32 examples/hello: $(OBJDIR)/hello.m32s.o $(patsubst %.o, %.m32s.o, $(QJS_LIB_OBJS)) $(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS) else examples/hello: $(OBJDIR)/hello.o $(QJS_LIB_OBJS) $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) endif # example of static JS compilation with modules HELLO_MODULE_SRCS=examples/hello_module.js HELLO_MODULE_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \ -fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \ -fno-date -m examples/hello_module: $(QJSC) libquickjs$(LTOEXT).a $(HELLO_MODULE_SRCS) $(QJSC) $(HELLO_MODULE_OPTS) -o $@ $(HELLO_MODULE_SRCS) # use of an external C module (static compilation) test_fib.c: $(QJSC) examples/test_fib.js $(QJSC) -e -M examples/fib.so,fib -m -o $@ examples/test_fib.js examples/test_fib: $(OBJDIR)/test_fib.o $(OBJDIR)/examples/fib.o libquickjs$(LTOEXT).a $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) examples/fib.so: $(OBJDIR)/examples/fib.pic.o $(CC) $(LDFLAGS) -shared -o $@ $^ examples/point.so: $(OBJDIR)/examples/point.pic.o $(CC) $(LDFLAGS) -shared -o $@ $^ ############################################################################### # documentation DOCS=doc/quickjs.pdf doc/quickjs.html doc/jsbignum.pdf doc/jsbignum.html build_doc: $(DOCS) clean_doc: rm -f $(DOCS) doc/%.pdf: doc/%.texi texi2pdf --clean -o $@ -q $< doc/%.html.pre: doc/%.texi makeinfo --html --no-headers --no-split --number-sections -o $@ $< doc/%.html: doc/%.html.pre sed -e 's|</style>|</style>\n<meta name="viewport" content="width=device-width, initial-scale=1.0">|' < $< > $@ ############################################################################### # tests ifndef CONFIG_DARWIN test: tests/bjson.so examples/point.so endif ifdef CONFIG_M32 test: qjs32 endif test: qjs ./qjs tests/test_closure.js ./qjs tests/test_language.js ./qjs tests/test_builtin.js ./qjs tests/test_loop.js ./qjs tests/test_std.js ./qjs tests/test_worker.js ifndef CONFIG_DARWIN ifdef CONFIG_BIGNUM ./qjs --bignum tests/test_bjson.js else ./qjs tests/test_bjson.js endif ./qjs examples/test_point.js endif ifdef CONFIG_BIGNUM ./qjs --bignum tests/test_op_overloading.js ./qjs --bignum tests/test_bignum.js ./qjs --qjscalc tests/test_qjscalc.js endif ifdef CONFIG_M32 ./qjs32 tests/test_closure.js ./qjs32 tests/test_language.js ./qjs32 tests/test_builtin.js ./qjs32 tests/test_loop.js ./qjs32 tests/test_std.js ./qjs32 tests/test_worker.js ifdef CONFIG_BIGNUM ./qjs32 --bignum tests/test_op_overloading.js ./qjs32 --bignum tests/test_bignum.js ./qjs32 --qjscalc tests/test_qjscalc.js endif endif stats: qjs qjs32 ./qjs -qd ./qjs32 -qd microbench: qjs ./qjs tests/microbench.js microbench-32: qjs32 ./qjs32 tests/microbench.js # ES5 tests (obsolete) test2o: run-test262 time ./run-test262 -m -c test262o.conf test2o-32: run-test262-32 time ./run-test262-32 -m -c test262o.conf test2o-update: run-test262 ./run-test262 -u -c test262o.conf # Test262 tests test2-default: run-test262 time ./run-test262 -m -c test262.conf test2: run-test262 time ./run-test262 -m -c test262.conf -a test2-32: run-test262-32 time ./run-test262-32 -m -c test262.conf -a test2-update: run-test262 ./run-test262 -u -c test262.conf -a test2-check: run-test262 time ./run-test262 -m -c test262.conf -E -a testall: all test microbench test2o test2 testall-32: all test-32 microbench-32 test2o-32 test2-32 testall-complete: testall testall-32 bench-v8: qjs make -C tests/bench-v8 ./qjs -d tests/bench-v8/combined.js tests/bjson.so: $(OBJDIR)/tests/bjson.pic.o $(CC) $(LDFLAGS) -shared -o $@ $^ $(LIBS) -include $(wildcard $(OBJDIR)/*.d)
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/Makefile
Makefile
apache-2.0
12,243
/* * C utilities * * Copyright (c) 2017 Fabrice Bellard * Copyright (c) 2018 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include "cutils.h" void pstrcpy(char *buf, int buf_size, const char *str) { int c; char *q = buf; if (buf_size <= 0) return; for(;;) { c = *str++; if (c == 0 || q >= buf + buf_size - 1) break; *q++ = c; } *q = '\0'; } /* strcat and truncate. */ char *pstrcat(char *buf, int buf_size, const char *s) { int len; len = strlen(buf); if (len < buf_size) pstrcpy(buf + len, buf_size - len, s); return buf; } int strstart(const char *str, const char *val, const char **ptr) { const char *p, *q; p = str; q = val; while (*q != '\0') { if (*p != *q) return 0; p++; q++; } if (ptr) *ptr = p; return 1; } int has_suffix(const char *str, const char *suffix) { size_t len = strlen(str); size_t slen = strlen(suffix); return (len >= slen && !memcmp(str + len - slen, suffix, slen)); } /* Dynamic buffer package */ static void *dbuf_default_realloc(void *opaque, void *ptr, size_t size) { return realloc(ptr, size); } void dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func) { memset(s, 0, sizeof(*s)); if (!realloc_func) realloc_func = dbuf_default_realloc; s->opaque = opaque; s->realloc_func = realloc_func; } void dbuf_init(DynBuf *s) { dbuf_init2(s, NULL, NULL); } /* return < 0 if error */ int dbuf_realloc(DynBuf *s, size_t new_size) { size_t size; uint8_t *new_buf; if (new_size > s->allocated_size) { if (s->error) return -1; size = s->allocated_size * 3 / 2; if (size > new_size) new_size = size; new_buf = s->realloc_func(s->opaque, s->buf, new_size); if (!new_buf) { s->error = TRUE; return -1; } s->buf = new_buf; s->allocated_size = new_size; } return 0; } int dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len) { size_t end; end = offset + len; if (dbuf_realloc(s, end)) return -1; memcpy(s->buf + offset, data, len); if (end > s->size) s->size = end; return 0; } int dbuf_put(DynBuf *s, const uint8_t *data, size_t len) { if (unlikely((s->size + len) > s->allocated_size)) { if (dbuf_realloc(s, s->size + len)) return -1; } memcpy(s->buf + s->size, data, len); s->size += len; return 0; } int dbuf_put_self(DynBuf *s, size_t offset, size_t len) { if (unlikely((s->size + len) > s->allocated_size)) { if (dbuf_realloc(s, s->size + len)) return -1; } memcpy(s->buf + s->size, s->buf + offset, len); s->size += len; return 0; } int dbuf_putc(DynBuf *s, uint8_t c) { return dbuf_put(s, &c, 1); } int dbuf_putstr(DynBuf *s, const char *str) { return dbuf_put(s, (const uint8_t *)str, strlen(str)); } int __attribute__((format(printf, 2, 3))) dbuf_printf(DynBuf *s, const char *fmt, ...) { va_list ap; char buf[128]; int len; va_start(ap, fmt); len = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); if (len < sizeof(buf)) { /* fast case */ return dbuf_put(s, (uint8_t *)buf, len); } else { if (dbuf_realloc(s, s->size + len + 1)) return -1; va_start(ap, fmt); vsnprintf((char *)(s->buf + s->size), s->allocated_size - s->size, fmt, ap); va_end(ap); s->size += len; } return 0; } void dbuf_free(DynBuf *s) { /* we test s->buf as a fail safe to avoid crashing if dbuf_free() is called twice */ if (s->buf) { s->realloc_func(s->opaque, s->buf, 0); } memset(s, 0, sizeof(*s)); } /* Note: at most 31 bits are encoded. At most UTF8_CHAR_LEN_MAX bytes are output. */ int unicode_to_utf8(uint8_t *buf, unsigned int c) { uint8_t *q = buf; if (c < 0x80) { *q++ = c; } else { if (c < 0x800) { *q++ = (c >> 6) | 0xc0; } else { if (c < 0x10000) { *q++ = (c >> 12) | 0xe0; } else { if (c < 0x00200000) { *q++ = (c >> 18) | 0xf0; } else { if (c < 0x04000000) { *q++ = (c >> 24) | 0xf8; } else if (c < 0x80000000) { *q++ = (c >> 30) | 0xfc; *q++ = ((c >> 24) & 0x3f) | 0x80; } else { return 0; } *q++ = ((c >> 18) & 0x3f) | 0x80; } *q++ = ((c >> 12) & 0x3f) | 0x80; } *q++ = ((c >> 6) & 0x3f) | 0x80; } *q++ = (c & 0x3f) | 0x80; } return q - buf; } static const unsigned int utf8_min_code[5] = { 0x80, 0x800, 0x10000, 0x00200000, 0x04000000, }; static const unsigned char utf8_first_code_mask[5] = { 0x1f, 0xf, 0x7, 0x3, 0x1, }; /* return -1 if error. *pp is not updated in this case. max_len must be >= 1. The maximum length for a UTF8 byte sequence is 6 bytes. */ int unicode_from_utf8(const uint8_t *p, int max_len, const uint8_t **pp) { int l, c, b, i; c = *p++; if (c < 0x80) { *pp = p; return c; } switch(c) { case 0xc0 ... 0xdf: l = 1; break; case 0xe0 ... 0xef: l = 2; break; case 0xf0 ... 0xf7: l = 3; break; case 0xf8 ... 0xfb: l = 4; break; case 0xfc ... 0xfd: l = 5; break; default: return -1; } /* check that we have enough characters */ if (l > (max_len - 1)) return -1; c &= utf8_first_code_mask[l - 1]; for(i = 0; i < l; i++) { b = *p++; if (b < 0x80 || b >= 0xc0) return -1; c = (c << 6) | (b & 0x3f); } if (c < utf8_min_code[l - 1]) return -1; *pp = p; return c; } #if 0 #if defined(EMSCRIPTEN) || defined(__ANDROID__) static void *rqsort_arg; static int (*rqsort_cmp)(const void *, const void *, void *); static int rqsort_cmp2(const void *p1, const void *p2) { return rqsort_cmp(p1, p2, rqsort_arg); } /* not reentrant, but not needed with emscripten */ void rqsort(void *base, size_t nmemb, size_t size, int (*cmp)(const void *, const void *, void *), void *arg) { rqsort_arg = arg; rqsort_cmp = cmp; qsort(base, nmemb, size, rqsort_cmp2); } #endif #else typedef void (*exchange_f)(void *a, void *b, size_t size); typedef int (*cmp_f)(const void *, const void *, void *opaque); static void exchange_bytes(void *a, void *b, size_t size) { uint8_t *ap = (uint8_t *)a; uint8_t *bp = (uint8_t *)b; while (size-- != 0) { uint8_t t = *ap; *ap++ = *bp; *bp++ = t; } } static void exchange_one_byte(void *a, void *b, size_t size) { uint8_t *ap = (uint8_t *)a; uint8_t *bp = (uint8_t *)b; uint8_t t = *ap; *ap = *bp; *bp = t; } static void exchange_int16s(void *a, void *b, size_t size) { uint16_t *ap = (uint16_t *)a; uint16_t *bp = (uint16_t *)b; for (size /= sizeof(uint16_t); size-- != 0;) { uint16_t t = *ap; *ap++ = *bp; *bp++ = t; } } static void exchange_one_int16(void *a, void *b, size_t size) { uint16_t *ap = (uint16_t *)a; uint16_t *bp = (uint16_t *)b; uint16_t t = *ap; *ap = *bp; *bp = t; } static void exchange_int32s(void *a, void *b, size_t size) { uint32_t *ap = (uint32_t *)a; uint32_t *bp = (uint32_t *)b; for (size /= sizeof(uint32_t); size-- != 0;) { uint32_t t = *ap; *ap++ = *bp; *bp++ = t; } } static void exchange_one_int32(void *a, void *b, size_t size) { uint32_t *ap = (uint32_t *)a; uint32_t *bp = (uint32_t *)b; uint32_t t = *ap; *ap = *bp; *bp = t; } static void exchange_int64s(void *a, void *b, size_t size) { uint64_t *ap = (uint64_t *)a; uint64_t *bp = (uint64_t *)b; for (size /= sizeof(uint64_t); size-- != 0;) { uint64_t t = *ap; *ap++ = *bp; *bp++ = t; } } static void exchange_one_int64(void *a, void *b, size_t size) { uint64_t *ap = (uint64_t *)a; uint64_t *bp = (uint64_t *)b; uint64_t t = *ap; *ap = *bp; *bp = t; } static void exchange_int128s(void *a, void *b, size_t size) { uint64_t *ap = (uint64_t *)a; uint64_t *bp = (uint64_t *)b; for (size /= sizeof(uint64_t) * 2; size-- != 0; ap += 2, bp += 2) { uint64_t t = ap[0]; uint64_t u = ap[1]; ap[0] = bp[0]; ap[1] = bp[1]; bp[0] = t; bp[1] = u; } } static void exchange_one_int128(void *a, void *b, size_t size) { uint64_t *ap = (uint64_t *)a; uint64_t *bp = (uint64_t *)b; uint64_t t = ap[0]; uint64_t u = ap[1]; ap[0] = bp[0]; ap[1] = bp[1]; bp[0] = t; bp[1] = u; } static inline exchange_f exchange_func(const void *base, size_t size) { switch (((uintptr_t)base | (uintptr_t)size) & 15) { case 0: if (size == sizeof(uint64_t) * 2) return exchange_one_int128; else return exchange_int128s; case 8: if (size == sizeof(uint64_t)) return exchange_one_int64; else return exchange_int64s; case 4: case 12: if (size == sizeof(uint32_t)) return exchange_one_int32; else return exchange_int32s; case 2: case 6: case 10: case 14: if (size == sizeof(uint16_t)) return exchange_one_int16; else return exchange_int16s; default: if (size == 1) return exchange_one_byte; else return exchange_bytes; } } static void heapsortx(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque) { uint8_t *basep = (uint8_t *)base; size_t i, n, c, r; exchange_f swap = exchange_func(base, size); if (nmemb > 1) { i = (nmemb / 2) * size; n = nmemb * size; while (i > 0) { i -= size; for (r = i; (c = r * 2 + size) < n; r = c) { if (c < n - size && cmp(basep + c, basep + c + size, opaque) <= 0) c += size; if (cmp(basep + r, basep + c, opaque) > 0) break; swap(basep + r, basep + c, size); } } for (i = n - size; i > 0; i -= size) { swap(basep, basep + i, size); for (r = 0; (c = r * 2 + size) < i; r = c) { if (c < i - size && cmp(basep + c, basep + c + size, opaque) <= 0) c += size; if (cmp(basep + r, basep + c, opaque) > 0) break; swap(basep + r, basep + c, size); } } } } static inline void *med3(void *a, void *b, void *c, cmp_f cmp, void *opaque) { return cmp(a, b, opaque) < 0 ? (cmp(b, c, opaque) < 0 ? b : (cmp(a, c, opaque) < 0 ? c : a )) : (cmp(b, c, opaque) > 0 ? b : (cmp(a, c, opaque) < 0 ? a : c )); } /* pointer based version with local stack and insertion sort threshhold */ void rqsort(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque) { struct { uint8_t *base; size_t count; int depth; } stack[50], *sp = stack; uint8_t *ptr, *pi, *pj, *plt, *pgt, *top, *m; size_t m4, i, lt, gt, span, span2; int c, depth; exchange_f swap = exchange_func(base, size); exchange_f swap_block = exchange_func(base, size | 128); if (nmemb < 2 || size <= 0) return; sp->base = (uint8_t *)base; sp->count = nmemb; sp->depth = 0; sp++; while (sp > stack) { sp--; ptr = sp->base; nmemb = sp->count; depth = sp->depth; while (nmemb > 6) { if (++depth > 50) { /* depth check to ensure worst case logarithmic time */ heapsortx(ptr, nmemb, size, cmp, opaque); nmemb = 0; break; } /* select median of 3 from 1/4, 1/2, 3/4 positions */ /* should use median of 5 or 9? */ m4 = (nmemb >> 2) * size; m = med3(ptr + m4, ptr + 2 * m4, ptr + 3 * m4, cmp, opaque); swap(ptr, m, size); /* move the pivot to the start or the array */ i = lt = 1; pi = plt = ptr + size; gt = nmemb; pj = pgt = top = ptr + nmemb * size; for (;;) { while (pi < pj && (c = cmp(ptr, pi, opaque)) >= 0) { if (c == 0) { swap(plt, pi, size); lt++; plt += size; } i++; pi += size; } while (pi < (pj -= size) && (c = cmp(ptr, pj, opaque)) <= 0) { if (c == 0) { gt--; pgt -= size; swap(pgt, pj, size); } } if (pi >= pj) break; swap(pi, pj, size); i++; pi += size; } /* array has 4 parts: * from 0 to lt excluded: elements identical to pivot * from lt to pi excluded: elements smaller than pivot * from pi to gt excluded: elements greater than pivot * from gt to n excluded: elements identical to pivot */ /* move elements identical to pivot in the middle of the array: */ /* swap values in ranges [0..lt[ and [i-lt..i[ swapping the smallest span between lt and i-lt is sufficient */ span = plt - ptr; span2 = pi - plt; lt = i - lt; if (span > span2) span = span2; swap_block(ptr, pi - span, span); /* swap values in ranges [gt..top[ and [i..top-(top-gt)[ swapping the smallest span between top-gt and gt-i is sufficient */ span = top - pgt; span2 = pgt - pi; pgt = top - span2; gt = nmemb - (gt - i); if (span > span2) span = span2; swap_block(pi, top - span, span); /* now array has 3 parts: * from 0 to lt excluded: elements smaller than pivot * from lt to gt excluded: elements identical to pivot * from gt to n excluded: elements greater than pivot */ /* stack the larger segment and keep processing the smaller one to minimize stack use for pathological distributions */ if (lt > nmemb - gt) { sp->base = ptr; sp->count = lt; sp->depth = depth; sp++; ptr = pgt; nmemb -= gt; } else { sp->base = pgt; sp->count = nmemb - gt; sp->depth = depth; sp++; nmemb = lt; } } /* Use insertion sort for small fragments */ for (pi = ptr + size, top = ptr + nmemb * size; pi < top; pi += size) { for (pj = pi; pj > ptr && cmp(pj - size, pj, opaque) > 0; pj -= size) swap(pj, pj - size, size); } } } #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/cutils.c
C
apache-2.0
16,925
/* * C utilities * * Copyright (c) 2017 Fabrice Bellard * Copyright (c) 2018 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef CUTILS_H #define CUTILS_H #include <stdlib.h> #include <inttypes.h> /* set if CPU is big endian */ #undef WORDS_BIGENDIAN #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define force_inline inline __attribute__((always_inline)) #define no_inline __attribute__((noinline)) #define __maybe_unused __attribute__((unused)) #define xglue(x, y) x ## y #define glue(x, y) xglue(x, y) #define stringify(s) tostring(s) #define tostring(s) #s #ifndef offsetof #define offsetof(type, field) ((size_t) &((type *)0)->field) #endif #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif typedef int BOOL; #ifndef FALSE enum { FALSE = 0, TRUE = 1, }; #endif void pstrcpy(char *buf, int buf_size, const char *str); char *pstrcat(char *buf, int buf_size, const char *s); int strstart(const char *str, const char *val, const char **ptr); int has_suffix(const char *str, const char *suffix); static inline int max_int(int a, int b) { if (a > b) return a; else return b; } static inline int min_int(int a, int b) { if (a < b) return a; else return b; } static inline uint32_t max_uint32(uint32_t a, uint32_t b) { if (a > b) return a; else return b; } static inline uint32_t min_uint32(uint32_t a, uint32_t b) { if (a < b) return a; else return b; } static inline int64_t max_int64(int64_t a, int64_t b) { if (a > b) return a; else return b; } static inline int64_t min_int64(int64_t a, int64_t b) { if (a < b) return a; else return b; } /* WARNING: undefined if a = 0 */ static inline int clz32(unsigned int a) { return __builtin_clz(a); } /* WARNING: undefined if a = 0 */ static inline int clz64(uint64_t a) { return __builtin_clzll(a); } /* WARNING: undefined if a = 0 */ static inline int ctz32(unsigned int a) { return __builtin_ctz(a); } /* WARNING: undefined if a = 0 */ static inline int ctz64(uint64_t a) { return __builtin_ctzll(a); } struct __attribute__((packed)) packed_u64 { uint64_t v; }; struct __attribute__((packed)) packed_u32 { uint32_t v; }; struct __attribute__((packed)) packed_u16 { uint16_t v; }; static inline uint64_t get_u64(const uint8_t *tab) { return ((const struct packed_u64 *)tab)->v; } static inline int64_t get_i64(const uint8_t *tab) { return (int64_t)((const struct packed_u64 *)tab)->v; } static inline void put_u64(uint8_t *tab, uint64_t val) { ((struct packed_u64 *)tab)->v = val; } static inline uint32_t get_u32(const uint8_t *tab) { return ((const struct packed_u32 *)tab)->v; } static inline int32_t get_i32(const uint8_t *tab) { return (int32_t)((const struct packed_u32 *)tab)->v; } static inline void put_u32(uint8_t *tab, uint32_t val) { ((struct packed_u32 *)tab)->v = val; } static inline uint32_t get_u16(const uint8_t *tab) { return ((const struct packed_u16 *)tab)->v; } static inline int32_t get_i16(const uint8_t *tab) { return (int16_t)((const struct packed_u16 *)tab)->v; } static inline void put_u16(uint8_t *tab, uint16_t val) { ((struct packed_u16 *)tab)->v = val; } static inline uint32_t get_u8(const uint8_t *tab) { return *tab; } static inline int32_t get_i8(const uint8_t *tab) { return (int8_t)*tab; } static inline void put_u8(uint8_t *tab, uint8_t val) { *tab = val; } static inline uint16_t bswap16(uint16_t x) { return (x >> 8) | (x << 8); } static inline uint32_t bswap32(uint32_t v) { return ((v & 0xff000000) >> 24) | ((v & 0x00ff0000) >> 8) | ((v & 0x0000ff00) << 8) | ((v & 0x000000ff) << 24); } static inline uint64_t bswap64(uint64_t v) { return ((v & ((uint64_t)0xff << (7 * 8))) >> (7 * 8)) | ((v & ((uint64_t)0xff << (6 * 8))) >> (5 * 8)) | ((v & ((uint64_t)0xff << (5 * 8))) >> (3 * 8)) | ((v & ((uint64_t)0xff << (4 * 8))) >> (1 * 8)) | ((v & ((uint64_t)0xff << (3 * 8))) << (1 * 8)) | ((v & ((uint64_t)0xff << (2 * 8))) << (3 * 8)) | ((v & ((uint64_t)0xff << (1 * 8))) << (5 * 8)) | ((v & ((uint64_t)0xff << (0 * 8))) << (7 * 8)); } /* XXX: should take an extra argument to pass slack information to the caller */ typedef void *DynBufReallocFunc(void *opaque, void *ptr, size_t size); typedef struct DynBuf { uint8_t *buf; size_t size; size_t allocated_size; BOOL error; /* true if a memory allocation error occurred */ DynBufReallocFunc *realloc_func; void *opaque; /* for realloc_func */ } DynBuf; void dbuf_init(DynBuf *s); void dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func); int dbuf_realloc(DynBuf *s, size_t new_size); int dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len); int dbuf_put(DynBuf *s, const uint8_t *data, size_t len); int dbuf_put_self(DynBuf *s, size_t offset, size_t len); int dbuf_putc(DynBuf *s, uint8_t c); int dbuf_putstr(DynBuf *s, const char *str); static inline int dbuf_put_u16(DynBuf *s, uint16_t val) { return dbuf_put(s, (uint8_t *)&val, 2); } static inline int dbuf_put_u32(DynBuf *s, uint32_t val) { return dbuf_put(s, (uint8_t *)&val, 4); } static inline int dbuf_put_u64(DynBuf *s, uint64_t val) { return dbuf_put(s, (uint8_t *)&val, 8); } int __attribute__((format(printf, 2, 3))) dbuf_printf(DynBuf *s, const char *fmt, ...); void dbuf_free(DynBuf *s); static inline BOOL dbuf_error(DynBuf *s) { return s->error; } static inline void dbuf_set_error(DynBuf *s) { s->error = TRUE; } #define UTF8_CHAR_LEN_MAX 6 int unicode_to_utf8(uint8_t *buf, unsigned int c); int unicode_from_utf8(const uint8_t *p, int max_len, const uint8_t **pp); static inline int from_hex(int c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'A' && c <= 'F') return c - 'A' + 10; else if (c >= 'a' && c <= 'f') return c - 'a' + 10; else return -1; } void rqsort(void *base, size_t nmemb, size_t size, int (*cmp)(const void *, const void *, void *), void *arg); #endif /* CUTILS_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/cutils.h
C
apache-2.0
7,403
/* * QuickJS: Example of C module * * Copyright (c) 2017-2018 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "../quickjs.h" #define countof(x) (sizeof(x) / sizeof((x)[0])) static int fib(int n) { if (n <= 0) return 0; else if (n == 1) return 1; else return fib(n - 1) + fib(n - 2); } static JSValue js_fib(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int n, res; if (JS_ToInt32(ctx, &n, argv[0])) return JS_EXCEPTION; res = fib(n); return JS_NewInt32(ctx, res); } static const JSCFunctionListEntry js_fib_funcs[] = { JS_CFUNC_DEF("fib", 1, js_fib ), }; static int js_fib_init(JSContext *ctx, JSModuleDef *m) { return JS_SetModuleExportList(ctx, m, js_fib_funcs, countof(js_fib_funcs)); } #ifdef JS_SHARED_LIBRARY #define JS_INIT_MODULE js_init_module #else #define JS_INIT_MODULE js_init_module_fib #endif JSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_fib_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_fib_funcs, countof(js_fib_funcs)); return m; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/fib.c
C
apache-2.0
2,291
/* fib module */ export function fib(n) { if (n <= 0) return 0; else if (n == 1) return 1; else return fib(n - 1) + fib(n - 2); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/fib_module.js
JavaScript
apache-2.0
166
console.log("Hello World");
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/hello.js
JavaScript
apache-2.0
28
/* example of JS module */ import { fib } from "./fib_module.js"; console.log("Hello World"); console.log("fib(10)=", fib(10));
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/hello_module.js
JavaScript
apache-2.0
130
/* * PI computation in Javascript using the QuickJS bigdecimal type * (decimal floating point) */ "use strict"; /* compute PI with a precision of 'prec' digits */ function calc_pi(prec) { const CHUD_A = 13591409m; const CHUD_B = 545140134m; const CHUD_C = 640320m; const CHUD_C3 = 10939058860032000m; /* C^3/24 */ const CHUD_DIGITS_PER_TERM = 14.18164746272548; /* log10(C/12)*3 */ /* return [P, Q, G] */ function chud_bs(a, b, need_G) { var c, P, Q, G, P1, Q1, G1, P2, Q2, G2, b1; if (a == (b - 1n)) { b1 = BigDecimal(b); G = (2m * b1 - 1m) * (6m * b1 - 1m) * (6m * b1 - 5m); P = G * (CHUD_B * b1 + CHUD_A); if (b & 1n) P = -P; G = G; Q = b1 * b1 * b1 * CHUD_C3; } else { c = (a + b) >> 1n; [P1, Q1, G1] = chud_bs(a, c, true); [P2, Q2, G2] = chud_bs(c, b, need_G); P = P1 * Q2 + P2 * G1; Q = Q1 * Q2; if (need_G) G = G1 * G2; else G = 0m; } return [P, Q, G]; } var n, P, Q, G; /* number of serie terms */ n = BigInt(Math.ceil(prec / CHUD_DIGITS_PER_TERM)) + 10n; [P, Q, G] = chud_bs(0n, n, false); Q = BigDecimal.div(Q, (P + Q * CHUD_A), { roundingMode: "half-even", maximumSignificantDigits: prec }); G = (CHUD_C / 12m) * BigDecimal.sqrt(CHUD_C, { roundingMode: "half-even", maximumSignificantDigits: prec }); return Q * G; } (function() { var r, n_digits, n_bits; if (typeof scriptArgs != "undefined") { if (scriptArgs.length < 2) { print("usage: pi n_digits"); return; } n_digits = scriptArgs[1] | 0; } else { n_digits = 1000; } /* we add more digits to reduce the probability of bad rounding for the last digits */ r = calc_pi(n_digits + 20); print(r.toFixed(n_digits, "down")); })();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/pi_bigdecimal.js
JavaScript
apache-2.0
2,128
/* * PI computation in Javascript using the QuickJS bigfloat type * (binary floating point) */ "use strict"; /* compute PI with a precision of 'prec' bits */ function calc_pi() { const CHUD_A = 13591409n; const CHUD_B = 545140134n; const CHUD_C = 640320n; const CHUD_C3 = 10939058860032000n; /* C^3/24 */ const CHUD_BITS_PER_TERM = 47.11041313821584202247; /* log2(C/12)*3 */ /* return [P, Q, G] */ function chud_bs(a, b, need_G) { var c, P, Q, G, P1, Q1, G1, P2, Q2, G2; if (a == (b - 1n)) { G = (2n * b - 1n) * (6n * b - 1n) * (6n * b - 5n); P = BigFloat(G * (CHUD_B * b + CHUD_A)); if (b & 1n) P = -P; G = BigFloat(G); Q = BigFloat(b * b * b * CHUD_C3); } else { c = (a + b) >> 1n; [P1, Q1, G1] = chud_bs(a, c, true); [P2, Q2, G2] = chud_bs(c, b, need_G); P = P1 * Q2 + P2 * G1; Q = Q1 * Q2; if (need_G) G = G1 * G2; else G = 0l; } return [P, Q, G]; } var n, P, Q, G; /* number of serie terms */ n = BigInt(Math.ceil(BigFloatEnv.prec / CHUD_BITS_PER_TERM)) + 10n; [P, Q, G] = chud_bs(0n, n, false); Q = Q / (P + Q * BigFloat(CHUD_A)); G = BigFloat((CHUD_C / 12n)) * BigFloat.sqrt(BigFloat(CHUD_C)); return Q * G; } (function() { var r, n_digits, n_bits; if (typeof scriptArgs != "undefined") { if (scriptArgs.length < 2) { print("usage: pi n_digits"); return; } n_digits = scriptArgs[1]; } else { n_digits = 1000; } n_bits = Math.ceil(n_digits * Math.log2(10)); /* we add more bits to reduce the probability of bad rounding for the last digits */ BigFloatEnv.setPrec( () => { r = calc_pi(); print(r.toFixed(n_digits, BigFloatEnv.RNDZ)); }, n_bits + 32); })();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/pi_bigfloat.js
JavaScript
apache-2.0
1,977
/* * PI computation in Javascript using the BigInt type */ "use strict"; /* return floor(log2(a)) for a > 0 and 0 for a = 0 */ function floor_log2(a) { var k_max, a1, k, i; k_max = 0n; while ((a >> (2n ** k_max)) != 0n) { k_max++; } k = 0n; a1 = a; for(i = k_max - 1n; i >= 0n; i--) { a1 = a >> (2n ** i); if (a1 != 0n) { a = a1; k |= (1n << i); } } return k; } /* return ceil(log2(a)) for a > 0 */ function ceil_log2(a) { return floor_log2(a - 1n) + 1n; } /* return floor(sqrt(a)) (not efficient but simple) */ function int_sqrt(a) { var l, u, s; if (a == 0n) return a; l = ceil_log2(a); u = 1n << ((l + 1n) / 2n); /* u >= floor(sqrt(a)) */ for(;;) { s = u; u = ((a / s) + s) / 2n; if (u >= s) break; } return s; } /* return pi * 2**prec */ function calc_pi(prec) { const CHUD_A = 13591409n; const CHUD_B = 545140134n; const CHUD_C = 640320n; const CHUD_C3 = 10939058860032000n; /* C^3/24 */ const CHUD_BITS_PER_TERM = 47.11041313821584202247; /* log2(C/12)*3 */ /* return [P, Q, G] */ function chud_bs(a, b, need_G) { var c, P, Q, G, P1, Q1, G1, P2, Q2, G2; if (a == (b - 1n)) { G = (2n * b - 1n) * (6n * b - 1n) * (6n * b - 5n); P = G * (CHUD_B * b + CHUD_A); if (b & 1n) P = -P; Q = b * b * b * CHUD_C3; } else { c = (a + b) >> 1n; [P1, Q1, G1] = chud_bs(a, c, true); [P2, Q2, G2] = chud_bs(c, b, need_G); P = P1 * Q2 + P2 * G1; Q = Q1 * Q2; if (need_G) G = G1 * G2; else G = 0n; } return [P, Q, G]; } var n, P, Q, G; /* number of serie terms */ n = BigInt(Math.ceil(Number(prec) / CHUD_BITS_PER_TERM)) + 10n; [P, Q, G] = chud_bs(0n, n, false); Q = (CHUD_C / 12n) * (Q << prec) / (P + Q * CHUD_A); G = int_sqrt(CHUD_C << (2n * prec)); return (Q * G) >> prec; } function main(args) { var r, n_digits, n_bits, out; if (args.length < 1) { print("usage: pi n_digits"); return; } n_digits = args[0] | 0; /* we add more bits to reduce the probability of bad rounding for the last digits */ n_bits = BigInt(Math.ceil(n_digits * Math.log2(10))) + 32n; r = calc_pi(n_bits); r = ((10n ** BigInt(n_digits)) * r) >> n_bits; out = r.toString(); print(out[0] + "." + out.slice(1)); } var args; if (typeof scriptArgs != "undefined") { args = scriptArgs; args.shift(); } else if (typeof arguments != "undefined") { args = arguments; } else { /* default: 1000 digits */ args=[1000]; } main(args);
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/pi_bigint.js
JavaScript
apache-2.0
2,834
/* * QuickJS: Example of C module with a class * * Copyright (c) 2019 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "../quickjs.h" #include <math.h> #define countof(x) (sizeof(x) / sizeof((x)[0])) /* Point Class */ typedef struct { int x; int y; } JSPointData; static JSClassID js_point_class_id; static void js_point_finalizer(JSRuntime *rt, JSValue val) { JSPointData *s = JS_GetOpaque(val, js_point_class_id); /* Note: 's' can be NULL in case JS_SetOpaque() was not called */ js_free_rt(rt, s); } static JSValue js_point_ctor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv) { JSPointData *s; JSValue obj = JS_UNDEFINED; JSValue proto; s = js_mallocz(ctx, sizeof(*s)); if (!s) return JS_EXCEPTION; if (JS_ToInt32(ctx, &s->x, argv[0])) goto fail; if (JS_ToInt32(ctx, &s->y, argv[1])) goto fail; /* using new_target to get the prototype is necessary when the class is extended. */ proto = JS_GetPropertyStr(ctx, new_target, "prototype"); if (JS_IsException(proto)) goto fail; obj = JS_NewObjectProtoClass(ctx, proto, js_point_class_id); JS_FreeValue(ctx, proto); if (JS_IsException(obj)) goto fail; JS_SetOpaque(obj, s); return obj; fail: js_free(ctx, s); JS_FreeValue(ctx, obj); return JS_EXCEPTION; } static JSValue js_point_get_xy(JSContext *ctx, JSValueConst this_val, int magic) { JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id); if (!s) return JS_EXCEPTION; if (magic == 0) return JS_NewInt32(ctx, s->x); else return JS_NewInt32(ctx, s->y); } static JSValue js_point_set_xy(JSContext *ctx, JSValueConst this_val, JSValue val, int magic) { JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id); int v; if (!s) return JS_EXCEPTION; if (JS_ToInt32(ctx, &v, val)) return JS_EXCEPTION; if (magic == 0) s->x = v; else s->y = v; return JS_UNDEFINED; } static JSValue js_point_norm(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id); if (!s) return JS_EXCEPTION; return JS_NewFloat64(ctx, sqrt((double)s->x * s->x + (double)s->y * s->y)); } static JSClassDef js_point_class = { "Point", .finalizer = js_point_finalizer, }; static const JSCFunctionListEntry js_point_proto_funcs[] = { JS_CGETSET_MAGIC_DEF("x", js_point_get_xy, js_point_set_xy, 0), JS_CGETSET_MAGIC_DEF("y", js_point_get_xy, js_point_set_xy, 1), JS_CFUNC_DEF("norm", 0, js_point_norm), }; static int js_point_init(JSContext *ctx, JSModuleDef *m) { JSValue point_proto, point_class; /* create the Point class */ JS_NewClassID(&js_point_class_id); JS_NewClass(JS_GetRuntime(ctx), js_point_class_id, &js_point_class); point_proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, point_proto, js_point_proto_funcs, countof(js_point_proto_funcs)); point_class = JS_NewCFunction2(ctx, js_point_ctor, "Point", 2, JS_CFUNC_constructor, 0); /* set proto.constructor and ctor.prototype */ JS_SetConstructor(ctx, point_class, point_proto); JS_SetClassProto(ctx, js_point_class_id, point_proto); JS_SetModuleExport(ctx, m, "Point", point_class); return 0; } JSModuleDef *js_init_module(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_point_init); if (!m) return NULL; JS_AddModuleExport(ctx, m, "Point"); return m; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/point.c
C
apache-2.0
4,817
/* example of JS module importing a C module */ import { fib } from "./fib.so"; console.log("Hello World"); console.log("fib(10)=", fib(10));
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/test_fib.js
JavaScript
apache-2.0
144
/* example of JS module importing a C module */ import { Point } from "./point.so"; function assert(b, str) { if (b) { return; } else { throw Error("assertion failed: " + str); } } class ColorPoint extends Point { constructor(x, y, color) { super(x, y); this.color = color; } get_color() { return this.color; } }; function main() { var pt, pt2; pt = new Point(2, 3); assert(pt.x === 2); assert(pt.y === 3); pt.x = 4; assert(pt.x === 4); assert(pt.norm() == 5); pt2 = new ColorPoint(2, 3, 0xffffff); assert(pt2.x === 2); assert(pt2.color === 0xffffff); assert(pt2.get_color() === 0xffffff); } main();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/examples/test_point.js
JavaScript
apache-2.0
718
make qjsc
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/gen_qjsc.sh
Shell
apache-2.0
10
/* * Javascript Compressor * * Copyright (c) 2008-2018 Fabrice Bellard * Copyright (c) 2017-2018 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <getopt.h> #include <stdarg.h> #include <string.h> #include <inttypes.h> #include <unistd.h> #include "cutils.h" typedef struct JSToken { int tok; char buf[20]; char *str; int len; int size; int line_num; /* line number for start of token */ int lines; /* number of embedded linefeeds in token */ } JSToken; enum { TOK_EOF = 256, TOK_IDENT, TOK_STR1, TOK_STR2, TOK_STR3, TOK_NUM, TOK_COM, TOK_LCOM, }; void tok_reset(JSToken *tt) { if (tt->str != tt->buf) { free(tt->str); tt->str = tt->buf; tt->size = sizeof(tt->buf); } tt->len = 0; } void tok_add_ch(JSToken *tt, int c) { if (tt->len + 1 > tt->size) { tt->size *= 2; if (tt->str == tt->buf) { tt->str = malloc(tt->size); memcpy(tt->str, tt->buf, tt->len); } else { tt->str = realloc(tt->str, tt->size); } } tt->str[tt->len++] = c; } FILE *infile; const char *filename; int output_line_num; int line_num; int ch; JSToken tokc; int skip_mask; #define DEFINE_MAX 20 char *define_tab[DEFINE_MAX]; int define_len; void error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (filename) { fprintf(stderr, "%s:%d: ", filename, line_num); } else { fprintf(stderr, "jscompress: "); } vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); exit(1); } void define_symbol(const char *def) { int i; for (i = 0; i < define_len; i++) { if (!strcmp(tokc.str, define_tab[i])) return; } if (define_len >= DEFINE_MAX) error("too many defines"); define_tab[define_len++] = strdup(def); } void undefine_symbol(const char *def) { int i, j; for (i = j = 0; i < define_len; i++) { if (!strcmp(tokc.str, define_tab[i])) { free(define_tab[i]); } else { define_tab[j++] = define_tab[i]; } } define_len = j; } const char *find_symbol(const char *def) { int i; for (i = 0; i < define_len; i++) { if (!strcmp(tokc.str, define_tab[i])) return "1"; } return NULL; } void next(void); void nextch(void) { ch = fgetc(infile); if (ch == '\n') line_num++; } int skip_blanks(void) { for (;;) { next(); if (tokc.tok != ' ' && tokc.tok != '\t' && tokc.tok != TOK_COM && tokc.tok != TOK_LCOM) return tokc.tok; } } void parse_directive(void) { int ifdef, mask = skip_mask; /* simplistic preprocessor: #define / #undef / #ifdef / #ifndef / #else / #endif no symbol substitution. */ skip_mask = 0; /* disable skipping to parse preprocessor line */ nextch(); if (skip_blanks() != TOK_IDENT) error("expected preprocessing directive after #"); if (!strcmp(tokc.str, "define")) { if (skip_blanks() != TOK_IDENT) error("expected identifier after #define"); define_symbol(tokc.str); } else if (!strcmp(tokc.str, "undef")) { if (skip_blanks() != TOK_IDENT) error("expected identifier after #undef"); undefine_symbol(tokc.str); } else if ((ifdef = 1, !strcmp(tokc.str, "ifdef")) || (ifdef = 0, !strcmp(tokc.str, "ifndef"))) { if (skip_blanks() != TOK_IDENT) error("expected identifier after #ifdef/#ifndef"); mask = (mask << 2) | 2 | ifdef; if (find_symbol(tokc.str)) mask ^= 1; } else if (!strcmp(tokc.str, "else")) { if (!(mask & 2)) error("#else without a #if"); mask ^= 1; } else if (!strcmp(tokc.str, "endif")) { if (!(mask & 2)) error("#endif without a #if"); mask >>= 2; } else { error("unsupported preprocessing directive"); } if (skip_blanks() != '\n') error("extra characters on preprocessing line"); skip_mask = mask; } /* return -1 if invalid char */ static int hex_to_num(int ch) { if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; else if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10; else if (ch >= '0' && ch <= '9') return ch - '0'; else return -1; } void next(void) { again: tok_reset(&tokc); tokc.line_num = line_num; tokc.lines = 0; switch(ch) { case EOF: tokc.tok = TOK_EOF; if (skip_mask) error("missing #endif"); break; case 'a' ... 'z': case 'A' ... 'Z': case '_': case '$': tok_add_ch(&tokc, ch); nextch(); while ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || (ch == '_' || ch == '$')) { tok_add_ch(&tokc, ch); nextch(); } tok_add_ch(&tokc, '\0'); tokc.tok = TOK_IDENT; break; case '.': nextch(); if (ch >= '0' && ch <= '9') { tok_add_ch(&tokc, '.'); goto has_dot; } tokc.tok = '.'; break; case '0': tok_add_ch(&tokc, ch); nextch(); if (ch == 'x' || ch == 'X') { /* hexa */ tok_add_ch(&tokc, ch); nextch(); while ((ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') || (ch >= '0' && ch <= '9')) { tok_add_ch(&tokc, ch); nextch(); } tok_add_ch(&tokc, '\0'); tokc.tok = TOK_NUM; break; } goto has_digit; case '1' ... '9': tok_add_ch(&tokc, ch); nextch(); has_digit: /* decimal */ while (ch >= '0' && ch <= '9') { tok_add_ch(&tokc, ch); nextch(); } if (ch == '.') { tok_add_ch(&tokc, ch); nextch(); has_dot: while (ch >= '0' && ch <= '9') { tok_add_ch(&tokc, ch); nextch(); } } if (ch == 'e' || ch == 'E') { tok_add_ch(&tokc, ch); nextch(); if (ch == '+' || ch == '-') { tok_add_ch(&tokc, ch); nextch(); } while (ch >= '0' && ch <= '9') { tok_add_ch(&tokc, ch); nextch(); } } tok_add_ch(&tokc, '\0'); tokc.tok = TOK_NUM; break; case '`': { nextch(); while (ch != '`' && ch != EOF) { if (ch == '\\') { tok_add_ch(&tokc, ch); nextch(); if (ch == EOF) { error("unexpected char after '\\'"); } tok_add_ch(&tokc, ch); } else { tok_add_ch(&tokc, ch); nextch(); } } nextch(); tok_add_ch(&tokc, 0); tokc.tok = TOK_STR3; } break; case '\"': case '\'': { int n, i, c, hex_digit_count; int quote_ch; quote_ch = ch; nextch(); while (ch != quote_ch && ch != EOF) { if (ch == '\\') { nextch(); switch(ch) { case 'n': tok_add_ch(&tokc, '\n'); nextch(); break; case 'r': tok_add_ch(&tokc, '\r'); nextch(); break; case 't': tok_add_ch(&tokc, '\t'); nextch(); break; case 'v': tok_add_ch(&tokc, '\v'); nextch(); break; case '\"': case '\'': case '\\': tok_add_ch(&tokc, ch); nextch(); break; case '0' ... '7': n = 0; while (ch >= '0' && ch <= '7') { n = n * 8 + (ch - '0'); nextch(); } tok_add_ch(&tokc, n); break; case 'x': case 'u': if (ch == 'x') hex_digit_count = 2; else hex_digit_count = 4; nextch(); n = 0; for(i = 0; i < hex_digit_count; i++) { c = hex_to_num(ch); if (c < 0) error("unexpected char after '\\x'"); n = n * 16 + c; nextch(); } if (n >= 256) error("unicode is currently unsupported"); tok_add_ch(&tokc, n); break; default: error("unexpected char after '\\'"); } } else { /* XXX: should refuse embedded newlines */ tok_add_ch(&tokc, ch); nextch(); } } nextch(); tok_add_ch(&tokc, 0); if (quote_ch == '\'') tokc.tok = TOK_STR1; else tokc.tok = TOK_STR2; } break; case '/': nextch(); if (ch == '/') { tok_add_ch(&tokc, '/'); tok_add_ch(&tokc, ch); nextch(); while (ch != '\n' && ch != EOF) { tok_add_ch(&tokc, ch); nextch(); } tok_add_ch(&tokc, '\0'); tokc.tok = TOK_LCOM; } else if (ch == '*') { int last; tok_add_ch(&tokc, '/'); tok_add_ch(&tokc, ch); last = 0; for(;;) { nextch(); if (ch == EOF) error("unterminated comment"); if (ch == '\n') tokc.lines++; tok_add_ch(&tokc, ch); if (last == '*' && ch == '/') break; last = ch; } nextch(); tok_add_ch(&tokc, '\0'); tokc.tok = TOK_COM; } else { tokc.tok = '/'; } break; case '#': parse_directive(); goto again; case '\n': /* adjust line number */ tokc.line_num--; tokc.lines++; /* fall thru */ default: tokc.tok = ch; nextch(); break; } if (skip_mask & 1) goto again; } void print_tok(FILE *f, JSToken *tt) { /* keep output lines in sync with input lines */ while (output_line_num < tt->line_num) { putc('\n', f); output_line_num++; } switch(tt->tok) { case TOK_IDENT: case TOK_COM: case TOK_LCOM: fprintf(f, "%s", tt->str); break; case TOK_NUM: { unsigned long a; char *p; a = strtoul(tt->str, &p, 0); if (*p == '\0' && a <= 0x7fffffff) { /* must be an integer */ fprintf(f, "%d", (int)a); } else { fprintf(f, "%s", tt->str); } } break; case TOK_STR3: fprintf(f, "`%s`", tt->str); break; case TOK_STR1: case TOK_STR2: { int i, c, quote_ch; if (tt->tok == TOK_STR1) quote_ch = '\''; else quote_ch = '\"'; fprintf(f, "%c", quote_ch); for(i = 0; i < tt->len - 1; i++) { c = (uint8_t)tt->str[i]; switch(c) { case '\r': fprintf(f, "\\r"); break; case '\n': fprintf(f, "\\n"); break; case '\t': fprintf(f, "\\t"); break; case '\v': fprintf(f, "\\v"); break; case '\"': case '\'': if (c == quote_ch) fprintf(f, "\\%c", c); else fprintf(f, "%c", c); break; case '\\': fprintf(f, "\\\\"); break; default: /* XXX: no utf-8 support! */ if (c >= 32 && c <= 255) { fprintf(f, "%c", c); } else if (c <= 255) fprintf(f, "\\x%02x", c); else fprintf(f, "\\u%04x", c); break; } } fprintf(f, "%c", quote_ch); } break; default: if (tokc.tok >= 256) error("unsupported token in print_tok: %d", tt->tok); fprintf(f, "%c", tt->tok); break; } output_line_num += tt->lines; } /* check if token pasting could occur */ static BOOL compat_token(int c1, int c2) { if ((c1 == TOK_IDENT || c1 == TOK_NUM) && (c2 == TOK_IDENT || c2 == TOK_NUM)) return FALSE; if ((c1 == c2 && strchr("+-<>&|=*/.", c1)) || (c2 == '=' && strchr("+-<>&|!*/^%", c1)) || (c1 == '=' && c2 == '>') || (c1 == '/' && c2 == '*') || (c1 == '.' && c2 == TOK_NUM) || (c1 == TOK_NUM && c2 == '.')) return FALSE; return TRUE; } void js_compress(const char *filename, const char *outfilename, BOOL do_strip, BOOL keep_header) { FILE *outfile; int ltok, seen_space; line_num = 1; infile = fopen(filename, "rb"); if (!infile) { perror(filename); exit(1); } output_line_num = 1; outfile = fopen(outfilename, "wb"); if (!outfile) { perror(outfilename); exit(1); } nextch(); next(); ltok = 0; seen_space = 0; if (do_strip) { if (keep_header) { while (tokc.tok == ' ' || tokc.tok == '\n' || tokc.tok == '\t' || tokc.tok == '\v' || tokc.tok == '\b' || tokc.tok == '\f') { seen_space = 1; next(); } if (tokc.tok == TOK_COM) { print_tok(outfile, &tokc); //fprintf(outfile, "\n"); ltok = tokc.tok; seen_space = 0; next(); } } for(;;) { if (tokc.tok == TOK_EOF) break; if (tokc.tok == ' ' || tokc.tok == '\r' || tokc.tok == '\t' || tokc.tok == '\v' || tokc.tok == '\b' || tokc.tok == '\f' || tokc.tok == TOK_LCOM || tokc.tok == TOK_COM) { /* don't print spaces or comments */ seen_space = 1; } else if (tokc.tok == TOK_STR3) { print_tok(outfile, &tokc); ltok = tokc.tok; seen_space = 0; } else if (tokc.tok == TOK_STR1 || tokc.tok == TOK_STR2) { int count, i; /* find the optimal quote char */ count = 0; for(i = 0; i < tokc.len; i++) { if (tokc.str[i] == '\'') count++; else if (tokc.str[i] == '\"') count--; } if (count > 0) tokc.tok = TOK_STR2; else if (count < 0) tokc.tok = TOK_STR1; print_tok(outfile, &tokc); ltok = tokc.tok; seen_space = 0; } else { if (seen_space && !compat_token(ltok, tokc.tok)) { fprintf(outfile, " "); } print_tok(outfile, &tokc); ltok = tokc.tok; seen_space = 0; } next(); } } else { /* just handle preprocessing */ while (tokc.tok != TOK_EOF) { print_tok(outfile, &tokc); next(); } } fclose(outfile); fclose(infile); } #define HASH_SIZE 30011 #define MATCH_LEN_MIN 3 #define MATCH_LEN_MAX (4 + 63) #define DIST_MAX 65535 static int find_longest_match(int *pdist, const uint8_t *src, int src_len, const int *hash_next, int cur_pos) { int pos, i, match_len, match_pos, pos_min, len_max; len_max = min_int(src_len - cur_pos, MATCH_LEN_MAX); match_len = 0; match_pos = 0; pos_min = max_int(cur_pos - DIST_MAX - 1, 0); pos = hash_next[cur_pos]; while (pos >= pos_min) { for(i = 0; i < len_max; i++) { if (src[cur_pos + i] != src[pos + i]) break; } if (i > match_len) { match_len = i; match_pos = pos; } pos = hash_next[pos]; } *pdist = cur_pos - match_pos - 1; return match_len; } int lz_compress(uint8_t **pdst, const uint8_t *src, int src_len) { int *hash_table, *hash_next; uint32_t h, v; int i, dist, len, len1, dist1; uint8_t *dst, *q; /* build the hash table */ hash_table = malloc(sizeof(hash_table[0]) * HASH_SIZE); for(i = 0; i < HASH_SIZE; i++) hash_table[i] = -1; hash_next = malloc(sizeof(hash_next[0]) * src_len); for(i = 0; i < src_len; i++) hash_next[i] = -1; for(i = 0; i < src_len - MATCH_LEN_MIN + 1; i++) { h = ((src[i] << 16) | (src[i + 1] << 8) | src[i + 2]) % HASH_SIZE; hash_next[i] = hash_table[h]; hash_table[h] = i; } for(;i < src_len; i++) { hash_next[i] = -1; } free(hash_table); dst = malloc(src_len + 4); /* never larger than the source */ q = dst; *q++ = src_len >> 24; *q++ = src_len >> 16; *q++ = src_len >> 8; *q++ = src_len >> 0; /* compress */ i = 0; while (i < src_len) { if (src[i] >= 128) return -1; len = find_longest_match(&dist, src, src_len, hash_next, i); if (len >= MATCH_LEN_MIN) { /* heuristic: see if better length just after */ len1 = find_longest_match(&dist1, src, src_len, hash_next, i + 1); if (len1 > len) goto no_match; } if (len < MATCH_LEN_MIN) { no_match: *q++ = src[i]; i++; } else if (len <= (3 + 15) && dist < (1 << 10)) { v = 0x8000 | ((len - 3) << 10) | dist; *q++ = v >> 8; *q++ = v; i += len; } else if (len >= 4 && len <= (4 + 63) && dist < (1 << 16)) { v = 0xc00000 | ((len - 4) << 16) | dist; *q++ = v >> 16; *q++ = v >> 8; *q++ = v; i += len; } else { goto no_match; } } free(hash_next); *pdst = dst; return q - dst; } static int load_file(uint8_t **pbuf, const char *filename) { FILE *f; uint8_t *buf; int buf_len; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } fseek(f, 0, SEEK_END); buf_len = ftell(f); fseek(f, 0, SEEK_SET); buf = malloc(buf_len + 1); fread(buf, 1, buf_len, f); buf[buf_len] = '\0'; fclose(f); *pbuf = buf; return buf_len; } static void save_file(const char *filename, const uint8_t *buf, int buf_len) { FILE *f; f = fopen(filename, "wb"); if (!f) { perror(filename); exit(1); } fwrite(buf, 1, buf_len, f); fclose(f); } static void save_c_source(const char *filename, const uint8_t *buf, int buf_len, const char *var_name) { FILE *f; int i; f = fopen(filename, "wb"); if (!f) { perror(filename); exit(1); } fprintf(f, "/* This file is automatically generated - do not edit */\n\n"); fprintf(f, "const uint8_t %s[] = {\n", var_name); for(i = 0; i < buf_len; i++) { fprintf(f, " 0x%02x,", buf[i]); if ((i % 8) == 7 || (i == buf_len - 1)) fprintf(f, "\n"); } fprintf(f, "};\n"); fclose(f); } #define DEFAULT_OUTPUT_FILENAME "out.js" void help(void) { printf("jscompress version 1.0 Copyright (c) 2008-2018 Fabrice Bellard\n" "usage: jscompress [options] filename\n" "Javascript compressor\n" "\n" "-h print this help\n" "-n do not compress spaces\n" "-H keep the first comment\n" "-c compress to file\n" "-C name compress to C source ('name' is the variable name)\n" "-D symbol define preprocessor symbol\n" "-U symbol undefine preprocessor symbol\n" "-o outfile set the output filename (default=%s)\n", DEFAULT_OUTPUT_FILENAME); exit(1); } int main(int argc, char **argv) { int c, do_strip, keep_header, compress; const char *out_filename, *c_var, *fname; char tmpfilename[1024]; do_strip = 1; keep_header = 0; out_filename = DEFAULT_OUTPUT_FILENAME; compress = 0; c_var = NULL; for(;;) { c = getopt(argc, argv, "hno:HcC:D:U:"); if (c == -1) break; switch(c) { case 'h': help(); break; case 'n': do_strip = 0; break; case 'o': out_filename = optarg; break; case 'H': keep_header = 1; break; case 'c': compress = 1; break; case 'C': c_var = optarg; compress = 1; break; case 'D': define_symbol(optarg); break; case 'U': undefine_symbol(optarg); break; } } if (optind >= argc) help(); filename = argv[optind++]; if (compress) { #if defined(__ANDROID__) /* XXX: use another directory ? */ snprintf(tmpfilename, sizeof(tmpfilename), "out.%d", getpid()); #else snprintf(tmpfilename, sizeof(tmpfilename), "/tmp/out.%d", getpid()); #endif fname = tmpfilename; } else { fname = out_filename; } js_compress(filename, fname, do_strip, keep_header); if (compress) { uint8_t *buf1, *buf2; int buf1_len, buf2_len; buf1_len = load_file(&buf1, fname); unlink(fname); buf2_len = lz_compress(&buf2, buf1, buf1_len); if (buf2_len < 0) { fprintf(stderr, "Could not compress file (UTF8 chars are forbidden)\n"); exit(1); } if (c_var) { save_c_source(out_filename, buf2, buf2_len, c_var); } else { save_file(out_filename, buf2, buf2_len); } free(buf1); free(buf2); } return 0; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/jscompress.c
C
apache-2.0
25,033