aLiYun.lua 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. --- 模块功能:阿里云物联网套件客户端功能.
  2. -- 目前的产品节点类型仅支持“设备”,设备认证方式支持“一机一密和“一型一密”
  3. -- @module aLiYun
  4. -- @author openLuat
  5. -- @license MIT
  6. -- @copyright openLuat
  7. -- @release 2018.04.16
  8. require"log"
  9. require"http"
  10. require"mqtt"
  11. module(..., package.seeall)
  12. local sProductKey,sProductSecret,sGetDeviceNameFnc,sGetDeviceSecretFnc,sSetDeviceSecretFnc
  13. local sRegion = "cn-shanghai"
  14. --实例ID,根据此ID来判断是否需要一型一密免预注册认证
  15. local sInstanceId
  16. --连接方式
  17. local sConnectMode,sConnectHost,sConnectPort,sGetClientIdFnc,sGetUserNameFnc,sGetPasswordFnc
  18. local sKeepAlive,sCleanSession,sWill
  19. local isSleep = false--休眠,不去重连服务器
  20. local isAuthSleep =false --休眠,不去重连鉴权
  21. local sErrHandleCo,sErrHandleCb,sErrHandleTmout
  22. local outQueue =
  23. {
  24. SUBSCRIBE = {},
  25. PUBLISH = {},
  26. }
  27. local evtCb = {}
  28. local function insert(type,topic,qos,payload,cbFnc,cbPara)
  29. table.insert(outQueue[type],{t=topic,q=qos,p=payload,cb=cbFnc,para=cbPara})
  30. end
  31. local function remove(type)
  32. if #outQueue[type]>0 then return table.remove(outQueue[type],1) end
  33. end
  34. local function procSubscribe(client)
  35. local i
  36. for i=1,#outQueue["SUBSCRIBE"] do
  37. if not client:subscribe(outQueue["SUBSCRIBE"][i].t,outQueue["SUBSCRIBE"][i].q) then
  38. outQueue["SUBSCRIBE"] = {}
  39. return false,"procSubscribe"
  40. end
  41. end
  42. outQueue["SUBSCRIBE"] = {}
  43. return true
  44. end
  45. local function procReceive(client)
  46. local r,data,s
  47. while true do
  48. r,data,s = client:receive(60000,"aliyun_publish_ind")
  49. --接收到数据
  50. if r and data~="timeout" then
  51. log.info("aLiYun.procReceive",data.topic,string.toHex(data.payload))
  52. --OTA消息
  53. if data.topic=="/ota/device/upgrade/"..sProductKey.."/"..sGetDeviceNameFnc() then
  54. if aLiYunOta and aLiYunOta.upgrade then
  55. aLiYunOta.upgrade(data.payload)
  56. end
  57. --其他消息
  58. else
  59. if evtCb["receive"] then evtCb["receive"](data.topic,data.qos,data.payload) end
  60. end
  61. --如果有等待发送的数据,则立即退出本循环
  62. if #outQueue["PUBLISH"]>0 then
  63. return true,"procReceive"
  64. else
  65. if sErrHandleCo then coroutine.resume(sErrHandleCo,"feed") end
  66. end
  67. elseif data == "aliyun_publish_ind" and s:find("disconnect") then--主动断开
  68. client:disconnect()
  69. return false,"procReceive"
  70. elseif data == "aliyun_publish_ind" and s:find("send") then--来数据要发了
  71. log.info("aliyun aliyun_publish_ind")
  72. return true,"procReceive"
  73. else
  74. break
  75. end
  76. end
  77. return data=="timeout" or r,"procReceive"
  78. end
  79. local function procSend(client)
  80. if not procSubscribe(client) then
  81. return false,"procSubscribe"
  82. end
  83. while #outQueue["PUBLISH"]>0 do
  84. local item = table.remove(outQueue["PUBLISH"],1)
  85. local result = client:publish(item.t,item.p,item.q)
  86. if item.cb then item.cb(result,item.para) end
  87. if not result then
  88. return false,"procSend"
  89. else
  90. if sErrHandleCo then coroutine.resume(sErrHandleCo,"feed") end
  91. end
  92. end
  93. return true,"procSend"
  94. end
  95. --- 断开阿里云物联网套件的连接,并且不再重连
  96. -- @return nil
  97. -- @usage
  98. -- aLiYun.sleep()
  99. function sleep()
  100. isSleep = true
  101. log.info("aLiYun.sleep","open sleep, stop try reconnect")
  102. sys.publish("aliyun_publish_ind","disconnect")
  103. end
  104. --- 重新打开阿里云物联网套件的连接
  105. -- @return nil
  106. -- @usage
  107. -- aLiYun.wakeup()
  108. function wakeup()
  109. isSleep = false
  110. sys.publish("ALITUN_WAKEUP")
  111. log.info("aLiYun.wakeup","exit sleep")
  112. end
  113. --- 查看打开阿里云物联网套件的是否允许连接状态
  114. -- @return bool 是否允许连接阿里云
  115. -- @usage
  116. -- local ar = aLiYun.sleepStatus()
  117. function sleepStatus()
  118. return isSleep
  119. end
  120. --- 断开阿里云物联网套件的鉴权连接,并且不再重连
  121. -- @return nil
  122. -- @usage
  123. -- aLiYun.Authsleep()
  124. function Authsleep()
  125. isAuthSleep = true
  126. log.info("aLiYun.Authsleep","open sleep, stop try reconnect")
  127. sys.publish("aliyun_publish_ind","disconnect")
  128. end
  129. --- 重新打开阿里云物联网套件的鉴权连接
  130. -- @return nil
  131. -- @usage
  132. -- aLiYun.Authwakeup()
  133. function Authwakeup()
  134. isAuthSleep = false
  135. sys.publish("ALITUN_Auth_WAKEUP")
  136. log.info("aLiYun.auth_wakeup","exit sleep")
  137. end
  138. --- 查看打开阿里云物联网套件的是否允许鉴权状态
  139. -- @return bool 是否允许连接阿里云
  140. -- @usage
  141. -- local ar = aLiYun.AuthSleepStatus()
  142. function AuthSleepStatus()
  143. return isAuthSleep
  144. end
  145. function clientDataTask(host,tPorts,clientId,user,password)
  146. local retryConnectCnt = 0
  147. local portIdx = 0
  148. while true do
  149. if isSleep then sys.waitUntil("ALITUN_WAKEUP") end
  150. if not socket.isReady() then
  151. retryConnectCnt = 0
  152. --等待网络环境准备就绪,超时时间是5分钟
  153. sys.waitUntil("IP_READY_IND",300000)
  154. end
  155. if socket.isReady() then
  156. local mqttClient = mqtt.client(clientId,sKeepAlive or 240,user,password,sCleanSession,sWill)
  157. portIdx = portIdx%(#tPorts)+1
  158. if mqttClient:connect(host,tonumber(tPorts[portIdx]),sConnectMode=="direct" and "tcp" or "tcp_ssl") then
  159. retryConnectCnt = 0
  160. if aLiYunOta and aLiYunOta.connectCb then aLiYunOta.connectCb(true,sProductKey,sGetDeviceNameFnc()) end
  161. if evtCb["connect"] then evtCb["connect"](true) end
  162. local result,prompt = procSubscribe(mqttClient)
  163. if result then
  164. local procs,k,v = {procSend,procReceive}
  165. while true do
  166. for k,v in pairs(procs) do
  167. result,prompt = v(mqttClient)
  168. if not result then log.warn("aLiYun.clientDataTask."..prompt.." error") break end
  169. end
  170. if not result then break end
  171. if sErrHandleCo then coroutine.resume(sErrHandleCo,"feed") end
  172. end
  173. else
  174. log.warn("aLiYun.clientDataTask."..prompt.." error")
  175. end
  176. while #outQueue["PUBLISH"]>0 do
  177. local item = table.remove(outQueue["PUBLISH"],1)
  178. if item.cb then item.cb(false,item.para) end
  179. end
  180. if aLiYunOta and aLiYunOta.connectCb then aLiYunOta.connectCb(false,sProductKey,sGetDeviceNameFnc()) end
  181. if evtCb["connect"] then evtCb["connect"](false) end
  182. else
  183. retryConnectCnt = retryConnectCnt+1
  184. if evtCb["reconnect"] then evtCb["reconnect"]() end
  185. end
  186. mqttClient:disconnect()
  187. if retryConnectCnt>=5 then link.shut() retryConnectCnt=0 end
  188. sys.wait(2000)
  189. else
  190. --进入飞行模式,20秒之后,退出飞行模式
  191. net.switchFly(true)
  192. sys.wait(20000)
  193. net.switchFly(false)
  194. end
  195. end
  196. end
  197. local function getDeviceSecretCb(result,prompt,head,body)
  198. log.info("aLiYun.getDeviceSecretCb",result,prompt)
  199. if result and body then
  200. local tJsonDecode = json.decode(body)
  201. if tJsonDecode and tJsonDecode["data"] and tJsonDecode["data"]["deviceSecret"] and tJsonDecode["data"]["deviceSecret"]~="" then
  202. sSetDeviceSecretFnc(tJsonDecode["data"]["deviceSecret"])
  203. end
  204. end
  205. sys.publish("GetDeviceSecretEnd")
  206. end
  207. local function authCbFnc(result,statusCode,head,body)
  208. log.info("aLiYun.authCbFnc",result,statusCode,body)
  209. sys.publish("ALIYUN_AUTH_IND",result,statusCode,body)
  210. end
  211. local function getBody(tag)
  212. if tag=="auth" then
  213. local data = "clientId"..sGetDeviceNameFnc().."deviceName"..sGetDeviceNameFnc().."productKey"..sProductKey
  214. local signKey= sGetDeviceSecretFnc()
  215. local sign = crypto.hmac_md5(data,data:len(),signKey,signKey:len())
  216. return "productKey="..sProductKey.."&sign="..sign.."&clientId="..sGetDeviceNameFnc().."&deviceName="..sGetDeviceNameFnc()
  217. elseif tag=="register" then
  218. local random=rtos.tick()
  219. local data = "deviceName"..sGetDeviceNameFnc().."productKey"..sProductKey.."random"..random
  220. local sign = crypto.hmac_md5(data,data:len(),sProductSecret,sProductSecret:len())
  221. return "productKey="..sProductKey.."&deviceName="..sGetDeviceNameFnc().."&random="..random.."&sign="..sign.."&signMethod=HmacMD5"
  222. end
  223. end
  224. function clientAuthTask()
  225. while not socket.isReady() do sys.waitUntil("IP_READY_IND") end
  226. while true do
  227. if isAuthSleep then sys.waitUntil("ALITUN_Auth_WAKEUP") end
  228. local retryCnt,authBody = 0,getBody("auth")
  229. while true do
  230. http.request("POST",
  231. "https://iot-auth."..sRegion..".aliyuncs.com/auth/devicename",
  232. nil,{["Content-Type"]="application/x-www-form-urlencoded"},authBody,20000,authCbFnc)
  233. local _,result,statusCode,body = sys.waitUntil("ALIYUN_AUTH_IND")
  234. --log.info("aLiYun.clientAuthTask1",result and statusCode=="200",body)
  235. local invalidSign
  236. if result and statusCode=="200" then
  237. local tJsonDecode,result = json.decode(body)
  238. --log.info("aLiYun.clientAuthTask2",result,tJsonDecode["message"],tJsonDecode["data"])
  239. if result and tJsonDecode["message"]=="success" and tJsonDecode["data"] and type(tJsonDecode["data"])=="table" then
  240. --log.info("aLiYun.clientAuthTask3",tJsonDecode["data"]["iotId"],tJsonDecode["data"]["iotToken"])
  241. if tJsonDecode["data"]["iotId"] and tJsonDecode["data"]["iotId"]~="" and tJsonDecode["data"]["iotToken"] and tJsonDecode["data"]["iotToken"]~="" then
  242. if evtCb["auth"] then evtCb["auth"](true) end
  243. local ports,host,returnMqtt = {}
  244. if tJsonDecode["data"]["resources"] and type(tJsonDecode["data"]["resources"])=="table" then
  245. if tJsonDecode["data"]["resources"]["mqtt"] then
  246. returnMqtt,host = true,tJsonDecode["data"]["resources"]["mqtt"]["host"]
  247. table.insert(ports,tJsonDecode["data"]["resources"]["mqtt"]["port"])
  248. end
  249. end
  250. sys.taskInit(clientDataTask,returnMqtt and host or sProductKey..".iot-as-mqtt."..sRegion..".aliyuncs.com",#ports~=0 and ports or {1883},sGetDeviceNameFnc(),tJsonDecode["data"]["iotId"],tJsonDecode["data"]["iotToken"])
  251. return
  252. end
  253. end
  254. if body and body:match("invalid sign") then
  255. invalidSign = true
  256. end
  257. end
  258. if sProductSecret and invalidSign then
  259. http.request("POST","https://iot-auth."..sRegion..".aliyuncs.com/auth/register/device",nil,
  260. {['Content-Type']="application/x-www-form-urlencoded"},
  261. getBody("register"),30000,getDeviceSecretCb)
  262. sys.waitUntil("GetDeviceSecretEnd")
  263. sys.wait(1000)
  264. authBody = getBody("auth")
  265. end
  266. retryCnt = retryCnt+1
  267. if retryCnt==3 then
  268. break
  269. end
  270. end
  271. if evtCb["auth"] then evtCb["auth"](false) end
  272. sys.wait(5000)
  273. end
  274. end
  275. local function directProc()
  276. local clientId = (sGetClientIdFnc and sGetClientIdFnc() or sGetDeviceNameFnc()).."|securemode=3,timestamp=2524608000000,signmethod=hmacsha1|"
  277. local userName = sGetUserNameFnc and sGetUserNameFnc() or (sGetDeviceNameFnc().."&"..sProductKey)
  278. local password
  279. if sGetPasswordFnc then
  280. password = sGetPasswordFnc()
  281. else
  282. local content = "clientId"..(sGetClientIdFnc and sGetClientIdFnc() or sGetDeviceNameFnc()).."deviceName"..sGetDeviceNameFnc().."productKey"..sProductKey.."timestamp2524608000000"
  283. local signKey= sGetDeviceSecretFnc()
  284. password = crypto.hmac_sha1(content,content:len(),signKey,signKey:len())
  285. end
  286. log.info("aLiYun.directProc",clientId,userName,password)
  287. sys.taskInit(clientDataTask,sConnectHost or (sProductKey..".iot-as-mqtt."..sRegion..".aliyuncs.com"),{sConnectPort},clientId,userName,password)
  288. end
  289. local function clientDirectTask()
  290. while not socket.isReady() do sys.waitUntil("IP_READY_IND") end
  291. local tm=os.time()
  292. --一机一密
  293. if sProductSecret==nil then
  294. directProc()
  295. --一型一密
  296. else
  297. local clientId
  298. --预注册
  299. if sInstanceId==nil then
  300. clientId = (sGetClientIdFnc and sGetClientIdFnc() or sGetDeviceNameFnc()).."|securemode=2,authType=register,random="..tm..",signmethod=hmacsha1|"
  301. --免预注册
  302. else
  303. clientId = (sGetClientIdFnc and sGetClientIdFnc() or sGetDeviceNameFnc()).."|securemode=-2,authType=regnwl,random="..tm..",signmethod=hmacsha1,instanceId="..sInstanceId.."|"
  304. end
  305. local userName = sGetUserNameFnc and sGetUserNameFnc() or (sGetDeviceNameFnc().."&"..sProductKey)
  306. local content = "deviceName"..sGetDeviceNameFnc().."productKey"..sProductKey.."random"..tm
  307. local signKey= sProductSecret
  308. local password = crypto.hmac_sha1(content,content:len(),signKey,signKey:len())
  309. while true do
  310. if isAuthSleep then sys.waitUntil("ALITUN_Auth_WAKEUP") end
  311. local mqttClient = mqtt.client(clientId,sKeepAlive or 240,userName,password)
  312. local r,ack = mqttClient:connect(sConnectHost,sConnectPort,"tcp_ssl")
  313. if r then
  314. local result,data = mqttClient:receive(60000)
  315. --接收到数据
  316. if result then
  317. log.info("aLiYun.clientDirectTask register rsp",data.topic,data.payload)
  318. local tJsonDecode,res = json.decode(data.payload)
  319. if res and tJsonDecode["deviceName"] and tJsonDecode["deviceSecret"] then
  320. sSetDeviceSecretFnc(tJsonDecode["deviceSecret"])
  321. sys.wait(1000)
  322. mqttClient:disconnect()
  323. directProc()
  324. break
  325. end
  326. end
  327. end
  328. mqttClient:disconnect()
  329. if ack==4 then
  330. directProc()
  331. break
  332. else
  333. sys.wait(5000)
  334. end
  335. end
  336. end
  337. end
  338. --- 配置阿里云物联网套件的产品信息和设备信息
  339. -- @string productKey,产品标识
  340. -- @string[opt=nil] productSecret,产品密钥
  341. -- 一机一密认证方案时,此参数传入nil
  342. -- 一型一密认证方案时,此参数传入真实的产品密钥
  343. -- @function getDeviceNameFnc,获取设备名称的函数
  344. -- @function getDeviceSecretFnc,获取设备密钥的函数
  345. -- @function[opt=nil] setDeviceSecretFnc,设置设备密钥的函数,一型一密认证方案才需要此参数
  346. -- @return nil
  347. -- @usage
  348. -- aLiYun.setup("b0FMK1Ga5cp",nil,getDeviceNameFnc,getDeviceSecretFnc)
  349. -- aLiYun.setup("a1AoVqkCIbG","7eCdPyR6fYPntFcM",getDeviceNameFnc,getDeviceSecretFnc,setDeviceSecretFnc)
  350. function setup(productKey,productSecret,getDeviceNameFnc,getDeviceSecretFnc,setDeviceSecretFnc)
  351. sProductKey,sProductSecret,sGetDeviceNameFnc,sGetDeviceSecretFnc,sSetDeviceSecretFnc = productKey,productSecret,getDeviceNameFnc,getDeviceSecretFnc,setDeviceSecretFnc
  352. if sConnectMode=="direct" then
  353. sys.taskInit(clientDirectTask)
  354. else
  355. sys.taskInit(clientAuthTask)
  356. end
  357. end
  358. --- 设置MQTT数据通道的参数
  359. -- @number[opt=1] cleanSession 1/0
  360. -- @table[opt=nil] will 遗嘱参数,格式为{qos=, retain=, topic=, payload=}
  361. -- @number[opt=240] keepAlive,单位秒
  362. -- @return nil
  363. -- @usage
  364. -- aLiYun.setMqtt(0)
  365. -- aLiYun.setMqtt(1,{qos=0,retain=1,topic="/willTopic",payload="will payload"})
  366. -- aLiYun.setMqtt(1,{qos=0,retain=1,topic="/willTopic",payload="will payload"},120)
  367. function setMqtt(cleanSession,will,keepAlive)
  368. sCleanSession,sWill,sKeepAlive = cleanSession,will,keepAlive
  369. end
  370. --- 设置地域region id
  371. -- @string region,地域id字符串,参考:https://help.aliyun.com/document_detail/40654.html?spm=a2c4g.11186623.2.16.c0a63f82Z7qCtA#concept-h4v-j5k-xdb
  372. -- @return nil
  373. -- @usage
  374. -- 设置华北1:aLiYun.setRegion("cn-qingdao")
  375. -- 设置华东1:aLiYun.setRegion("cn-hangzhou")
  376. -- 设置华南1:aLiYun.setRegion("cn-shenzhen")
  377. function setRegion(region)
  378. sRegion = region
  379. end
  380. -- 设置企业版实例id
  381. -- @string id,企业版实例id
  382. -- @return nil
  383. -- @usage
  384. -- aLiYun.setInstanceId(iot-060a1234")
  385. function setInstanceId(id)
  386. sInstanceId = id
  387. end
  388. --- 设置连接方式
  389. -- @string mode,连接方式,支持如下几种方式:
  390. -- "direct"表示MQTT-TCP直连
  391. -- @string host,服务器地址
  392. -- @number port,服务器端口
  393. -- @function getClientIdFnc,获取mqtt client id的函数
  394. -- @function getUserNameFnc,获取mqtt client userName的函数
  395. -- @function getPasswordFnc,获取mqtt client password的函数
  396. -- @return nil
  397. -- @usage
  398. -- 设置为MQTT-TCP直连:aLiYun.setConnectMode("direct")
  399. function setConnectMode(mode,host,port,getClientIdFnc,getUserNameFnc,getPasswordFnc)
  400. sConnectMode = mode
  401. sConnectHost = host
  402. sConnectPort = port or 1883
  403. sGetClientIdFnc = getClientIdFnc
  404. sGetUserNameFnc = getUserNameFnc
  405. sGetPasswordFnc = getPasswordFnc
  406. end
  407. --- 订阅主题
  408. -- @param topic,string或者table类型,一个主题时为string类型,多个主题时为table类型,主题内容为UTF8编码
  409. -- @param qos,number或者nil,topic为一个主题时,qos为number类型(0/1,默认0);topic为多个主题时,qos为nil
  410. -- @return nil
  411. -- @usage
  412. -- aLiYun.subscribe("/b0FMK1Ga5cp/862991234567890/get", 0)
  413. -- aLiYun.subscribe({["/b0FMK1Ga5cp/862991234567890/get"] = 0, ["/b0FMK1Ga5cp/862991234567890/get"] = 1})
  414. function subscribe(topic,qos)
  415. insert("SUBSCRIBE",topic,qos)
  416. sys.publish("aliyun_publish_ind","send")
  417. end
  418. --- 发布一条消息
  419. -- @string topic,UTF8编码的主题
  420. -- @string payload,负载
  421. -- @number[opt=0] qos,质量等级,0/1,默认0
  422. -- @function[opt=nil] cbFnc,消息发布结果的回调函数
  423. -- 回调函数的调用形式为:cbFnc(result,cbPara)。result为true表示发布成功,false或者nil表示订阅失败;cbPara为本接口中的第5个参数
  424. -- @param[opt=nil] cbPara,消息发布结果回调函数的回调参数
  425. -- @return nil
  426. -- @usage
  427. -- aLiYun.publish("/b0FMK1Ga5cp/862991234567890/update","test",0)
  428. -- aLiYun.publish("/b0FMK1Ga5cp/862991234567890/update","test",1,cbFnc,"cbFncPara")
  429. function publish(topic,payload,qos,cbFnc,cbPara)
  430. insert("PUBLISH",topic,qos,payload,cbFnc,cbPara)
  431. sys.publish("aliyun_publish_ind","send")
  432. log.info("aliyun aliyun_publish_ind","publish")
  433. end
  434. --- 注册事件的处理函数
  435. -- @string evt,事件
  436. -- "auth"表示鉴权服务器认证结果事件
  437. -- "connect"表示接入服务器连接结果事件
  438. -- "reconnect"表示重连事件
  439. -- "receive"表示接收到接入服务器的消息事件
  440. -- @function cbFnc,事件的处理函数
  441. -- 当evt为"auth"时,cbFnc的调用形式为:cbFnc(result),result为true表示认证成功,false或者nil表示认证失败
  442. -- 当evt为"connect"时,cbFnc的调用形式为:cbFnc(result),result为true表示连接成功,false或者nil表示连接失败
  443. -- 当evt为"receive"时,cbFnc的调用形式为:cbFnc(topic,qos,payload),topic为UTF8编码的主题(string类型),qos为质量等级(number类型),payload为原始编码的负载(string类型)
  444. -- 当evt为"reconnect"时,cbFnc的调用形式为:cbFnc(),表示lib中在自动重连阿里云服务器
  445. -- @return nil
  446. -- @usage
  447. -- aLiYun.on("connect",cbFnc)
  448. function on(evt,cbFnc)
  449. evtCb[evt] = cbFnc
  450. end
  451. --- 设置阿里云task连续一段时间工作异常的处理程序
  452. -- @function cbFnc,异常处理函数,cbFnc的调用形式为:cbFnc()
  453. -- @number[opt=150] tmout,连续工作异常的时间,当连续异常到达这个时间之后,会调用cbFnc()
  454. -- @return nil
  455. -- @usage
  456. -- aLiYun.setErrHandle(function() sys.restart("ALIYUN_TASK_INACTIVE") end, 300)
  457. function setErrHandle(cbFnc,tmout)
  458. sErrHandleCb = cbFnc
  459. sErrHandleTmout = tmout or 150
  460. if not sErrHandleCo then
  461. sErrHandleCo = sys.taskInit(function()
  462. while true do
  463. if sys.wait(sErrHandleTmout*1000) == nil then
  464. if not isSleep then
  465. sErrHandleCb()
  466. end
  467. end
  468. end
  469. end)
  470. end
  471. end