node.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. // Module for interfacing with system
  2. #include "module.h"
  3. #include "lauxlib.h"
  4. #include "lmem.h"
  5. #include "platform.h"
  6. #include <stdint.h>
  7. #include <string.h>
  8. #include "user_interface.h"
  9. #include "flash_api.h"
  10. #include "vfs.h"
  11. #include "user_version.h"
  12. #include "rom.h"
  13. #include "task/task.h"
  14. #define CPU80MHZ 80
  15. #define CPU160MHZ 160
  16. #define DELAY2SEC 2000
  17. static void restart_callback(void *arg) {
  18. UNUSED(arg);
  19. system_restart();
  20. }
  21. static int default_onerror(lua_State *L) {
  22. static os_timer_t restart_timer = {0};
  23. /* Use Lua print to print the ToS */
  24. lua_settop(L, 1);
  25. lua_getglobal(L, "print");
  26. lua_insert(L, 1);
  27. lua_pcall(L, 1, 0, 0);
  28. /* One first time through set automatic restart after 2s delay */
  29. if (!restart_timer.timer_func) {
  30. os_timer_setfn(&restart_timer, restart_callback, NULL);
  31. os_timer_arm(&restart_timer, DELAY2SEC, 0);
  32. }
  33. return 0;
  34. }
  35. // Lua: setonerror([function])
  36. static int node_setonerror( lua_State* L ) {
  37. lua_settop(L, 1);
  38. if (!lua_isfunction(L, 1)) {
  39. lua_pop(L, 1);
  40. lua_pushcfunction(L, default_onerror);
  41. }
  42. lua_setfield(L, LUA_REGISTRYINDEX, "onerror");
  43. return 0;
  44. }
  45. // Lua: startupcommand(string)
  46. static int node_startupcommand( lua_State* L ) {
  47. size_t l, lrcr;
  48. const char *cmd = luaL_checklstring(L, 1, &l);
  49. lrcr = platform_rcr_write(PLATFORM_RCR_INITSTR, cmd, l+1);
  50. lua_pushboolean(L, lrcr == ~0 ? 0 : 1);
  51. return 1;
  52. }
  53. // Lua: restart()
  54. static int node_restart( lua_State* L )
  55. {
  56. system_restart();
  57. return 0;
  58. }
  59. static int dsleepMax( lua_State *L ) {
  60. lua_pushnumber(L, (uint64_t)system_rtc_clock_cali_proc()*(0x80000000-1)/(0x1000));
  61. return 1;
  62. }
  63. // Lua: dsleep( us, option )
  64. static int node_deepsleep( lua_State* L )
  65. {
  66. uint64 us;
  67. uint8 option;
  68. //us = luaL_checkinteger( L, 1 );
  69. // Set deleep option, skip if nil
  70. if ( lua_isnumber(L, 2) )
  71. {
  72. option = lua_tointeger(L, 2);
  73. if ( option < 0 || option > 4)
  74. return luaL_error( L, "wrong arg range" );
  75. else
  76. system_deep_sleep_set_option( option );
  77. }
  78. bool instant = false;
  79. if (lua_isnumber(L, 3))
  80. instant = lua_tointeger(L, 3);
  81. // Set deleep time, skip if nil
  82. if ( lua_isnumber(L, 1) )
  83. {
  84. us = luaL_checknumber(L, 1);
  85. // if ( us <= 0 )
  86. if ( us < 0 )
  87. return luaL_error( L, "wrong arg range" );
  88. else
  89. {
  90. if (instant)
  91. system_deep_sleep_instant(us);
  92. else
  93. system_deep_sleep( us );
  94. }
  95. }
  96. return 0;
  97. }
  98. #ifdef PMSLEEP_ENABLE
  99. #include "pm/pmSleep.h"
  100. int node_sleep_resume_cb_ref= LUA_NOREF;
  101. void node_sleep_resume_cb(void)
  102. {
  103. PMSLEEP_DBG("START");
  104. pmSleep_execute_lua_cb(&node_sleep_resume_cb_ref);
  105. PMSLEEP_DBG("END");
  106. }
  107. // Lua: node.sleep(table)
  108. static int node_sleep( lua_State* L )
  109. {
  110. #ifdef TIMER_SUSPEND_ENABLE
  111. pmSleep_INIT_CFG(cfg);
  112. cfg.sleep_mode=LIGHT_SLEEP_T;
  113. if(lua_istable(L, 1)){
  114. pmSleep_parse_table_lua(L, 1, &cfg, NULL, &node_sleep_resume_cb_ref);
  115. }
  116. else{
  117. return luaL_argerror(L, 1, "must be table");
  118. }
  119. cfg.resume_cb_ptr = &node_sleep_resume_cb;
  120. pmSleep_suspend(&cfg);
  121. #else
  122. dbg_printf("\n The option \"TIMER_SUSPEND_ENABLE\" in \"app/include/user_config.h\" was disabled during FW build!\n");
  123. return luaL_error(L, "node.sleep() is unavailable");
  124. #endif
  125. return 0;
  126. }
  127. #else
  128. static int node_sleep( lua_State* L )
  129. {
  130. dbg_printf("\n The options \"TIMER_SUSPEND_ENABLE\" and \"PMSLEEP_ENABLE\" in \"app/include/user_config.h\" were disabled during FW build!\n");
  131. return luaL_error(L, "node.sleep() is unavailable");
  132. }
  133. #endif //PMSLEEP_ENABLE
  134. static void add_int_field( lua_State* L, lua_Integer i, const char *name){
  135. lua_pushinteger(L, i);
  136. lua_setfield(L, -2, name);
  137. }
  138. static void add_string_field( lua_State* L, const char *s, const char *name) {
  139. lua_pushstring(L, s);
  140. lua_setfield(L, -2, name);
  141. }
  142. static void get_lfs_config ( lua_State* L ){
  143. int config[5];
  144. lua_getlfsconfig(L, config);
  145. lua_createtable(L, 0, 4);
  146. add_int_field(L, config[0], "lfs_mapped");
  147. add_int_field(L, config[1], "lfs_base");
  148. add_int_field(L, config[2], "lfs_size");
  149. add_int_field(L, config[3], "lfs_used");
  150. }
  151. static int node_info( lua_State* L ){
  152. const char* options[] = {"lfs", "hw", "sw_version", "build_config", "legacy", NULL};
  153. int option = luaL_checkoption (L, 1, options[4], options);
  154. switch (option) {
  155. case 0: { // lfs
  156. get_lfs_config(L);
  157. return 1;
  158. }
  159. case 1: { // hw
  160. lua_createtable(L, 0, 5);
  161. add_int_field(L, system_get_chip_id(), "chip_id");
  162. add_int_field(L, spi_flash_get_id(), "flash_id");
  163. add_int_field(L, flash_rom_get_size_byte() / 1024, "flash_size");
  164. add_int_field(L, flash_rom_get_mode(), "flash_mode");
  165. add_int_field(L, flash_rom_get_speed(), "flash_speed");
  166. return 1;
  167. }
  168. case 2: { // sw_version
  169. lua_createtable(L, 0, 7);
  170. add_int_field(L, NODE_VERSION_MAJOR, "node_version_major");
  171. add_int_field(L, NODE_VERSION_MINOR, "node_version_minor");
  172. add_int_field(L, NODE_VERSION_REVISION, "node_version_revision");
  173. add_string_field(L, BUILDINFO_BRANCH, "git_branch");
  174. add_string_field(L, BUILDINFO_COMMIT_ID, "git_commit_id");
  175. add_string_field(L, BUILDINFO_RELEASE, "git_release");
  176. add_string_field(L, BUILDINFO_RELEASE_DTS, "git_commit_dts");
  177. return 1;
  178. }
  179. case 3: { // build_config
  180. lua_createtable(L, 0, 4);
  181. lua_pushboolean(L, BUILDINFO_SSL);
  182. lua_setfield(L, -2, "ssl");
  183. lua_pushnumber(L, BUILDINFO_LFS_SIZE);
  184. lua_setfield(L, -2, "lfs_size");
  185. add_string_field(L, BUILDINFO_MODULES, "modules");
  186. add_string_field(L, BUILDINFO_BUILD_TYPE, "number_type");
  187. return 1;
  188. }
  189. default: { // legacy
  190. platform_print_deprecation_note("node.info() without parameter", "in the next version");
  191. lua_pushinteger(L, NODE_VERSION_MAJOR);
  192. lua_pushinteger(L, NODE_VERSION_MINOR);
  193. lua_pushinteger(L, NODE_VERSION_REVISION);
  194. lua_pushinteger(L, system_get_chip_id()); // chip id
  195. lua_pushinteger(L, spi_flash_get_id()); // flash id
  196. lua_pushinteger(L, flash_rom_get_size_byte() / 1024); // flash size in KB
  197. lua_pushinteger(L, flash_rom_get_mode());
  198. lua_pushinteger(L, flash_rom_get_speed());
  199. return 8;
  200. }
  201. }
  202. }
  203. // Lua: chipid()
  204. static int node_chipid( lua_State* L )
  205. {
  206. uint32_t id = system_get_chip_id();
  207. lua_pushinteger(L, id);
  208. return 1;
  209. }
  210. // deprecated, moved to adc module
  211. // Lua: readvdd33()
  212. // static int node_readvdd33( lua_State* L )
  213. // {
  214. // uint32_t vdd33 = readvdd33();
  215. // lua_pushinteger(L, vdd33);
  216. // return 1;
  217. // }
  218. // Lua: flashid()
  219. static int node_flashid( lua_State* L )
  220. {
  221. uint32_t id = spi_flash_get_id();
  222. lua_pushinteger( L, id );
  223. return 1;
  224. }
  225. // Lua: flashsize()
  226. static int node_flashsize( lua_State* L )
  227. {
  228. uint32_t sz = flash_rom_get_size_byte();
  229. lua_pushinteger( L, sz );
  230. return 1;
  231. }
  232. // Lua: heap()
  233. static int node_heap( lua_State* L )
  234. {
  235. uint32_t sz = system_get_free_heap_size();
  236. lua_pushinteger(L, sz);
  237. return 1;
  238. }
  239. // Lua: input("string")
  240. static int node_input( lua_State* L ) {
  241. luaL_checkstring(L, 1);
  242. lua_getfield(L, LUA_REGISTRYINDEX, "stdin");
  243. lua_rawgeti(L, -1, 1); /* get the pipe_write func from stdin[1] */
  244. lua_insert(L, -2); /* and move above the pipe ref */
  245. lua_pushvalue(L, 1);
  246. lua_call(L, 2, 0); /* stdin:write(line); errors are thrown to caller */
  247. return 0;
  248. }
  249. static int serial_debug = 1;
  250. /*
  251. ** Output redirector. Note that panics in the output callback cannot be processed
  252. ** using luaL_pcallx() as this would create an infinite error loop, so they are
  253. ** reported direct to the UART.
  254. */
  255. void output_redirect(const char *str, size_t l) {
  256. lua_State *L = lua_getstate();
  257. int n = lua_gettop(L);
  258. lua_pushliteral(L, "stdout");
  259. lua_rawget(L, LUA_REGISTRYINDEX); /* fetch reg.stdout */
  260. if (lua_istable(L, -1)) { /* reg.stdout is pipe */
  261. if (serial_debug) {
  262. uart0_sendStrn(str, l);
  263. }
  264. lua_rawgeti(L, -1, 1); /* get the pipe_write func from stdout[1] */
  265. lua_insert(L, -2); /* and move above the pipe ref */
  266. lua_pushlstring(L, str, l);
  267. if (lua_pcall(L, 2, 0, 0) != LUA_OK) { /* Reg.stdout:write(str) */
  268. lua_writestringerror("error calling stdout:write(%s)\n", lua_tostring(L, -1));
  269. system_restart();
  270. }
  271. } else { /* reg.stdout == nil */
  272. uart0_sendStrn(str, l);
  273. }
  274. lua_settop(L, n); /* Make sure all code paths leave stack unchanged */
  275. }
  276. extern int pipe_create(lua_State *L);
  277. // Lua: output(function(c), debug)
  278. static int node_output( lua_State* L )
  279. {
  280. serial_debug = (lua_isnumber(L, 2) && lua_tointeger(L, 2) == 0) ? 0 : 1;
  281. lua_settop(L, 1);
  282. if (lua_isfunction(L, 1)) {
  283. lua_pushcfunction(L, pipe_create);
  284. lua_insert(L, 1);
  285. lua_pushinteger(L, LUA_TASK_MEDIUM);
  286. lua_call(L, 2, 1); /* Any pipe.create() errors thrown back to caller */
  287. } else { // remove the stdout pipe
  288. lua_pop(L,1);
  289. lua_pushnil(L); /* T[1] = nil */
  290. serial_debug = 1;
  291. }
  292. lua_pushliteral(L, "stdout");
  293. lua_insert(L, 1);
  294. lua_rawset(L, LUA_REGISTRYINDEX); /* Reg.stdout = nil or pipe */
  295. return 0;
  296. }
  297. static int writer(lua_State* L, const void* p, size_t size, void* u)
  298. {
  299. UNUSED(L);
  300. int file_fd = *( (int *)u );
  301. if (!file_fd)
  302. return 1;
  303. NODE_DBG("get fd:%d,size:%d\n", file_fd, size);
  304. if (size != 0 && (size != vfs_write(file_fd, (const char *)p, size)) )
  305. return 1;
  306. NODE_DBG("write fd:%d,size:%d\n", file_fd, size);
  307. return 0;
  308. }
  309. #if LUA_VERSION_NUM == 501
  310. #define getproto(o) (clvalue(o)->l.p)
  311. #endif
  312. // Lua: compile(filename) -- compile lua file into lua bytecode, and save to .lc
  313. static int node_compile( lua_State* L )
  314. {
  315. Proto* f;
  316. int file_fd = 0;
  317. size_t len;
  318. const char *fname = luaL_checklstring( L, 1, &len );
  319. const char *basename = vfs_basename( fname );
  320. luaL_argcheck(L, strlen(basename) <= FS_OBJ_NAME_LEN && strlen(fname) == len, 1, "filename invalid");
  321. char *output = luaM_malloc( L, len+1 );
  322. strcpy(output, fname);
  323. // check here that filename end with ".lua".
  324. if (len < 4 || (strcmp( output + len - 4, ".lua") != 0) ) {
  325. luaM_free( L, output );
  326. return luaL_error(L, "not a .lua file");
  327. }
  328. output[strlen(output) - 2] = 'c';
  329. output[strlen(output) - 1] = '\0';
  330. NODE_DBG(output);
  331. NODE_DBG("\n");
  332. if (luaL_loadfile(L, fname) != 0) {
  333. luaM_free( L, output );
  334. return luaL_error(L, lua_tostring(L, -1));
  335. }
  336. int stripping = 1; /* strip debug information? */
  337. file_fd = vfs_open(output, "w+");
  338. if (!file_fd)
  339. {
  340. luaM_free( L, output );
  341. return luaL_error(L, "cannot open/write to file");
  342. }
  343. int result = lua_dump(L, writer, &file_fd, stripping);
  344. if (vfs_flush(file_fd) != VFS_RES_OK) {
  345. // overwrite Lua error, like writer() does in case of a file io error
  346. result = 1;
  347. }
  348. vfs_close(file_fd);
  349. file_fd = 0;
  350. luaM_free( L, output );
  351. if (result == LUA_ERR_CC_INTOVERFLOW) {
  352. return luaL_error(L, "value too big or small for target integer type");
  353. }
  354. if (result == LUA_ERR_CC_NOTINTEGER) {
  355. return luaL_error(L, "target lua_Number is integral but fractional value found");
  356. }
  357. if (result == 1) { // result status generated by writer() or fs_flush() fail
  358. return luaL_error(L, "writing to file failed");
  359. }
  360. return 0;
  361. }
  362. // Lua: node.task.post([priority],task_cb) -- schedule a task for execution next
  363. static int node_task_post( lua_State* L )
  364. {
  365. int n=1;
  366. unsigned priority = TASK_PRIORITY_MEDIUM;
  367. if (lua_type(L, 1) == LUA_TNUMBER) {
  368. priority = (unsigned) luaL_checkint(L, 1);
  369. luaL_argcheck(L, priority <= TASK_PRIORITY_HIGH, 1, "invalid priority");
  370. n++;
  371. }
  372. luaL_checktype(L, n, LUA_TFUNCTION);
  373. lua_settop(L, n);
  374. (void) luaL_posttask(L, priority);
  375. return 0;
  376. }
  377. // Lua: setcpufreq(mhz)
  378. // mhz is either CPU80MHZ od CPU160MHZ
  379. static int node_setcpufreq(lua_State* L)
  380. {
  381. // http://www.esp8266.com/viewtopic.php?f=21&t=1369
  382. uint32_t new_freq = luaL_checkinteger(L, 1);
  383. if (new_freq == CPU160MHZ){
  384. REG_SET_BIT(0x3ff00014, BIT(0));
  385. ets_update_cpu_frequency(CPU160MHZ);
  386. } else {
  387. REG_CLR_BIT(0x3ff00014, BIT(0));
  388. ets_update_cpu_frequency(CPU80MHZ);
  389. }
  390. new_freq = ets_get_cpu_frequency();
  391. lua_pushinteger(L, new_freq);
  392. return 1;
  393. }
  394. // Lua: freq = node.getcpufreq()
  395. static int node_getcpufreq(lua_State* L)
  396. {
  397. lua_pushinteger(L, system_get_cpu_freq());
  398. return 1;
  399. }
  400. // Lua: code, reason [, exccause, epc1, epc2, epc3, excvaddr, depc ] = bootreason()
  401. static int node_bootreason (lua_State *L)
  402. {
  403. const struct rst_info *ri = system_get_rst_info ();
  404. uint32_t arr[8] = {
  405. rtc_get_reset_reason(),
  406. ri->reason,
  407. ri->exccause, ri->epc1, ri->epc2, ri->epc3, ri->excvaddr, ri->depc
  408. };
  409. int i, n = ((ri->reason != REASON_EXCEPTION_RST) ? 2 : 8);
  410. for (i = 0; i < n; ++i)
  411. lua_pushinteger (L, arr[i]);
  412. return n;
  413. }
  414. // Lua: restore()
  415. static int node_restore (lua_State *L)
  416. {
  417. system_restore();
  418. return 0;
  419. }
  420. /* node.stripdebug([level[, function]]). 
  421. * level: 1 don't discard debug
  422. * 2 discard Local and Upvalue debug info
  423. * 3 discard Local, Upvalue and lineno debug info.
  424. * function: Function to be stripped as per setfenv except 0 not permitted.
  425. * If no arguments then the current default setting is returned.
  426. * If function is omitted, this is the default setting for future compiles
  427. * The function returns an estimated integer count of the bytes stripped.
  428. */
  429. static int node_stripdebug (lua_State *L) {
  430. int n = lua_gettop(L);
  431. int strip = 0;
  432. lua_settop(L, 2);
  433. if (!lua_isnil(L, 1)) {
  434. strip = lua_tointeger(L, 1);
  435. luaL_argcheck(L, strip > 0 && strip < 4, 1, "Invalid strip level");
  436. }
  437. if (lua_isnumber(L, 2)) {
  438. /* Use debug interface to replace stack level by corresponding function */
  439. int scope = luaL_checkinteger(L, 2);
  440. if (scope > 0) {
  441. lua_Debug ar;
  442. lua_pop(L, 1);
  443. if (lua_getstack(L, scope, &ar)) {
  444. lua_getinfo(L, "f", &ar); /* put function at [2] (ToS) */
  445. }
  446. }
  447. }
  448. int isfunc = lua_isfunction(L, 2);
  449. luaL_argcheck(L, n < 2 || isfunc, 2, "not a valid function");
  450. /* return result of lua_stripdebug, adding 1 if this is get/set level) */
  451. lua_pushinteger(L, lua_stripdebug(L, strip - 1) + (isfunc ? 0 : 1));
  452. return 1;
  453. }
  454. #if LUA_VERSION_NUM == 501
  455. // Lua: node.egc.setmode( mode, [param])
  456. // where the mode is one of the node.egc constants NOT_ACTIVE , ON_ALLOC_FAILURE,
  457. // ON_MEM_LIMIT, ALWAYS. In the case of ON_MEM_LIMIT an integer parameter is reqired
  458. // See legc.h and lecg.c.
  459. static int node_egc_setmode(lua_State* L) {
  460. unsigned mode = luaL_checkinteger(L, 1);
  461. int limit = luaL_optinteger (L, 2, 0);
  462. luaL_argcheck(L, mode <= (EGC_ON_ALLOC_FAILURE | EGC_ON_MEM_LIMIT | EGC_ALWAYS), 1, "invalid mode");
  463. luaL_argcheck(L, !(mode & EGC_ON_MEM_LIMIT) || limit!=0, 1, "limit must be non-zero");
  464. lua_setegcmode( L, mode, limit );
  465. return 0;
  466. }
  467. // totalallocated, estimatedused = node.egc.meminfo()
  468. static int node_egc_meminfo(lua_State *L) {
  469. int totals[2];
  470. lua_getegcinfo(L, totals);
  471. lua_pushinteger(L, totals[0]);
  472. lua_pushinteger(L, totals[1]);
  473. return 2;
  474. }
  475. #endif
  476. //
  477. // Lua: osprint(true/false)
  478. // Allows you to turn on the native Espressif SDK printing
  479. static int node_osprint( lua_State* L )
  480. {
  481. if (lua_toboolean(L, 1)) {
  482. system_set_os_print(1);
  483. } else {
  484. system_set_os_print(0);
  485. }
  486. return 0;
  487. }
  488. int node_random_range(int l, int u) {
  489. // The range is the number of different values to return
  490. unsigned int range = u + 1 - l;
  491. // If this is very large then use simpler code
  492. if (range >= 0x7fffffff) {
  493. unsigned int v;
  494. // This cannot loop more than half the time
  495. while ((v = os_random()) >= range) {
  496. }
  497. // Now v is in the range [0, range)
  498. return v + l;
  499. }
  500. // Easy case, with only one value, we know the result
  501. if (range == 1) {
  502. return l;
  503. }
  504. // Another easy case -- uniform 32-bit
  505. if (range == 0) {
  506. return os_random();
  507. }
  508. // Now we have to figure out what a large multiple of range is
  509. // that just fits into 32 bits.
  510. // The limit will be less than 1 << 32 by some amount (not much)
  511. uint32_t limit = ((0x80000000 / ((range + 1) >> 1)) - 1) * range;
  512. uint32_t v;
  513. while ((v = os_random()) >= limit) {
  514. }
  515. // Now v is uniformly distributed in [0, limit) and limit is a multiple of range
  516. return (v % range) + l;
  517. }
  518. static int node_random (lua_State *L) {
  519. int u;
  520. int l;
  521. switch (lua_gettop(L)) { /* check number of arguments */
  522. case 0: { /* no arguments */
  523. #ifdef LUA_NUMBER_INTEGRAL
  524. lua_pushnumber(L, 0); /* Number between 0 and 1 - always 0 with ints */
  525. #else
  526. lua_pushnumber(L, (lua_Number)os_random() / (lua_Number)(1LL << 32));
  527. #endif
  528. return 1;
  529. }
  530. case 1: { /* only upper limit */
  531. l = 1;
  532. u = luaL_checkint(L, 1);
  533. break;
  534. }
  535. case 2: { /* lower and upper limits */
  536. l = luaL_checkint(L, 1);
  537. u = luaL_checkint(L, 2);
  538. break;
  539. }
  540. default:
  541. return luaL_error(L, "wrong number of arguments");
  542. }
  543. luaL_argcheck(L, l<=u, 2, "interval is empty");
  544. lua_pushnumber(L, node_random_range(l, u)); /* int between `l' and `u' */
  545. return 1;
  546. }
  547. #ifdef DEVELOPMENT_TOOLS
  548. // Lua: rec = node.readrcr(id)
  549. static int node_readrcr (lua_State *L) {
  550. int id = luaL_checkinteger(L, 1);
  551. char *data;
  552. int n = platform_rcr_read(id, (void **)&data);
  553. if (n == ~0) return 0;
  554. lua_pushlstring(L, data, n);
  555. return 1;
  556. }
  557. // Lua: n = node.writercr(id,rec)
  558. static int node_writercr (lua_State *L) {
  559. int id = luaL_checkinteger(L, 1),l;
  560. const char *data = lua_tolstring(L, 2, &l);
  561. int n = platform_rcr_write(id, data, l);
  562. lua_pushinteger(L, n);
  563. return 1;
  564. }
  565. #endif
  566. // Lua: n = node.LFS.reload(lfsimage)
  567. static int node_lfsreload (lua_State *L) {
  568. lua_settop(L, 1);
  569. luaL_lfsreload(L);
  570. return 1;
  571. }
  572. // Lua: n = node.flashindex(module)
  573. // Lua: n = node.LFS.get(module)
  574. static int node_lfsindex (lua_State *L) {
  575. lua_settop(L, 1);
  576. luaL_pushlfsmodule(L);
  577. return 1;
  578. }
  579. // Lua: n = node.LFS.list([option])
  580. // Note that option is ignored in this release
  581. static int node_lfslist (lua_State *L) {
  582. lua_settop(L, 1);
  583. luaL_pushlfsmodules(L);
  584. if (lua_istable(L, -1) && lua_getglobal(L, "table") == LUA_TTABLE) {
  585. lua_getfield(L, -1, "sort");
  586. lua_remove(L, -2); /* remove table table */
  587. lua_pushvalue(L, -2); /* dup array of modules ref to ToS */
  588. lua_call(L, 1, 0);
  589. }
  590. return 1;
  591. }
  592. //== node.LFS Table emulator ==============================================//
  593. static int node_lfs_func (lua_State* L) { /*T[1] = LFS, T[2] = fieldname */
  594. lua_remove(L, 1);
  595. lua_settop(L, 1);
  596. const char *name = lua_tostring(L, 1);
  597. if (!name) {
  598. lua_pushnil(L);
  599. } else if (!strcmp(name, "config")) {
  600. get_lfs_config(L);
  601. } else if (!strcmp(name, "time")) {
  602. luaL_pushlfsdts(L);
  603. } else {
  604. luaL_pushlfsmodule(L);
  605. }
  606. return 1;
  607. }
  608. LROT_BEGIN(node_lfs_meta, NULL, LROT_MASK_INDEX)
  609. LROT_FUNCENTRY( __index, node_lfs_func)
  610. LROT_END(node_lfs_meta, NULL, LROT_MASK_INDEX)
  611. LROT_BEGIN(node_lfs, LROT_TABLEREF(node_lfs_meta), 0)
  612. LROT_FUNCENTRY( list, node_lfslist)
  613. LROT_FUNCENTRY( get, node_lfsindex)
  614. LROT_FUNCENTRY( reload, node_lfsreload )
  615. LROT_END(node_lfs, LROT_TABLEREF(node_lfs_meta), 0)
  616. typedef enum pt_t { lfs_addr=0, lfs_size, spiffs_addr, spiffs_size, max_pt} pt_t;
  617. LROT_BEGIN(pt_map, NULL, 0)
  618. LROT_NUMENTRY( lfs_addr, lfs_addr )
  619. LROT_NUMENTRY( lfs_size, lfs_size )
  620. LROT_NUMENTRY( spiffs_addr, spiffs_addr )
  621. LROT_NUMENTRY( spiffs_size, spiffs_size )
  622. LROT_END(pt_map, NULL, 0)
  623. // Lua: ptinfo = node.getpartitiontable()
  624. static int node_getpartitiontable (lua_State *L) {
  625. uint32_t param[max_pt] = {0};
  626. param[lfs_size] = platform_flash_get_partition(NODEMCU_LFS0_PARTITION, param + lfs_addr);
  627. param[spiffs_size] = platform_flash_get_partition(NODEMCU_SPIFFS0_PARTITION, param + spiffs_addr);
  628. lua_settop(L, 0);
  629. lua_createtable (L, 0, max_pt); /* at index 1 */
  630. lua_pushrotable(L, LROT_TABLEREF(pt_map)); /* at index 2 */
  631. lua_pushnil(L); /* first key at index 3 */
  632. while (lua_next(L, 2) != 0) { /* key at index 3, and v at index 4 */
  633. lua_pushvalue(L, 3); /* dup key to index 5 */
  634. lua_pushinteger(L, param[lua_tointeger(L, 4)]); /* param [v] at index 6 */
  635. lua_rawset(L, 1);
  636. lua_pop(L, 1); /* discard v */
  637. }
  638. lua_pop(L, 1); /* discard pt_map reference */
  639. return 1;
  640. }
  641. static void insert_partition(partition_item_t *p, int n, uint32_t type, uint32_t addr) {
  642. if (n>0)
  643. memmove(p+1, p, n*sizeof(partition_item_t)); /* overlapped so must be move not cpy */
  644. p->type = type;
  645. p->addr = addr;
  646. p->size = 0;
  647. }
  648. static void delete_partition(partition_item_t *p, int n) {
  649. if (n>0)
  650. memmove(p, p+1, n*sizeof(partition_item_t)); /* overlapped so must be move not cpy */
  651. }
  652. #define SKIP (~0)
  653. #define IROM0_PARTITION (SYSTEM_PARTITION_CUSTOMER_BEGIN + NODEMCU_IROM0TEXT_PARTITION)
  654. #define LFS_PARTITION (SYSTEM_PARTITION_CUSTOMER_BEGIN + NODEMCU_LFS0_PARTITION)
  655. #define SPIFFS_PARTITION (SYSTEM_PARTITION_CUSTOMER_BEGIN + NODEMCU_SPIFFS0_PARTITION)
  656. // Lua: node.setpartitiontable(pt_settings)
  657. static int node_setpartitiontable (lua_State *L) {
  658. partition_item_t *rcr_pt = NULL, *pt;
  659. uint32_t flash_size = flash_rom_get_size_byte();
  660. uint32_t i = platform_rcr_read(PLATFORM_RCR_PT, (void **) &rcr_pt);
  661. uint32_t last = 0;
  662. uint32_t n = i / sizeof(partition_item_t);
  663. uint32_t param[max_pt] = {SKIP, SKIP, SKIP, SKIP};
  664. luaL_argcheck(L, lua_istable(L, 1), 1, "must be table");
  665. lua_settop(L, 1);
  666. /* convert input table into 4 option array */
  667. lua_pushrotable(L, LROT_TABLEREF(pt_map)); /* at index 2 */
  668. lua_pushnil(L); /* first key at index 3 */
  669. while (lua_next(L, 1) != 0) {
  670. /* 'key' (at index 3) and 'value' (at index 4) */
  671. luaL_argcheck(L, lua_isstring(L, 3) && lua_isnumber(L, 4), 1, "invalid partition setting");
  672. lua_pushvalue(L, 3); /* dup key to index 5 */
  673. lua_rawget(L, 2); /* lookup in pt_map */
  674. luaL_argcheck(L, !lua_isnil(L, -1), 1, "invalid partition setting");
  675. param[lua_tointeger(L, 5)] = lua_tointeger(L, 4);
  676. /* removes 'value'; keeps 'key' for next iteration */
  677. lua_pop(L, 2); /* discard value and lookup */
  678. }
  679. /*
  680. * Allocate a scratch Partition Table as userdata on the Lua stack, and copy the
  681. * current Flash PT into this for manipulation
  682. */
  683. lua_newuserdata(L, (n+2)*sizeof(partition_item_t));
  684. pt = lua_touserdata (L, -1);
  685. memcpy(pt, rcr_pt, n*sizeof(partition_item_t));
  686. pt[n].type = 0; pt[n+1].type = 0;
  687. for (i = 0; i < n; i ++) {
  688. partition_item_t *p = pt + i;
  689. if (p->type == IROM0_PARTITION && p[1].type != LFS_PARTITION) {
  690. // if the LFS partition is not following IROM0 then slot a blank one in
  691. insert_partition(p + 1, n-i-1, LFS_PARTITION, p->addr + p->size);
  692. n++;
  693. } else if (p->type == LFS_PARTITION) {
  694. if (p[1].type != SPIFFS_PARTITION) {
  695. // if the SPIFFS partition is not following LFS then slot a blank one in
  696. insert_partition(p + 1, n-i-1, SPIFFS_PARTITION, 0);
  697. n++;
  698. }
  699. // update the LFS options if set
  700. if (param[lfs_addr] != SKIP) {
  701. p->addr = param[lfs_addr];
  702. }
  703. if (param[lfs_size] != SKIP) {
  704. p->size = param[lfs_size];
  705. }
  706. } else if (p->type == SPIFFS_PARTITION) {
  707. // update the SPIFFS options if set
  708. if (param[spiffs_addr] != SKIP) {
  709. p->addr = param[spiffs_addr];
  710. p->size = SKIP;
  711. }
  712. if (param[spiffs_size] != SKIP) {
  713. // BOTCH: - at the moment the firmware doesn't boot if the SPIFFS partition
  714. // is deleted so the minimum SPIFFS size is 64Kb
  715. p->size = param[spiffs_size] > 0x10000 ? param[spiffs_size] : 0x10000;
  716. }
  717. if (p->size == SKIP) {
  718. if (p->addr < 0) {
  719. // This allocate all the remaining flash to SPIFFS
  720. p->addr = last;
  721. p->size = flash_size - last;
  722. } else {
  723. p->size = flash_size - p->addr;
  724. }
  725. } else if (/* size is specified && */ p->addr == 0) {
  726. // if the is addr not specified then start SPIFFS at 1Mb
  727. // boundary if the size will fit otherwise make it consecutive
  728. // to the previous partition.
  729. p->addr = (p->size <= flash_size - 0x100000) ? 0x100000 : last;
  730. }
  731. }
  732. if (p->size == 0) {
  733. // Delete 0-sized partitions as the SDK barfs on these
  734. delete_partition(p, n-i-1);
  735. n--; i--;
  736. } else {
  737. // Do consistency tests on the partition
  738. if (p->addr & (INTERNAL_FLASH_SECTOR_SIZE - 1) ||
  739. p->size & (INTERNAL_FLASH_SECTOR_SIZE - 1) ||
  740. p->addr < last ||
  741. p->addr + p->size > flash_size) {
  742. luaL_error(L, "value out of range");
  743. }
  744. }
  745. }
  746. // for (i = 0; i < n; i ++)
  747. // dbg_printf("Partition %d: %04x %06x %06x\n", i, pt[i].type, pt[i].addr, pt[i].size);
  748. platform_rcr_write(PLATFORM_RCR_PT, pt, n*sizeof(partition_item_t));
  749. while(1); // Trigger WDT; the new PT will be loaded on reboot
  750. return 0;
  751. }
  752. // Module function map
  753. #if LUA_VERSION_NUM == 501
  754. LROT_BEGIN(node_egc, NULL, 0)
  755. LROT_FUNCENTRY( meminfo, node_egc_meminfo )
  756. LROT_FUNCENTRY( setmode, node_egc_setmode )
  757. LROT_NUMENTRY( NOT_ACTIVE, EGC_NOT_ACTIVE )
  758. LROT_NUMENTRY( ON_ALLOC_FAILURE, EGC_ON_ALLOC_FAILURE )
  759. LROT_NUMENTRY( ON_MEM_LIMIT, EGC_ON_MEM_LIMIT )
  760. LROT_NUMENTRY( ALWAYS, EGC_ALWAYS )
  761. LROT_END(node_egc, NULL, 0)
  762. #endif
  763. LROT_BEGIN(node_task, NULL, 0)
  764. LROT_FUNCENTRY( post, node_task_post )
  765. LROT_NUMENTRY( LOW_PRIORITY, TASK_PRIORITY_LOW )
  766. LROT_NUMENTRY( MEDIUM_PRIORITY, TASK_PRIORITY_MEDIUM )
  767. LROT_NUMENTRY( HIGH_PRIORITY, TASK_PRIORITY_HIGH )
  768. LROT_END(node_task, NULL, 0)
  769. LROT_BEGIN(node, NULL, 0)
  770. LROT_FUNCENTRY( heap, node_heap )
  771. LROT_FUNCENTRY( info, node_info )
  772. LROT_TABENTRY( task, node_task )
  773. LROT_FUNCENTRY( flashindex, node_lfsindex )
  774. LROT_TABENTRY( LFS, node_lfs )
  775. LROT_FUNCENTRY( setonerror, node_setonerror )
  776. LROT_FUNCENTRY( startupcommand, node_startupcommand )
  777. LROT_FUNCENTRY( restart, node_restart )
  778. LROT_FUNCENTRY( dsleep, node_deepsleep )
  779. LROT_FUNCENTRY( dsleepMax, dsleepMax )
  780. LROT_FUNCENTRY( sleep, node_sleep )
  781. #ifdef PMSLEEP_ENABLE
  782. PMSLEEP_INT_MAP
  783. #endif
  784. #ifdef DEVELOPMENT_TOOLS
  785. LROT_FUNCENTRY( readrcr, node_readrcr )
  786. LROT_FUNCENTRY( writercr, node_writercr )
  787. #endif
  788. LROT_FUNCENTRY( chipid, node_chipid )
  789. LROT_FUNCENTRY( flashid, node_flashid )
  790. LROT_FUNCENTRY( flashsize, node_flashsize )
  791. LROT_FUNCENTRY( input, node_input )
  792. LROT_FUNCENTRY( output, node_output )
  793. // Moved to adc module, use adc.readvdd33()
  794. // LROT_FUNCENTRY( readvdd33, node_readvdd33 )
  795. LROT_FUNCENTRY( compile, node_compile )
  796. LROT_NUMENTRY( CPU80MHZ, CPU80MHZ )
  797. LROT_NUMENTRY( CPU160MHZ, CPU160MHZ )
  798. LROT_FUNCENTRY( setcpufreq, node_setcpufreq )
  799. LROT_FUNCENTRY( getcpufreq, node_getcpufreq )
  800. LROT_FUNCENTRY( bootreason, node_bootreason )
  801. LROT_FUNCENTRY( restore, node_restore )
  802. LROT_FUNCENTRY( random, node_random )
  803. LROT_FUNCENTRY( stripdebug, node_stripdebug )
  804. #if LUA_VERSION_NUM == 501
  805. LROT_TABENTRY( egc, node_egc )
  806. #endif
  807. #ifdef DEVELOPMENT_TOOLS
  808. LROT_FUNCENTRY( osprint, node_osprint )
  809. #endif
  810. LROT_FUNCENTRY( getpartitiontable, node_getpartitiontable )
  811. LROT_FUNCENTRY( setpartitiontable, node_setpartitiontable )
  812. // Combined to dsleep(us, option)
  813. // LROT_FUNCENTRY( dsleepsetoption, node_deepsleep_setoption )
  814. LROT_END(node, NULL, 0)
  815. int luaopen_node( lua_State *L ) {
  816. lua_settop(L, 0);
  817. return node_setonerror(L); /* set default onerror action */
  818. }
  819. NODEMCU_MODULE(NODE, "node", node, luaopen_node);