node.c 32 KB

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