node.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. // Module for interfacing with system
  2. #include "module.h"
  3. #include "lauxlib.h"
  4. #include "ldebug.h"
  5. #include "ldo.h"
  6. #include "lfunc.h"
  7. #include "lmem.h"
  8. #include "lobject.h"
  9. #include "lstate.h"
  10. #include "legc.h"
  11. #include "lopcodes.h"
  12. #include "lstring.h"
  13. #include "lundump.h"
  14. #include "platform.h"
  15. #include "lrodefs.h"
  16. #include "c_types.h"
  17. #include "c_string.h"
  18. #include "driver/uart.h"
  19. #include "user_interface.h"
  20. #include "flash_api.h"
  21. #include "vfs.h"
  22. #include "user_version.h"
  23. #include "rom.h"
  24. #include "task/task.h"
  25. #define CPU80MHZ 80
  26. #define CPU160MHZ 160
  27. // Lua: restart()
  28. static int node_restart( lua_State* L )
  29. {
  30. system_restart();
  31. return 0;
  32. }
  33. // Lua: dsleep( us, option )
  34. static int node_deepsleep( lua_State* L )
  35. {
  36. uint32 us;
  37. uint8 option;
  38. //us = luaL_checkinteger( L, 1 );
  39. // Set deleep option, skip if nil
  40. if ( lua_isnumber(L, 2) )
  41. {
  42. option = lua_tointeger(L, 2);
  43. if ( option < 0 || option > 4)
  44. return luaL_error( L, "wrong arg range" );
  45. else
  46. system_deep_sleep_set_option( option );
  47. }
  48. // Set deleep time, skip if nil
  49. if ( lua_isnumber(L, 1) )
  50. {
  51. us = luaL_checknumber(L, 1);
  52. // if ( us <= 0 )
  53. if ( us < 0 )
  54. return luaL_error( L, "wrong arg range" );
  55. else
  56. system_deep_sleep( us );
  57. }
  58. return 0;
  59. }
  60. // Lua: dsleep_set_options
  61. // Combined to dsleep( us, option )
  62. // static int node_deepsleep_setoption( lua_State* L )
  63. // {
  64. // s32 option;
  65. // option = luaL_checkinteger( L, 1 );
  66. // if ( option < 0 || option > 4)
  67. // return luaL_error( L, "wrong arg range" );
  68. // else
  69. // deep_sleep_set_option( option );
  70. // return 0;
  71. // }
  72. // Lua: info()
  73. static int node_info( lua_State* L )
  74. {
  75. lua_pushinteger(L, NODE_VERSION_MAJOR);
  76. lua_pushinteger(L, NODE_VERSION_MINOR);
  77. lua_pushinteger(L, NODE_VERSION_REVISION);
  78. lua_pushinteger(L, system_get_chip_id()); // chip id
  79. lua_pushinteger(L, spi_flash_get_id()); // flash id
  80. #if defined(FLASH_SAFE_API)
  81. lua_pushinteger(L, flash_safe_get_size_byte() / 1024); // flash size in KB
  82. #else
  83. lua_pushinteger(L, flash_rom_get_size_byte() / 1024); // flash size in KB
  84. #endif // defined(FLASH_SAFE_API)
  85. lua_pushinteger(L, flash_rom_get_mode());
  86. lua_pushinteger(L, flash_rom_get_speed());
  87. return 8;
  88. }
  89. // Lua: chipid()
  90. static int node_chipid( lua_State* L )
  91. {
  92. uint32_t id = system_get_chip_id();
  93. lua_pushinteger(L, id);
  94. return 1;
  95. }
  96. // deprecated, moved to adc module
  97. // Lua: readvdd33()
  98. // static int node_readvdd33( lua_State* L )
  99. // {
  100. // uint32_t vdd33 = readvdd33();
  101. // lua_pushinteger(L, vdd33);
  102. // return 1;
  103. // }
  104. // Lua: flashid()
  105. static int node_flashid( lua_State* L )
  106. {
  107. uint32_t id = spi_flash_get_id();
  108. lua_pushinteger( L, id );
  109. return 1;
  110. }
  111. // Lua: flashsize()
  112. static int node_flashsize( lua_State* L )
  113. {
  114. if (lua_type(L, 1) == LUA_TNUMBER)
  115. {
  116. flash_rom_set_size_byte(luaL_checkinteger(L, 1));
  117. }
  118. #if defined(FLASH_SAFE_API)
  119. uint32_t sz = flash_safe_get_size_byte();
  120. #else
  121. uint32_t sz = flash_rom_get_size_byte();
  122. #endif // defined(FLASH_SAFE_API)
  123. lua_pushinteger( L, sz );
  124. return 1;
  125. }
  126. // Lua: heap()
  127. static int node_heap( lua_State* L )
  128. {
  129. uint32_t sz = system_get_free_heap_size();
  130. lua_pushinteger(L, sz);
  131. return 1;
  132. }
  133. extern lua_Load gLoad;
  134. extern bool user_process_input(bool force);
  135. // Lua: input("string")
  136. static int node_input( lua_State* L )
  137. {
  138. size_t l = 0;
  139. const char *s = luaL_checklstring(L, 1, &l);
  140. if (s != NULL && l > 0 && l < LUA_MAXINPUT - 1)
  141. {
  142. lua_Load *load = &gLoad;
  143. if (load->line_position == 0) {
  144. c_memcpy(load->line, s, l);
  145. load->line[l + 1] = '\0';
  146. load->line_position = c_strlen(load->line) + 1;
  147. load->done = 1;
  148. NODE_DBG("Get command:\n");
  149. NODE_DBG(load->line); // buggy here
  150. NODE_DBG("\nResult(if any):\n");
  151. user_process_input(true);
  152. }
  153. }
  154. return 0;
  155. }
  156. static int output_redir_ref = LUA_NOREF;
  157. static int serial_debug = 1;
  158. void output_redirect(const char *str) {
  159. lua_State *L = lua_getstate();
  160. // if(c_strlen(str)>=TX_BUFF_SIZE){
  161. // NODE_ERR("output too long.\n");
  162. // return;
  163. // }
  164. if (output_redir_ref == LUA_NOREF) {
  165. uart0_sendStr(str);
  166. return;
  167. }
  168. if (serial_debug != 0) {
  169. uart0_sendStr(str);
  170. }
  171. lua_rawgeti(L, LUA_REGISTRYINDEX, output_redir_ref);
  172. lua_pushstring(L, str);
  173. lua_call(L, 1, 0); // this call back function should never user output.
  174. }
  175. // Lua: output(function(c), debug)
  176. static int node_output( lua_State* L )
  177. {
  178. // luaL_checkanyfunction(L, 1);
  179. if (lua_type(L, 1) == LUA_TFUNCTION || lua_type(L, 1) == LUA_TLIGHTFUNCTION) {
  180. lua_pushvalue(L, 1); // copy argument (func) to the top of stack
  181. if (output_redir_ref != LUA_NOREF)
  182. luaL_unref(L, LUA_REGISTRYINDEX, output_redir_ref);
  183. output_redir_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  184. } else { // unref the key press function
  185. if (output_redir_ref != LUA_NOREF)
  186. luaL_unref(L, LUA_REGISTRYINDEX, output_redir_ref);
  187. output_redir_ref = LUA_NOREF;
  188. serial_debug = 1;
  189. return 0;
  190. }
  191. if ( lua_isnumber(L, 2) )
  192. {
  193. serial_debug = lua_tointeger(L, 2);
  194. if (serial_debug != 0)
  195. serial_debug = 1;
  196. } else {
  197. serial_debug = 1; // default to 1
  198. }
  199. return 0;
  200. }
  201. static int writer(lua_State* L, const void* p, size_t size, void* u)
  202. {
  203. UNUSED(L);
  204. int file_fd = *( (int *)u );
  205. if (!file_fd)
  206. return 1;
  207. NODE_DBG("get fd:%d,size:%d\n", file_fd, size);
  208. if (size != 0 && (size != vfs_write(file_fd, (const char *)p, size)) )
  209. return 1;
  210. NODE_DBG("write fd:%d,size:%d\n", file_fd, size);
  211. return 0;
  212. }
  213. #define toproto(L,i) (clvalue(L->top+(i))->l.p)
  214. // Lua: compile(filename) -- compile lua file into lua bytecode, and save to .lc
  215. static int node_compile( lua_State* L )
  216. {
  217. Proto* f;
  218. int file_fd = 0;
  219. size_t len;
  220. const char *fname = luaL_checklstring( L, 1, &len );
  221. const char *basename = vfs_basename( fname );
  222. luaL_argcheck(L, c_strlen(basename) <= FS_OBJ_NAME_LEN && c_strlen(fname) == len, 1, "filename invalid");
  223. char *output = luaM_malloc( L, len+1 );
  224. c_strcpy(output, fname);
  225. // check here that filename end with ".lua".
  226. if (len < 4 || (c_strcmp( output + len - 4, ".lua") != 0) ) {
  227. luaM_free( L, output );
  228. return luaL_error(L, "not a .lua file");
  229. }
  230. output[c_strlen(output) - 2] = 'c';
  231. output[c_strlen(output) - 1] = '\0';
  232. NODE_DBG(output);
  233. NODE_DBG("\n");
  234. if (luaL_loadfsfile(L, fname) != 0) {
  235. luaM_free( L, output );
  236. return luaL_error(L, lua_tostring(L, -1));
  237. }
  238. f = toproto(L, -1);
  239. int stripping = 1; /* strip debug information? */
  240. file_fd = vfs_open(output, "w+");
  241. if (!file_fd)
  242. {
  243. luaM_free( L, output );
  244. return luaL_error(L, "cannot open/write to file");
  245. }
  246. lua_lock(L);
  247. int result = luaU_dump(L, f, writer, &file_fd, stripping);
  248. lua_unlock(L);
  249. if (vfs_flush(file_fd) != VFS_RES_OK) {
  250. // overwrite Lua error, like writer() does in case of a file io error
  251. result = 1;
  252. }
  253. vfs_close(file_fd);
  254. file_fd = 0;
  255. luaM_free( L, output );
  256. if (result == LUA_ERR_CC_INTOVERFLOW) {
  257. return luaL_error(L, "value too big or small for target integer type");
  258. }
  259. if (result == LUA_ERR_CC_NOTINTEGER) {
  260. return luaL_error(L, "target lua_Number is integral but fractional value found");
  261. }
  262. if (result == 1) { // result status generated by writer() or fs_flush() fail
  263. return luaL_error(L, "writing to file failed");
  264. }
  265. return 0;
  266. }
  267. // Task callback handler for node.task.post()
  268. static task_handle_t do_node_task_handle;
  269. static void do_node_task (task_param_t task_fn_ref, uint8_t prio)
  270. {
  271. lua_State* L = lua_getstate();
  272. lua_rawgeti(L, LUA_REGISTRYINDEX, (int)task_fn_ref);
  273. luaL_unref(L, LUA_REGISTRYINDEX, (int)task_fn_ref);
  274. lua_pushinteger(L, prio);
  275. lua_call(L, 1, 0);
  276. }
  277. // Lua: node.task.post([priority],task_cb) -- schedule a task for execution next
  278. static int node_task_post( lua_State* L )
  279. {
  280. int n = 1, Ltype = lua_type(L, 1);
  281. unsigned priority = TASK_PRIORITY_MEDIUM;
  282. if (Ltype == LUA_TNUMBER) {
  283. priority = (unsigned) luaL_checkint(L, 1);
  284. luaL_argcheck(L, priority <= TASK_PRIORITY_HIGH, 1, "invalid priority");
  285. Ltype = lua_type(L, ++n);
  286. }
  287. luaL_argcheck(L, Ltype == LUA_TFUNCTION || Ltype == LUA_TLIGHTFUNCTION, n, "invalid function");
  288. lua_pushvalue(L, n);
  289. int task_fn_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  290. if (!do_node_task_handle) // bind the task handle to do_node_task on 1st call
  291. do_node_task_handle = task_get_id(do_node_task);
  292. if(!task_post(priority, do_node_task_handle, (task_param_t)task_fn_ref)) {
  293. luaL_unref(L, LUA_REGISTRYINDEX, task_fn_ref);
  294. luaL_error(L, "Task queue overflow. Task not posted");
  295. }
  296. return 0;
  297. }
  298. // Lua: setcpufreq(mhz)
  299. // mhz is either CPU80MHZ od CPU160MHZ
  300. static int node_setcpufreq(lua_State* L)
  301. {
  302. // http://www.esp8266.com/viewtopic.php?f=21&t=1369
  303. uint32_t new_freq = luaL_checkinteger(L, 1);
  304. if (new_freq == CPU160MHZ){
  305. REG_SET_BIT(0x3ff00014, BIT(0));
  306. ets_update_cpu_frequency(CPU160MHZ);
  307. } else {
  308. REG_CLR_BIT(0x3ff00014, BIT(0));
  309. ets_update_cpu_frequency(CPU80MHZ);
  310. }
  311. new_freq = ets_get_cpu_frequency();
  312. lua_pushinteger(L, new_freq);
  313. return 1;
  314. }
  315. // Lua: code, reason [, exccause, epc1, epc2, epc3, excvaddr, depc ] = bootreason()
  316. static int node_bootreason (lua_State *L)
  317. {
  318. const struct rst_info *ri = system_get_rst_info ();
  319. uint32_t arr[8] = {
  320. rtc_get_reset_reason(),
  321. ri->reason,
  322. ri->exccause, ri->epc1, ri->epc2, ri->epc3, ri->excvaddr, ri->depc
  323. };
  324. int i, n = ((ri->reason != REASON_EXCEPTION_RST) ? 2 : 8);
  325. for (i = 0; i < n; ++i)
  326. lua_pushinteger (L, arr[i]);
  327. return n;
  328. }
  329. // Lua: restore()
  330. static int node_restore (lua_State *L)
  331. {
  332. system_restore();
  333. return 0;
  334. }
  335. #ifdef LUA_OPTIMIZE_DEBUG
  336. /* node.stripdebug([level[, function]]). 
  337. * level: 1 don't discard debug
  338. * 2 discard Local and Upvalue debug info
  339. * 3 discard Local, Upvalue and lineno debug info.
  340. * function: Function to be stripped as per setfenv except 0 not permitted.
  341. * If no arguments then the current default setting is returned.
  342. * If function is omitted, this is the default setting for future compiles
  343. * The function returns an estimated integer count of the bytes stripped.
  344. */
  345. static int node_stripdebug (lua_State *L) {
  346. int level;
  347. if (L->top == L->base) {
  348. lua_pushlightuserdata(L, &luaG_stripdebug );
  349. lua_gettable(L, LUA_REGISTRYINDEX);
  350. if (lua_isnil(L, -1)) {
  351. lua_pop(L, 1);
  352. lua_pushinteger(L, LUA_OPTIMIZE_DEBUG);
  353. }
  354. return 1;
  355. }
  356. level = luaL_checkint(L, 1);
  357. if ((level <= 0) || (level > 3)) luaL_argerror(L, 1, "must in range 1-3");
  358. if (L->top == L->base + 1) {
  359. /* Store the default level in the registry if no function parameter */
  360. lua_pushlightuserdata(L, &luaG_stripdebug);
  361. lua_pushinteger(L, level);
  362. lua_settable(L, LUA_REGISTRYINDEX);
  363. lua_settop(L,0);
  364. return 0;
  365. }
  366. if (level == 1) {
  367. lua_settop(L,0);
  368. lua_pushinteger(L, 0);
  369. return 1;
  370. }
  371. if (!lua_isfunction(L, 2)) {
  372. int scope = luaL_checkint(L, 2);
  373. if (scope > 0) {
  374. /* if the function parameter is a +ve integer then climb to find function */
  375. lua_Debug ar;
  376. lua_pop(L, 1); /* pop level as getinfo will replace it by the function */
  377. if (lua_getstack(L, scope, &ar)) {
  378. lua_getinfo(L, "f", &ar);
  379. }
  380. }
  381. }
  382. if(!lua_isfunction(L, 2) || lua_iscfunction(L, -1)) luaL_argerror(L, 2, "must be a Lua Function");
  383. // lua_lock(L);
  384. Proto *f = clvalue(L->base + 1)->l.p;
  385. // lua_unlock(L);
  386. lua_settop(L,0);
  387. lua_pushinteger(L, luaG_stripdebug(L, f, level, 1));
  388. return 1;
  389. }
  390. #endif
  391. // Lua: node.egc.setmode( mode, [param])
  392. // where the mode is one of the node.egc constants NOT_ACTIVE , ON_ALLOC_FAILURE,
  393. // ON_MEM_LIMIT, ALWAYS. In the case of ON_MEM_LIMIT an integer parameter is reqired
  394. // See legc.h and lecg.c.
  395. static int node_egc_setmode(lua_State* L) {
  396. unsigned mode = luaL_checkinteger(L, 1);
  397. unsigned limit = luaL_optinteger (L, 2, 0);
  398. luaL_argcheck(L, mode <= (EGC_ON_ALLOC_FAILURE | EGC_ON_MEM_LIMIT | EGC_ALWAYS), 1, "invalid mode");
  399. luaL_argcheck(L, !(mode & EGC_ON_MEM_LIMIT) || limit>0, 1, "limit must be non-zero");
  400. legc_set_mode( L, mode, limit );
  401. return 0;
  402. }
  403. //
  404. // Lua: osprint(true/false)
  405. // Allows you to turn on the native Espressif SDK printing
  406. static int node_osprint( lua_State* L )
  407. {
  408. if (lua_toboolean(L, 1)) {
  409. system_set_os_print(1);
  410. } else {
  411. system_set_os_print(0);
  412. }
  413. return 0;
  414. }
  415. // Module function map
  416. static const LUA_REG_TYPE node_egc_map[] = {
  417. { LSTRKEY( "setmode" ), LFUNCVAL( node_egc_setmode ) },
  418. { LSTRKEY( "NOT_ACTIVE" ), LNUMVAL( EGC_NOT_ACTIVE ) },
  419. { LSTRKEY( "ON_ALLOC_FAILURE" ), LNUMVAL( EGC_ON_ALLOC_FAILURE ) },
  420. { LSTRKEY( "ON_MEM_LIMIT" ), LNUMVAL( EGC_ON_MEM_LIMIT ) },
  421. { LSTRKEY( "ALWAYS" ), LNUMVAL( EGC_ALWAYS ) },
  422. { LNILKEY, LNILVAL }
  423. };
  424. static const LUA_REG_TYPE node_task_map[] = {
  425. { LSTRKEY( "post" ), LFUNCVAL( node_task_post ) },
  426. { LSTRKEY( "LOW_PRIORITY" ), LNUMVAL( TASK_PRIORITY_LOW ) },
  427. { LSTRKEY( "MEDIUM_PRIORITY" ), LNUMVAL( TASK_PRIORITY_MEDIUM ) },
  428. { LSTRKEY( "HIGH_PRIORITY" ), LNUMVAL( TASK_PRIORITY_HIGH ) },
  429. { LNILKEY, LNILVAL }
  430. };
  431. static const LUA_REG_TYPE node_map[] =
  432. {
  433. { LSTRKEY( "restart" ), LFUNCVAL( node_restart ) },
  434. { LSTRKEY( "dsleep" ), LFUNCVAL( node_deepsleep ) },
  435. { LSTRKEY( "info" ), LFUNCVAL( node_info ) },
  436. { LSTRKEY( "chipid" ), LFUNCVAL( node_chipid ) },
  437. { LSTRKEY( "flashid" ), LFUNCVAL( node_flashid ) },
  438. { LSTRKEY( "flashsize" ), LFUNCVAL( node_flashsize) },
  439. { LSTRKEY( "heap" ), LFUNCVAL( node_heap ) },
  440. { LSTRKEY( "input" ), LFUNCVAL( node_input ) },
  441. { LSTRKEY( "output" ), LFUNCVAL( node_output ) },
  442. // Moved to adc module, use adc.readvdd33()
  443. // { LSTRKEY( "readvdd33" ), LFUNCVAL( node_readvdd33) },
  444. { LSTRKEY( "compile" ), LFUNCVAL( node_compile) },
  445. { LSTRKEY( "CPU80MHZ" ), LNUMVAL( CPU80MHZ ) },
  446. { LSTRKEY( "CPU160MHZ" ), LNUMVAL( CPU160MHZ ) },
  447. { LSTRKEY( "setcpufreq" ), LFUNCVAL( node_setcpufreq) },
  448. { LSTRKEY( "bootreason" ), LFUNCVAL( node_bootreason) },
  449. { LSTRKEY( "restore" ), LFUNCVAL( node_restore) },
  450. #ifdef LUA_OPTIMIZE_DEBUG
  451. { LSTRKEY( "stripdebug" ), LFUNCVAL( node_stripdebug ) },
  452. #endif
  453. { LSTRKEY( "egc" ), LROVAL( node_egc_map ) },
  454. { LSTRKEY( "task" ), LROVAL( node_task_map ) },
  455. #ifdef DEVELOPMENT_TOOLS
  456. { LSTRKEY( "osprint" ), LFUNCVAL( node_osprint ) },
  457. #endif
  458. // Combined to dsleep(us, option)
  459. // { LSTRKEY( "dsleepsetoption" ), LFUNCVAL( node_deepsleep_setoption) },
  460. { LNILKEY, LNILVAL }
  461. };
  462. NODEMCU_MODULE(NODE, "node", node_map, NULL);