sys.lua 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. --- 模块功能:Luat协程调度框架
  2. --module(..., package.seeall)
  3. local sys = {}
  4. local table = _G.table
  5. local unpack = table.unpack
  6. local rtos = _G.rtos
  7. local coroutine = _G.coroutine
  8. local log = _G.log
  9. -- lib脚本版本号,只要lib中的任何一个脚本做了修改,都需要更新此版本号
  10. SCRIPT_LIB_VER = "1.0.0"
  11. -- TaskID最大值
  12. local TASK_TIMER_ID_MAX = 0x1FFFFF
  13. -- msgId 最大值(请勿修改否则会发生msgId碰撞的危险)
  14. local MSG_TIMER_ID_MAX = 0x7FFFFF
  15. -- 任务定时器id
  16. local taskTimerId = 0
  17. -- 消息定时器id
  18. local msgId = TASK_TIMER_ID_MAX
  19. -- 定时器id表
  20. local timerPool = {}
  21. local taskTimerPool = {}
  22. --消息定时器参数表
  23. local para = {}
  24. --定时器是否循环表
  25. --local loop = {}
  26. --lua脚本运行出错时,是否回退为本地烧写的版本
  27. --local sRollBack = true
  28. _G.COROUTINE_ERROR_ROLL_BACK = true
  29. _G.COROUTINE_ERROR_RESTART = true
  30. -- 对coroutine.resume加一个修饰器用于捕获协程错误
  31. --local rawcoresume = coroutine.resume
  32. local function wrapper(co,...)
  33. local arg = {...}
  34. if not arg[1] then
  35. local traceBack = debug.traceback(co)
  36. traceBack = (traceBack and traceBack~="") and (arg[2].."\r\n"..traceBack) or arg[2]
  37. log.error("coroutine.resume",traceBack)
  38. --if errDump and type(errDump.appendErr)=="function" then
  39. -- errDump.appendErr(traceBack)
  40. --end
  41. if _G.COROUTINE_ERROR_ROLL_BACK then
  42. sys.timerStart(assert,500,false,traceBack)
  43. elseif _G.COROUTINE_ERROR_RESTART then
  44. rtos.reboot()
  45. end
  46. end
  47. return ...
  48. end
  49. sys.coresume = function(...)
  50. local arg = {...}
  51. return wrapper(arg[1], coroutine.resume(...))
  52. end
  53. --- Task任务延时函数,只能用于任务函数中
  54. -- @number ms 整数,最大等待126322567毫秒
  55. -- @return 定时结束返回nil,被其他线程唤起返回调用线程传入的参数
  56. -- @usage sys.wait(30)
  57. function sys.wait(ms)
  58. -- 参数检测,参数不能为负值
  59. --assert(ms > 0, "The wait time cannot be negative!")
  60. -- 选一个未使用的定时器ID给该任务线程
  61. while true do
  62. if taskTimerId >= TASK_TIMER_ID_MAX - 1 then
  63. taskTimerId = 0
  64. else
  65. taskTimerId = taskTimerId + 1
  66. end
  67. if taskTimerPool[taskTimerId] == nil then
  68. break
  69. end
  70. end
  71. local timerid = taskTimerId
  72. taskTimerPool[coroutine.running()] = timerid
  73. timerPool[timerid] = coroutine.running()
  74. -- 调用core的rtos定时器
  75. if 1 ~= rtos.timer_start(timerid, ms) then log.debug("rtos.timer_start error") return end
  76. -- 挂起调用的任务线程
  77. local message = {coroutine.yield()}
  78. if #message ~= 0 then
  79. rtos.timer_stop(timerid)
  80. taskTimerPool[coroutine.running()] = nil
  81. timerPool[timerid] = nil
  82. return unpack(message)
  83. end
  84. end
  85. --- Task任务的条件等待函数(包括事件消息和定时器消息等条件),只能用于任务函数中。
  86. -- @param id 消息ID
  87. -- @number ms 等待超时时间,单位ms,最大等待126322567毫秒
  88. -- @return result 接收到消息返回true,超时返回false
  89. -- @return data 接收到消息返回消息参数
  90. -- @usage result, data = sys.waitUntil("SIM_IND", 120000)
  91. function sys.waitUntil(id, ms)
  92. sys.subscribe(id, coroutine.running())
  93. local message = ms and {sys.wait(ms)} or {coroutine.yield()}
  94. sys.unsubscribe(id, coroutine.running())
  95. return message[1] ~= nil, unpack(message, 2, #message)
  96. end
  97. --- Task任务的条件等待函数扩展(包括事件消息和定时器消息等条件),只能用于任务函数中。
  98. -- @param id 消息ID
  99. -- @number ms 等待超时时间,单位ms,最大等待126322567毫秒
  100. -- @return message 接收到消息返回message,超时返回false
  101. -- @return data 接收到消息返回消息参数
  102. -- @usage result, data = sys.waitUntilExt("SIM_IND", 120000)
  103. function sys.waitUntilExt(id, ms)
  104. sys.subscribe(id, coroutine.running())
  105. local message = ms and {sys.wait(ms)} or {coroutine.yield()}
  106. sys.unsubscribe(id, coroutine.running())
  107. if message[1] ~= nil then return unpack(message) end
  108. return false
  109. end
  110. --- 创建一个任务线程,在模块最末行调用该函数并注册模块中的任务函数,main.lua导入该模块即可
  111. -- @param fun 任务函数名,用于resume唤醒时调用
  112. -- @param ... 任务函数fun的可变参数
  113. -- @return co 返回该任务的线程号
  114. -- @usage sys.taskInit(task1,'a','b')
  115. function sys.taskInit(fun, ...)
  116. local co = coroutine.create(fun)
  117. sys.coresume(co, ...)
  118. return co
  119. end
  120. ------------------------------------------ rtos消息回调处理部分 ------------------------------------------
  121. --[[
  122. 函数名:cmpTable
  123. 功能 :比较两个table的内容是否相同,注意:table中不能再包含table
  124. 参数 :
  125. t1:第一个table
  126. t2:第二个table
  127. 返回值:相同返回true,否则false
  128. ]]
  129. local function cmpTable(t1, t2)
  130. if not t2 then return #t1 == 0 end
  131. if #t1 == #t2 then
  132. for i = 1, #t1 do
  133. if unpack(t1, i, i) ~= unpack(t2, i, i) then
  134. return false
  135. end
  136. end
  137. return true
  138. end
  139. return false
  140. end
  141. --- 关闭定时器
  142. -- @param val 值为number时,识别为定时器ID,值为回调函数时,需要传参数
  143. -- @param ... val值为函数时,函数的可变参数
  144. -- @return 无
  145. -- @usage timerStop(1)
  146. function sys.timerStop(val, ...)
  147. -- val 为定时器ID
  148. if type(val) == 'number' then
  149. timerPool[val], para[val] = nil
  150. rtos.timer_stop(val)
  151. else
  152. for k, v in pairs(timerPool) do
  153. -- 回调函数相同
  154. if type(v) == 'table' and v.cb == val or v == val then
  155. -- 可变参数相同
  156. if cmpTable({...}, para[k]) then
  157. rtos.timer_stop(k)
  158. timerPool[k], para[k] = nil
  159. break
  160. end
  161. end
  162. end
  163. end
  164. end
  165. --- 关闭同一回调函数的所有定时器
  166. -- @param fnc 定时器回调函数
  167. -- @return 无
  168. -- @usage timerStopAll(cbFnc)
  169. function sys.timerStopAll(fnc)
  170. for k, v in pairs(timerPool) do
  171. if type(v) == "table" and v.cb == fnc or v == fnc then
  172. rtos.timer_stop(k)
  173. timerPool[k], para[k] = nil
  174. end
  175. end
  176. end
  177. function sys.timerAdvStart(fnc, ms, _repeat, ...)
  178. --回调函数和时长检测
  179. --assert(fnc ~= nil, "sys.timerStart(first param) is nil !")
  180. --assert(ms > 0, "sys.timerStart(Second parameter) is <= zero !")
  181. -- 关闭完全相同的定时器
  182. local arg = {...}
  183. if #arg == 0 then
  184. sys.timerStop(fnc)
  185. else
  186. sys.timerStop(fnc, ...)
  187. end
  188. -- 为定时器申请ID,ID值 1-20 留给任务,20-30留给消息专用定时器
  189. while true do
  190. if msgId >= MSG_TIMER_ID_MAX then msgId = TASK_TIMER_ID_MAX end
  191. msgId = msgId + 1
  192. if timerPool[msgId] == nil then
  193. timerPool[msgId] = fnc
  194. break
  195. end
  196. end
  197. --调用底层接口启动定时器
  198. if rtos.timer_start(msgId, ms, _repeat) ~= 1 then return end
  199. --如果存在可变参数,在定时器参数表中保存参数
  200. if #arg ~= 0 then
  201. para[msgId] = arg
  202. end
  203. --返回定时器id
  204. return msgId
  205. end
  206. --- 开启一个定时器
  207. -- @param fnc 定时器回调函数
  208. -- @number ms 整数,最大定时126322567毫秒
  209. -- @param ... 可变参数 fnc的参数
  210. -- @return number 定时器ID,如果失败,返回nil
  211. function sys.timerStart(fnc, ms, ...)
  212. return sys.timerAdvStart(fnc, ms, 0, ...)
  213. end
  214. --- 开启一个循环定时器
  215. -- @param fnc 定时器回调函数
  216. -- @number ms 整数,最大定时126322567毫秒
  217. -- @param ... 可变参数 fnc的参数
  218. -- @return number 定时器ID,如果失败,返回nil
  219. function sys.timerLoopStart(fnc, ms, ...)
  220. return sys.timerAdvStart(fnc, ms, -1, ...)
  221. end
  222. --- 判断某个定时器是否处于开启状态
  223. -- @param val 有两种形式
  224. --一种是开启定时器时返回的定时器id,此形式时不需要再传入可变参数...就能唯一标记一个定时器
  225. --另一种是开启定时器时的回调函数,此形式时必须再传入可变参数...才能唯一标记一个定时器
  226. -- @param ... 可变参数
  227. -- @return number 开启状态返回true,否则nil
  228. function sys.timerIsActive(val, ...)
  229. if type(val) == "number" then
  230. return timerPool[val]
  231. else
  232. for k, v in pairs(timerPool) do
  233. if v == val then
  234. if cmpTable({...}, para[k]) then return true end
  235. end
  236. end
  237. end
  238. end
  239. ------------------------------------------ LUA应用消息订阅/发布接口 ------------------------------------------
  240. -- 订阅者列表
  241. local subscribers = {}
  242. --内部消息队列
  243. local messageQueue = {}
  244. --- 订阅消息
  245. -- @param id 消息id
  246. -- @param callback 消息回调处理
  247. -- @usage subscribe("NET_STATUS_IND", callback)
  248. function sys.subscribe(id, callback)
  249. --if not id or type(id) == "boolean" or (type(callback) ~= "function" and type(callback) ~= "thread") then
  250. -- log.warn("warning: sys.subscribe invalid parameter", id, callback)
  251. -- return
  252. --end
  253. --log.debug("sys", "subscribe", id, callback)
  254. if type(id) == "table" then
  255. -- 支持多topic订阅
  256. for _, v in pairs(id) do sys.subscribe(v, callback) end
  257. return
  258. end
  259. if not subscribers[id] then subscribers[id] = {} end
  260. subscribers[id][callback] = true
  261. end
  262. --- 取消订阅消息
  263. -- @param id 消息id
  264. -- @param callback 消息回调处理
  265. -- @usage unsubscribe("NET_STATUS_IND", callback)
  266. function sys.unsubscribe(id, callback)
  267. --if not id or type(id) == "boolean" or (type(callback) ~= "function" and type(callback) ~= "thread") then
  268. -- log.warn("warning: sys.unsubscribe invalid parameter", id, callback)
  269. -- return
  270. --end
  271. --log.debug("sys", "unsubscribe", id, callback)
  272. if type(id) == "table" then
  273. -- 支持多topic订阅
  274. for _, v in pairs(id) do sys.unsubscribe(v, callback) end
  275. return
  276. end
  277. if subscribers[id] then subscribers[id][callback] = nil end
  278. -- 判断消息是否无其他订阅
  279. for k, _ in pairs(subscribers[id]) do
  280. return
  281. end
  282. subscribers[id] = nil
  283. end
  284. --- 发布内部消息,存储在内部消息队列中
  285. -- @param ... 可变参数,用户自定义
  286. -- @return 无
  287. -- @usage publish("NET_STATUS_IND")
  288. function sys.publish(...)
  289. table.insert(messageQueue, {...})
  290. end
  291. -- 分发消息
  292. local function dispatch()
  293. while true do
  294. if #messageQueue == 0 then
  295. break
  296. end
  297. local message = table.remove(messageQueue, 1)
  298. if subscribers[message[1]] then
  299. for callback, _ in pairs(subscribers[message[1]]) do
  300. if type(callback) == "function" then
  301. callback(unpack(message, 2, #message))
  302. elseif type(callback) == "thread" then
  303. sys.coresume(callback, unpack(message))
  304. end
  305. end
  306. end
  307. end
  308. end
  309. -- rtos消息回调
  310. --local handlers = {}
  311. --setmetatable(handlers, {__index = function() return function() end end, })
  312. --- 注册rtos消息回调处理函数
  313. -- @number id 消息类型id
  314. -- @param handler 消息处理函数
  315. -- @return 无
  316. -- @usage rtos.on(rtos.MSG_KEYPAD, function(param) handle keypad message end)
  317. --function sys.on(id, handler)
  318. -- handlers[id] = handler
  319. --end
  320. ------------------------------------------ Luat 主调度框架 ------------------------------------------
  321. local function safeRun()
  322. -- 分发内部消息
  323. dispatch()
  324. -- 阻塞读取外部消息
  325. local msg, param, exparam = rtos.receive(rtos.INF_TIMEOUT)
  326. --log.info("sys", msg, param, exparam, tableNSize(timerPool), tableNSize(para), tableNSize(taskTimerPool), tableNSize(subscribers))
  327. -- 空消息?
  328. if not msg or msg == 0 then
  329. -- 无任何操作
  330. -- 判断是否为定时器消息,并且消息是否注册
  331. elseif msg == rtos.MSG_TIMER and timerPool[param] then
  332. if param < TASK_TIMER_ID_MAX then
  333. local taskId = timerPool[param]
  334. timerPool[param] = nil
  335. if taskTimerPool[taskId] == param then
  336. taskTimerPool[taskId] = nil
  337. sys.coresume(taskId)
  338. end
  339. else
  340. local cb = timerPool[param]
  341. --如果不是循环定时器,从定时器id表中删除此定时器
  342. if exparam == 0 then timerPool[param] = nil end
  343. if para[param] ~= nil then
  344. cb(unpack(para[param]))
  345. if exparam == 0 then para[param] = nil end
  346. else
  347. cb()
  348. end
  349. --如果是循环定时器,继续启动此定时器
  350. --if loop[param] then rtos.timer_start(param, loop[param]) end
  351. end
  352. --其他消息(音频消息、充电管理消息、按键消息等)
  353. --elseif type(msg) == "number" then
  354. -- handlers[msg](param, exparam)
  355. --else
  356. -- handlers[msg.id](msg)
  357. end
  358. end
  359. --- run()从底层获取core消息并及时处理相关消息,查询定时器并调度各注册成功的任务线程运行和挂起
  360. -- @return 无
  361. -- @usage sys.run()
  362. function sys.run()
  363. --local result, err
  364. while true do
  365. --if sRollBack then
  366. safeRun()
  367. --else
  368. -- result, err = pcall(safeRun)
  369. -- if not result then rtos.restart(err) end
  370. --end
  371. end
  372. end
  373. _G.sys_pub = sys.publish
  374. return sys
  375. ----------------------------