tmr.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*guys, srsly, turn on warnings in the makefile*/
  2. #if defined(__GNUC__)
  3. #pragma GCC diagnostic warning "-Wall"
  4. #pragma GCC diagnostic warning "-Wextra"
  5. #pragma GCC diagnostic ignored "-Wunused-parameter"
  6. #endif
  7. /* See docs/modules/tmr.md for documentaiton o current API */
  8. #include "module.h"
  9. #include "lauxlib.h"
  10. #include "platform.h"
  11. #include <stdint.h>
  12. #include "user_interface.h"
  13. #include "pm/swtimer.h"
  14. #define TIMER_MODE_SINGLE 0
  15. #define TIMER_MODE_AUTO 1
  16. #define TIMER_MODE_SEMI 2
  17. #define TIMER_MODE_OFF 3
  18. #define TIMER_IDLE_FLAG (1<<7)
  19. #define STRINGIFY_VAL(x) #x
  20. #define STRINGIFY(x) STRINGIFY_VAL(x)
  21. // assuming system_timer_reinit() has *not* been called
  22. #define MAX_TIMEOUT_DEF 0x68D7A3 // SDK specfied limit
  23. static const uint32 MAX_TIMEOUT=MAX_TIMEOUT_DEF;
  24. static const char* MAX_TIMEOUT_ERR_STR = "Range: 1-"STRINGIFY(MAX_TIMEOUT_DEF);
  25. typedef struct{
  26. os_timer_t os;
  27. sint32_t lua_ref; /* Reference to registered callback function */
  28. sint32_t self_ref; /* Reference to UD registered slot */
  29. uint32_t interval;
  30. uint8_t mode;
  31. } tmr_t;
  32. // The previous implementation extended the rtc counter to 64 bits, and then
  33. // applied rtc2sec with the current calibration value to that 64 bit value.
  34. // This means that *ALL* clock ticks since bootup are counted with the
  35. // *current* clock period. In extreme cases (long uptime, sudden temperature
  36. // change), this could result in tmr.time() going backwards....
  37. //
  38. // This implementation instead applies rtc2usec to short time intervals only
  39. // (the longest being around 1 second), and then accumulates the resulting
  40. // microseconds in a 64 bit counter. That's guaranteed to be monotonic, and
  41. // should be a lot closer to representing an actual uptime.
  42. static uint32_t rtc_time_cali=0;
  43. static uint32_t last_rtc_time=0;
  44. static uint64_t last_rtc_time_us=0;
  45. static sint32_t soft_watchdog = -1;
  46. static os_timer_t rtc_timer;
  47. static void alarm_timer_common(void* arg){
  48. tmr_t *tmr = (tmr_t *) arg;
  49. if(tmr->lua_ref > 0) {
  50. lua_State* L = lua_getstate();
  51. lua_rawgeti(L, LUA_REGISTRYINDEX, tmr->lua_ref);
  52. lua_rawgeti(L, LUA_REGISTRYINDEX, tmr->self_ref);
  53. if (tmr->mode != TIMER_MODE_AUTO) {
  54. if(tmr->mode == TIMER_MODE_SINGLE) {
  55. luaL_unref2(L, LUA_REGISTRYINDEX, tmr->lua_ref);
  56. luaL_unref2(L, LUA_REGISTRYINDEX, tmr->self_ref);
  57. tmr->mode = TIMER_MODE_OFF;
  58. } else if (tmr->mode == TIMER_MODE_SEMI) {
  59. tmr->mode |= TIMER_IDLE_FLAG;
  60. luaL_unref2(L, LUA_REGISTRYINDEX, tmr->self_ref);
  61. }
  62. }
  63. luaL_pcallx(L, 1, 0);
  64. }
  65. }
  66. // Lua: tmr.delay( us )
  67. static int tmr_delay( lua_State* L ){
  68. sint32_t us = luaL_checkinteger(L, 1);
  69. luaL_argcheck(L, us>0, 1, "wrong arg range");
  70. while(us > 0){
  71. os_delay_us(us >= 1000000 ? 1000000 : us);
  72. system_soft_wdt_feed ();
  73. us -= 1000000;
  74. }
  75. return 0;
  76. }
  77. // Lua: tmr.now() , return system timer in us
  78. static int tmr_now(lua_State* L){
  79. lua_pushinteger(L, (uint32_t) (0x7FFFFFFF & system_get_time()));
  80. return 1;
  81. }
  82. // Lua: tmr.ccount() , returns CCOUNT register
  83. static int tmr_ccount(lua_State* L){
  84. lua_pushinteger(L, CCOUNT_REG);
  85. return 1;
  86. }
  87. /*
  88. ** Health warning: this is also called DIRECTLY from alarm() which assumes that the Lua
  89. ** stack is preserved for the following start(), so the stack MUST be balanced here.
  90. */
  91. // Lua: t:register( interval, mode, function )
  92. static int tmr_register(lua_State* L) {
  93. tmr_t *tmr = (tmr_t *) luaL_checkudata(L, 1, "tmr.timer");
  94. uint32_t interval = luaL_checkinteger(L, 2);
  95. uint8_t mode = luaL_checkinteger(L, 3);
  96. luaL_argcheck(L, (interval > 0 && interval <= MAX_TIMEOUT), 2, MAX_TIMEOUT_ERR_STR);
  97. luaL_argcheck(L, (mode == TIMER_MODE_SINGLE || mode == TIMER_MODE_SEMI || mode == TIMER_MODE_AUTO), 3, "Invalid mode");
  98. luaL_argcheck(L, lua_isfunction(L, 4), 4, "Must be function");
  99. //get the lua function reference
  100. lua_pushvalue(L, 4);
  101. if(!(tmr->mode & TIMER_IDLE_FLAG) && tmr->mode != TIMER_MODE_OFF)
  102. os_timer_disarm(&tmr->os);
  103. luaL_reref(L, LUA_REGISTRYINDEX, &tmr->lua_ref);
  104. tmr->mode = mode|TIMER_IDLE_FLAG;
  105. tmr->interval = interval;
  106. os_timer_setfn(&tmr->os, alarm_timer_common, tmr);
  107. return 0;
  108. }
  109. // Lua: t:start()
  110. static int tmr_start(lua_State* L){
  111. tmr_t *tmr = (tmr_t *) luaL_checkudata(L, 1, "tmr.timer");
  112. int idle = tmr->mode & TIMER_IDLE_FLAG;
  113. lua_settop(L, 1); /* ignore any args after the userdata */
  114. if (tmr->self_ref == LUA_NOREF)
  115. tmr->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  116. if(idle) {
  117. tmr->mode &= ~TIMER_IDLE_FLAG;
  118. os_timer_arm(&tmr->os, tmr->interval, tmr->mode==TIMER_MODE_AUTO);
  119. }
  120. lua_pushboolean(L, !idle); /* false if the timer is not idle */
  121. return 1;
  122. }
  123. // Lua: t:alarm( interval, repeat, function )
  124. static int tmr_alarm(lua_State* L){
  125. tmr_register(L);
  126. return tmr_start(L);
  127. }
  128. // Lua: t:stop()
  129. static int tmr_stop(lua_State* L){
  130. tmr_t *tmr = (tmr_t *) luaL_checkudata(L, 1, "tmr.timer");
  131. int idle = tmr->mode == TIMER_MODE_OFF || (tmr->mode & TIMER_IDLE_FLAG);
  132. luaL_unref2(L, LUA_REGISTRYINDEX, tmr->self_ref);
  133. if(!idle)
  134. os_timer_disarm(&tmr->os);
  135. tmr->mode |= TIMER_IDLE_FLAG;
  136. lua_pushboolean(L, !idle); /* return false if the timer is idle (or not registered) */
  137. return 1;
  138. }
  139. #ifdef TIMER_SUSPEND_ENABLE
  140. #define TMR_SUSPEND_REMOVED_MSG "This feature has been removed, we apologize for any inconvenience this may have caused."
  141. #define tmr_suspend tmr_suspend_removed
  142. #define tmr_resume tmr_suspend_removed
  143. #define tmr_suspend_all tmr_suspend_removed
  144. #define tmr_resume_all tmr_suspend_removed
  145. static int tmr_suspend_removed(lua_State* L){
  146. return luaL_error(L, TMR_SUSPEND_REMOVED_MSG);
  147. }
  148. #endif
  149. // Lua: t:unregister()
  150. static int tmr_unregister(lua_State* L){
  151. tmr_t *tmr = (tmr_t *) luaL_checkudata(L, 1, "tmr.timer");
  152. luaL_unref2(L, LUA_REGISTRYINDEX, tmr->self_ref);
  153. luaL_unref2(L, LUA_REGISTRYINDEX, tmr->lua_ref);
  154. if(!(tmr->mode & TIMER_IDLE_FLAG) && tmr->mode != TIMER_MODE_OFF)
  155. os_timer_disarm(&tmr->os);
  156. tmr->mode = TIMER_MODE_OFF;
  157. return 0;
  158. }
  159. // Lua: t:interval( interval )
  160. static int tmr_interval(lua_State* L){
  161. tmr_t *tmr = (tmr_t *) luaL_checkudata(L, 1, "tmr.timer");
  162. uint32_t interval = luaL_checkinteger(L, 2);
  163. luaL_argcheck(L, (interval > 0 && interval <= MAX_TIMEOUT), 2, MAX_TIMEOUT_ERR_STR);
  164. if(tmr->mode != TIMER_MODE_OFF){
  165. tmr->interval = interval;
  166. if(!(tmr->mode&TIMER_IDLE_FLAG)){
  167. os_timer_disarm(&tmr->os);
  168. os_timer_arm(&tmr->os, tmr->interval, tmr->mode==TIMER_MODE_AUTO);
  169. }
  170. }
  171. return 0;
  172. }
  173. // Lua: t:state()
  174. static int tmr_state(lua_State* L){
  175. tmr_t *tmr = (tmr_t *) luaL_checkudata(L, 1, "tmr.timer");
  176. if(tmr->mode == TIMER_MODE_OFF){
  177. lua_pushnil(L);
  178. return 1;
  179. }
  180. lua_pushboolean(L, (tmr->mode & TIMER_IDLE_FLAG) == 0);
  181. lua_pushinteger(L, tmr->mode & (~TIMER_IDLE_FLAG));
  182. return 2;
  183. }
  184. // Lua: tmr.wdclr()
  185. static int tmr_wdclr( lua_State* L ){
  186. system_soft_wdt_feed ();
  187. return 0;
  188. }
  189. // The on ESP8266 system_rtc_clock_cali_proc() returns a fixed point value
  190. // (12 bit fraction part), giving how many rtc clock ticks represent 1us.
  191. // The high 64 bits of the uint64_t multiplication are not needed)
  192. static uint32_t rtc2usec(uint64_t rtc){
  193. return (rtc*rtc_time_cali)>>12;
  194. }
  195. // This returns the number of microseconds uptime. Note that it relies on
  196. // the rtc clock, which is notoriously temperature dependent
  197. inline static uint64_t rtc_timer_update(bool do_calibration){
  198. if (do_calibration || rtc_time_cali==0)
  199. rtc_time_cali=system_rtc_clock_cali_proc();
  200. uint32_t current = system_get_rtc_time();
  201. uint32_t since_last=current-last_rtc_time; // This will transparently deal with wraparound
  202. uint32_t us_since_last=rtc2usec(since_last);
  203. uint64_t now=last_rtc_time_us+us_since_last;
  204. // Only update if at least 100ms has passed since we last updated.
  205. // This prevents the rounding errors in rtc2usec from accumulating
  206. if (us_since_last>=100000){
  207. last_rtc_time=current;
  208. last_rtc_time_us=now;
  209. }
  210. return now;
  211. }
  212. void rtc_callback(void *arg){
  213. rtc_timer_update(true);
  214. if(soft_watchdog > 0){
  215. soft_watchdog--;
  216. if(soft_watchdog == 0)
  217. system_restart();
  218. }
  219. }
  220. // Lua: tmr.time() , return rtc time in second
  221. static int tmr_time( lua_State* L ){
  222. uint64_t us=rtc_timer_update(false);
  223. lua_pushinteger(L, us/1000000);
  224. return 1;
  225. }
  226. // Lua: tmr.softwd( value )
  227. static int tmr_softwd( lua_State* L ){
  228. int t = luaL_checkinteger(L, 1);
  229. luaL_argcheck(L, t>0 , 2, "invalid time");
  230. soft_watchdog = t;
  231. return 0;
  232. }
  233. // Lua: tmr.create()
  234. static int tmr_create( lua_State *L ) {
  235. tmr_t *ud = (tmr_t *)lua_newuserdata(L, sizeof(*ud));
  236. luaL_getmetatable(L, "tmr.timer");
  237. lua_setmetatable(L, -2);
  238. *ud = (tmr_t) {{0}, LUA_NOREF, LUA_NOREF, 0, TIMER_MODE_OFF};
  239. return 1;
  240. }
  241. // Module function map
  242. LROT_BEGIN(tmr_dyn, NULL, LROT_MASK_GC_INDEX)
  243. LROT_FUNCENTRY( __gc, tmr_unregister )
  244. LROT_TABENTRY( __index, tmr_dyn )
  245. LROT_FUNCENTRY( register, tmr_register )
  246. LROT_FUNCENTRY( alarm, tmr_alarm )
  247. LROT_FUNCENTRY( start, tmr_start )
  248. LROT_FUNCENTRY( stop, tmr_stop )
  249. LROT_FUNCENTRY( unregister, tmr_unregister )
  250. LROT_FUNCENTRY( state, tmr_state )
  251. LROT_FUNCENTRY( interval, tmr_interval )
  252. #ifdef TIMER_SUSPEND_ENABLE
  253. LROT_FUNCENTRY( suspend, tmr_suspend )
  254. LROT_FUNCENTRY( resume, tmr_resume )
  255. #endif
  256. LROT_END(tmr_dyn, NULL, LROT_MASK_GC_INDEX)
  257. LROT_BEGIN(tmr, NULL, 0)
  258. LROT_FUNCENTRY( delay, tmr_delay )
  259. LROT_FUNCENTRY( now, tmr_now )
  260. LROT_FUNCENTRY( wdclr, tmr_wdclr )
  261. LROT_FUNCENTRY( softwd, tmr_softwd )
  262. LROT_FUNCENTRY( time, tmr_time )
  263. LROT_FUNCENTRY( ccount, tmr_ccount )
  264. #ifdef TIMER_SUSPEND_ENABLE
  265. LROT_FUNCENTRY( suspend_all, tmr_suspend_all )
  266. LROT_FUNCENTRY( resume_all, tmr_resume_all )
  267. #endif
  268. LROT_FUNCENTRY( create, tmr_create )
  269. LROT_NUMENTRY( ALARM_SINGLE, TIMER_MODE_SINGLE )
  270. LROT_NUMENTRY( ALARM_SEMI, TIMER_MODE_SEMI )
  271. LROT_NUMENTRY( ALARM_AUTO, TIMER_MODE_AUTO )
  272. LROT_END(tmr, NULL, 0)
  273. #include "pm/swtimer.h"
  274. int luaopen_tmr( lua_State *L ){
  275. luaL_rometatable(L, "tmr.timer", LROT_TABLEREF(tmr_dyn));
  276. last_rtc_time=system_get_rtc_time(); // Right now is time 0
  277. last_rtc_time_us=0;
  278. os_timer_disarm(&rtc_timer);
  279. os_timer_setfn(&rtc_timer, rtc_callback, NULL);
  280. os_timer_arm(&rtc_timer, 1000, 1);
  281. // The function rtc_callback calls the a function that calibrates the SoftRTC
  282. // for drift in the esp8266's clock. My guess: after the duration of light_sleep
  283. // there is bound to be some drift in the clock, so a calibration is due.
  284. SWTIMER_REG_CB(rtc_callback, SWTIMER_RESUME);
  285. // The function alarm_timer_common handles timers created by the developer via
  286. // tmr.create(). No reason not to resume the timers, so resume em'.
  287. SWTIMER_REG_CB(alarm_timer_common, SWTIMER_RESUME);
  288. return 0;
  289. }
  290. NODEMCU_MODULE(TMR, "tmr", tmr, luaopen_tmr);