node.c 26 KB

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