longLinkSocketTask.lua 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. module(...,package.seeall)
  2. require"socket"
  3. require"nvm"
  4. require"utils"
  5. --调度中心服务器信息
  6. local ddzxIp,ddzxTcpPort = nvm.get("ddzxIp"),nvm.get("ddzxTcpPort")
  7. local ddzxWaitRecvMsgMaxTime = nvm.get("ddzxWaitRecvMsgMaxTime")
  8. local devId = nvm.get("devId")
  9. local devSn = nvm.get("devSn")
  10. --ntp同步时间结果
  11. local timerSyncResult = false
  12. --长连接socket连接状态
  13. local longLinkSocketConnState = false
  14. --前置机服务器信息
  15. local qzjIp,qzjTcpPort
  16. local qzjFrameSn = 0x0000
  17. --协议参数
  18. local prefix = 0xdc
  19. local version = 0x0000
  20. local encryptType = 0x00
  21. local channel = 0x00
  22. local errorCode = 0x0000
  23. --待上报消息队列最大长度
  24. local MSG_QUENE_MAX_LENGTH = nvm.get("msgQueueMaxLen") or 3000
  25. --十六进制字符串反转
  26. local function hexStrReverse(hexstr)
  27. local str = ""
  28. for i = 1, string.len(hexstr) - 1, 2 do
  29. local tmpStr = string.sub(hexstr, -(i+1), -i)
  30. str = str .. tmpStr
  31. end
  32. return str
  33. end
  34. --openMulByteReverse:开启多字节反转
  35. local function hex2bin( hexstr, openMulByteReverse )
  36. --检查字符串长度
  37. if(hexstr:len()%2~=0) then
  38. return false,"hex2str invalid input lenth"
  39. end
  40. if openMulByteReverse then
  41. hexstr = hexStrReverse(hexstr)
  42. end
  43. local str = ""
  44. for i = 1, string.len(hexstr) - 1, 2 do
  45. local doublebytestr = string.sub(hexstr, i, i+1);
  46. local n = tonumber(doublebytestr, 16);
  47. if 0 == n then
  48. str = str .. '\00'
  49. else
  50. str = str .. string.format("%c", n)
  51. end
  52. end
  53. return str
  54. end
  55. local function hex2str(str)
  56. --判断输入类型
  57. if (type(str)~="string") then
  58. return nil,"hex2str invalid input type"
  59. end
  60. --滤掉分隔符
  61. str=str:gsub("[%s%p]",""):upper()
  62. --检查内容是否合法
  63. if(str:find("[^0-9A-Fa-f]")~=nil) then
  64. return nil,"hex2str invalid input content"
  65. end
  66. --检查字符串长度
  67. if(str:len()%2~=0) then
  68. return nil,"hex2str invalid input lenth"
  69. end
  70. --拼接字符串
  71. local index=1
  72. local ret=""
  73. for index=1,str:len(),2 do
  74. ret=ret..string.char(tonumber(str:sub(index,index+1),16))
  75. end
  76. --log.info("socketHeartbeatTask.hex2str", ret)
  77. return ret
  78. end
  79. local function getFormatTimeBin(time)
  80. local tClock = time and os.date("*t",time) or os.date("*t")
  81. local formatTimeBin = string.char(tonumber((""..tClock.year):sub(3,4)))
  82. ..string.char(tClock.month)
  83. ..string.char(tClock.day)
  84. ..string.char(tClock.hour)
  85. ..string.char(tClock.min)
  86. ..string.char(tClock.sec)
  87. return formatTimeBin
  88. end
  89. --计算头部校验码
  90. local function getHeadVerifyCode(packet)
  91. if not packet then
  92. log.info("longLinkSocketTask.getHeadVerifyCode", "packet empty!!")
  93. return false
  94. end
  95. if #packet <22 then
  96. log.info("longLinkSocketTask.getHeadVerifyCode", "packet length < 22!! ",packet:toHex())
  97. return false
  98. end
  99. local CRC = 0XFFFF
  100. for i=1,22 do
  101. CRC = bit.bxor( CRC, string.byte(packet:sub(i,i)))
  102. end
  103. local verifyCodeBin = string.char(bit.band(CRC,0x00FF))
  104. return true, verifyCodeBin
  105. end
  106. --计算尾部校验码
  107. local function getTailVerifyCode(packet)
  108. if not packet then
  109. log.info("longLinkSocketTask.getTailVerifyCode", "packet empty!!")
  110. return false
  111. end
  112. local CRC = 0XFFFF
  113. if #packet <= 0 then
  114. CRC = 0X0000
  115. else
  116. for i=1,#packet do
  117. CRC = bit.bxor( CRC, string.byte(packet:sub(i,i)))
  118. for j=1,8 do
  119. if bit.band(CRC,1) ~= 0 then
  120. CRC = bit.bxor(bit.rshift(CRC,1), 0xA001)
  121. else
  122. CRC = bit.rshift(CRC,1)
  123. end
  124. end
  125. end
  126. end
  127. local verifyCodeBin = string.char(bit.band(CRC,0x00FF))..string.char(bit.rshift(CRC,8))
  128. return true, verifyCodeBin
  129. end
  130. --生成报文
  131. local function createPacket(frameSn,messageType,commandId,reserve,content)
  132. if not prefix then
  133. log.info("longLinkSocketTask.createPacket", "prefix empty!!")
  134. return false
  135. end
  136. if not version then
  137. log.info("longLinkSocketTask.createPacket", "version empty!!")
  138. return false
  139. end
  140. if not encryptType then
  141. log.info("longLinkSocketTask.createPacket", "encryptType empty!!")
  142. return false
  143. end
  144. if not channel then
  145. log.info("longLinkSocketTask.createPacket", "channel empty!!")
  146. return false
  147. end
  148. if not errorCode then
  149. log.info("longLinkSocketTask.createPacket", "errorCode empty!!")
  150. return false
  151. end
  152. if not devSn then
  153. log.info("longLinkSocketTask.createPacket", "devSn empty!!")
  154. return false
  155. end
  156. if not devId then
  157. log.info("longLinkSocketTask.createPacket", "devId empty!!")
  158. return false
  159. end
  160. if not frameSn then
  161. log.info("longLinkSocketTask.createPacket", "frameSn empty!!")
  162. return false
  163. end
  164. if not messageType then
  165. log.info("longLinkSocketTask.createPacket", "messageType empty!!")
  166. return false
  167. end
  168. if not commandId then
  169. log.info("longLinkSocketTask.createPacket", "commandId empty!!")
  170. return false
  171. end
  172. if not reserve then
  173. log.info("longLinkSocketTask.createPacket", "reserve empty!!")
  174. return false
  175. end
  176. local packetBin = ""
  177. local frameSnHexStr = string.format("%04x",frameSn)
  178. local devIdHexStr = string.format("%08x", commandId == 0x0002 and 0x00000000 or devId)
  179. local commandIdHexStr = string.format("%04x",commandId)
  180. local reserveHexStr = string.format("%08x",reserve)
  181. local contentSizeHexStr = string.format("%04x",#content)
  182. local errorCodeHexStr = string.format("%04x",errorCode)
  183. packetBin = string.char(prefix)..hex2bin(string.format("%04x",version))..string.char(encryptType)..hex2bin(frameSnHexStr,true)..string.char(channel)
  184. ..hex2bin(errorCodeHexStr)..hex2bin(devIdHexStr,true)..string.char(messageType)..hex2bin(commandIdHexStr)
  185. ..hex2bin(reserveHexStr)..hex2bin(contentSizeHexStr,true)
  186. local headRes, headVerifyCodeBin = getHeadVerifyCode(packetBin)
  187. if not headRes then
  188. log.info("longLinkSocketTask.createPacket", "getHeadVerifyCode failed!!")
  189. return false
  190. end
  191. packetBin = packetBin..headVerifyCodeBin..content
  192. local tailRes, tailVerifyCodeBin = getTailVerifyCode(packetBin)
  193. if not tailRes then
  194. log.info("longLinkSocketTask.createPacket", "getTailVerifyCode failed!!")
  195. return false
  196. end
  197. packetBin = packetBin..tailVerifyCodeBin
  198. --log.info("longLinkSocketTask.createPacket", "packetBin hex:",packetBin:toHex())
  199. return true, packetBin
  200. end
  201. --解析响应报文
  202. local function parseRespPacket(packet)
  203. if not packet then
  204. log.info("longLinkSocketTask.parseRespPacket", "packet empty!!")
  205. return false
  206. end
  207. if #packet < 25 then
  208. log.info("longLinkSocketTask.parseRespPacket", "packet length < 25!! packet:", packet:toHex())
  209. return false
  210. end
  211. local prefixP = string.byte(packet:sub(1,1))
  212. if prefixP ~= prefix then
  213. log.info("longLinkSocketTask.parseRespPacket", "prefix invalid!! prefixP:", prefixP)
  214. return false
  215. end
  216. local messageTypeP = pack.unpack(packet:sub(14),">b")
  217. if messageTypeP ~= 0x02 then
  218. log.info("longLinkSocketTask.parseRespPacket", "messageType invalid!! messageTypeP:", messageTypeP)
  219. return false
  220. end
  221. local contentStart = 24
  222. --local contentLenP = pack.unpack(packet:sub(21,22),"<H")
  223. local contentLenP = string.byte(packet:sub(22,22))*16 + string.byte(packet:sub(21,21))
  224. local contenP = ""
  225. local parseRes = {}
  226. local commandIdP = string.byte(packet:sub(15,15))*16 + string.byte(packet:sub(16,16))
  227. parseRes["commandId"] = commandIdP
  228. parseRes["reserve"] = packet:sub(17,20):toHex()
  229. log.info("longLinkSocketTask.parseRespPacket","commandIdP:", packet:sub(15,16):toHex(),"contentLenP:",contentLenP,"messageTypeP:",messageTypeP)
  230. if commandIdP == 0x0002 then
  231. if contentLenP == 0 then
  232. log.info("longLinkSocketTask.parseRespPacket", "contentLen invalid!! ")
  233. return false
  234. end
  235. if contentLenP + 25 ~= #packet then
  236. log.info("longLinkSocketTask.parseRespPacket", "packet format error!! packet:", packet:toHex())
  237. return false
  238. end
  239. contenP = packet:sub(24,contentLenP+23)
  240. local splitPos = string.find(contenP,"\/")
  241. if not splitPos then
  242. log.info("longLinkSocketTask.parseRespPacket","split char \/ not found!! contenP:", contenP)
  243. return false
  244. end
  245. local qzjIpP = string.sub(contenP,1,splitPos-1)
  246. local qzjPortP = string.sub(contenP,splitPos+1)
  247. parseRes["qzjIp"] = qzjIpP
  248. parseRes["qzjPortP"] = qzjPortP
  249. qzjIp = qzjIpP
  250. qzjTcpPort = qzjPortP
  251. log.info("longLinkSocketTask.parseRespPacket","parseRes qzjIpP:", qzjIpP, "qzjPortP:", qzjPortP)
  252. return true, parseRes
  253. elseif commandIdP == 0x0003 then
  254. return true, parseRes
  255. elseif commandIdP == 0x0018 then
  256. if contentLenP ~= 0x06 then
  257. log.info("longLinkSocketTask.parseRespPacket", "contentLen invalid!! ")
  258. return false
  259. end
  260. if contentLenP + 25 ~= #packet then
  261. log.info("longLinkSocketTask.parseRespPacket", "packet format error!! packet:", packet:toHex())
  262. return false
  263. end
  264. contenP = packet:sub(24,contentLenP+23)
  265. local Y,m,d,h,i,s = string.byte(contenP:sub(1,1))+2000
  266. ,string.byte(contenP:sub(2,2))
  267. ,string.byte(contenP:sub(3,3))
  268. ,string.byte(contenP:sub(4,4))
  269. ,string.byte(contenP:sub(5,5))
  270. ,string.byte(contenP:sub(6,6))
  271. local serverTime = os.time({day=d, month=m, year=Y, hour=h, minute=i, second=s})
  272. parseRes["serverTime"] = serverTime
  273. log.info("longLinkSocketTask.parseRespPacket","serverTime:", serverTime)
  274. return true, parseRes
  275. elseif commandIdP == 0x0007 then
  276. return true, parseRes
  277. else
  278. log.info("longLinkSocketTask.parseRespPacket","commandIdP invalid!!")
  279. return false
  280. end
  281. end
  282. --数据发送的消息队列
  283. local msgQuene = {}
  284. local function insertMsg(data)
  285. if #msgQuene >= MSG_QUENE_MAX_LENGTH then
  286. log.warn("longLinkSocketTask.insertMsg", "------> #msgQuene >= MSG_QUENE_MAX_LENGTH !! skip insert !! <-------", #msgQuene, MSG_QUENE_MAX_LENGTH)
  287. --table.remove(msgQuene,1)
  288. return false
  289. end
  290. table.insert(msgQuene,data)
  291. return true
  292. end
  293. function waitForSend()
  294. return #msgQuene > 0
  295. end
  296. function outMsgprocess(socketClient)
  297. --队列中有消息
  298. while #msgQuene>0 do
  299. --获取消息,并从队列中删除
  300. local outMsg = table.remove(msgQuene,1)
  301. log.info("longLinkSocketTask.outMsgprocess","send qzj message:",outMsg:toHex(),os.time())
  302. --发送这条消息,并获取发送结果
  303. local result = socketClient:send(outMsg)
  304. --发送失败的话立刻返回nil(等同于false)
  305. if not result then return end
  306. end
  307. return true
  308. end
  309. function inMsgProcess(socketClient)
  310. local result,data
  311. while true do
  312. result,data = socketClient:recv(2000)
  313. --接收到数据
  314. if result then --接收成功
  315. log.info("longLinkSocketTask.inMsgProcess","receive qzj message:",data:toHex())
  316. local res,parseData = parseRespPacket(data)
  317. if res then
  318. --处理data数据
  319. if parseData.commandId == 0x0003 then --收到前置机连接应答报文
  320. qzjFrameSn = qzjFrameSn + 1
  321. local res, qzjGetTimePacket = createPacket(qzjFrameSn,0x1,0x0018,0x00000000,"")
  322. if res then
  323. insertMsg(qzjGetTimePacket)
  324. else
  325. log.error("longLinkSocketTask.inMsgProcess","createPacket qzjGetTimePacket failed!!")
  326. end
  327. elseif parseData.commandId == 0x0018 then --收到前置机获取时间应答报文
  328. qzjFrameSn = qzjFrameSn + 1
  329. local timeBin = getFormatTimeBin()
  330. local content = string.char(0x03)..string.char(0x00)..timeBin
  331. local res, qzjReportTimePacket = createPacket(qzjFrameSn,0x1,0x0007,0x05000000,content)
  332. if res then
  333. insertMsg(qzjReportTimePacket)
  334. else
  335. log.error("longLinkSocketTask.inMsgProcess","createPacket qzjReportTimePacket failed!! reserve(0x05000000)")
  336. end
  337. elseif parseData.commandId == 0x0007 then
  338. if parseData.reserve == "05000000" then
  339. local timeBin = getFormatTimeBin()
  340. local content = string.char(0x03)..string.char(0x00)..timeBin
  341. local res, qzjReportTimePacket = createPacket(0x0000,0x1,0x0007,0x02000000,content)
  342. if res then
  343. insertMsg(qzjReportTimePacket)
  344. else
  345. log.error("longLinkSocketTask.inMsgProcess","createPacket qzjReportTimePacket failed!! reserve(0x02000000)")
  346. end
  347. elseif parseData.reserve == "02000000" then
  348. local timeBin = getFormatTimeBin()
  349. local content = string.char(0x03)..string.char(0xf0)..timeBin..hex2bin("923c0aaace84c4341432c013e3")
  350. qzjFrameSn = qzjFrameSn + 1
  351. local res, qzjHeartbeatFirstPacket = createPacket(qzjFrameSn,0x1,0x0007,0x04003c0a,content)
  352. if res then
  353. insertMsg(qzjHeartbeatFirstPacket)
  354. else
  355. log.error("longLinkSocketTask.inMsgProcess","createPacket qzjHeartbeatFirstPacket failed!!")
  356. end
  357. sys.publish("MESSAGE_TYPE_START_HEARTBEAT")
  358. end
  359. else
  360. log.error("longLinkSocketTask.inMsgProcess","parseData.commandId invalid!! commandId:", parseData.commandId)
  361. end
  362. else
  363. log.error("longLinkSocketTask.inMsgProcess","parseRespPacket failed!!",data:toHex())
  364. end
  365. --如果msgQuene中有等待发送的数据,则立即退出本循环
  366. if waitForSend() then return true end
  367. else --接收失败
  368. log.info("longLinkSocketTask.inMsgProcess","wait receive qzj message timeout")
  369. --如果msgQuene中有等待发送的数据,则立即退出本循环
  370. if waitForSend() then return true end
  371. break
  372. end
  373. end
  374. --返回结果,处理成功返回true,处理出错返回false
  375. return result or data=="timeout"
  376. end
  377. --连接前置机主任务
  378. sys.taskInit(
  379. function()
  380. while true do
  381. log.info("longLinkSocketTask.qzjTask","wait ON_MESSAGE_DDZX_AUTH_SUCCESS message ...")
  382. local res,data = sys.waitUntil("ON_MESSAGE_DDZX_AUTH_SUCCESS", 3600*1000)
  383. if res then
  384. log.info("longLinkSocketTask.qzjTask","receive ON_MESSAGE_DDZX_AUTH_SUCCESS message")
  385. break
  386. else
  387. log.info("longLinkSocketTask.qzjTask","wait ON_MESSAGE_DDZX_AUTH_SUCCESS timeout")
  388. end
  389. end
  390. local retryConnectCnt = 0 --失败次数统计
  391. while true do
  392. --是否获取到了分配的ip(是否连上网)
  393. if socket.isReady() then
  394. --新建一个socket对象,如果是udp只需要把tcp改成udp即可
  395. local socketClient = socket.tcp()
  396. --尝试连接指定服务器
  397. if socketClient:connect(qzjIp,qzjTcpPort) then
  398. --连接成功
  399. log.info("longLinkSocketTask.qzjTask","connect success")
  400. retryConnectCnt = 0 --失败次数清零
  401. longLinkSocketConnState = true
  402. --循环处理接收和发送的数据
  403. while true do
  404. if not inMsgProcess(socketClient) then --接收消息处理函数
  405. log.error("longLinkSocketTask.qzjTask","longLinkSocketTask.inMsgProcess error")
  406. break
  407. end
  408. if not outMsgprocess(socketClient) then --发送消息处理函数
  409. log.error("longLinkSocketTask.qzjTask","longLinkSocketTask.outMsgprocess error")
  410. break
  411. end
  412. end
  413. else
  414. log.info("longLinkSocketTask.qzjTask","connect fail")
  415. --连接失败
  416. retryConnectCnt = retryConnectCnt+1 --失败次数加一
  417. end
  418. socketClient:close() --断开socket连接
  419. if retryConnectCnt>=5 then --失败次数大于五次了
  420. link.shut() --强制断开TCP/UDP连接
  421. retryConnectCnt=0 --失败次数清零
  422. longLinkSocketConnState = false
  423. --停止重连前置机的尝试,重新从调度中心获取可用的端口
  424. sys.publish("ON_MESSAGE_DO_DDZX_TASK",true)
  425. while true do
  426. log.info("longLinkSocketTask.qzjTask","wait ON_MESSAGE_DDZX_AUTH_SUCCESS message ...")
  427. local res,data = sys.waitUntil("ON_MESSAGE_DDZX_AUTH_SUCCESS", 3600*1000)
  428. if res then
  429. log.info("longLinkSocketTask.qzjTask","receive ON_MESSAGE_DDZX_AUTH_SUCCESS message")
  430. break
  431. else
  432. log.info("longLinkSocketTask.qzjTask","wait ON_MESSAGE_DDZX_AUTH_SUCCESS timeout")
  433. end
  434. end
  435. else
  436. sys.wait(5000)
  437. end
  438. else
  439. retryConnectCnt = 0 --没连上网,失败次数清零
  440. longLinkSocketConnState = false
  441. --没连上网
  442. --等待网络环境准备就绪,超时时间是5分钟
  443. sys.waitUntil("IP_READY_IND",300000)
  444. --等完了还没连上?
  445. if not socket.isReady() then
  446. --进入飞行模式,20秒之后,退出飞行模式
  447. net.switchFly(true)
  448. sys.wait(20000)
  449. net.switchFly(false)
  450. end
  451. end
  452. end
  453. end)
  454. --等待时间同步成功消息通知
  455. sys.subscribe("TIMER_SYNC_SUCCESS", function ( ... )
  456. log.info("longLinkSocketTask.subscribe","TIMER_SYNC_SUCCESS")
  457. timerSyncResult = true
  458. end)
  459. --连接调度中心(获取前置机连接信息)
  460. sys.taskInit(
  461. function()
  462. while not timerSyncResult do
  463. log.info("longLinkSocketTask.ddzxSocketClient","wait TIMER_SYNC_SUCCESS message ...")
  464. sys.wait(1000)
  465. end
  466. while not devSn do
  467. log.info("longLinkSocketTask.ddzxSocketClient","devSn empty! time:", os.time())
  468. devSn = nvm.get("devSn")
  469. sys.wait(1000)
  470. end
  471. while not devId do
  472. log.info("longLinkSocketTask.ddzxSocketClient","devId empty! time:", os.time())
  473. devId = nvm.get("devId")
  474. sys.wait(1000)
  475. end
  476. while not ddzxIp do
  477. log.info("longLinkSocketTask.ddzxSocketClient","ddzxIp empty! time:", os.time())
  478. ddzxIp = nvm.get("ddzxIp")
  479. sys.wait(1000)
  480. end
  481. while not ddzxTcpPort do
  482. log.info("longLinkSocketTask.ddzxSocketClient","ddzxTcpPort empty! time:", os.time())
  483. ddzxTcpPort = nvm.get("ddzxTcpPort")
  484. sys.wait(1000)
  485. end
  486. while not ddzxWaitRecvMsgMaxTime do
  487. log.info("longLinkSocketTask.ddzxSocketClient","ddzxWaitRecvMsgMaxTime empty! time:", os.time())
  488. ddzxWaitRecvMsgMaxTime = nvm.get("ddzxWaitRecvMsgMaxTime")
  489. sys.wait(1000)
  490. end
  491. local retryConnectCnt = 0 --失败次数统计
  492. while true do
  493. --是否获取到了分配的ip(是否连上网)
  494. if socket.isReady() then
  495. --新建一个socket对象,如果是udp只需要把tcp改成udp即可
  496. local ddzxSocketClient = socket.tcp()
  497. --尝试连接指定服务器
  498. if ddzxSocketClient:connect(ddzxIp,ddzxTcpPort) then
  499. local result,packet_data = createPacket(0,0x1,0x0002,0x00000000,devSn)
  500. if not result then
  501. log.info("longLinkSocketTask.ddzxSocketClient", "createDdzxAuthPacket failed!!")
  502. else
  503. --连接成功
  504. log.info("longLinkSocketTask.ddzxSocketClient", "ddzxIp", ddzxIp, "ddzxTcpPort", ddzxTcpPort, "packet_data", packet_data:toHex())
  505. if ddzxSocketClient:send(packet_data, 10) then
  506. retryConnectCnt = 0
  507. log.info("longLinkSocketTask.ddzxSocketClient", "wait recv server message ... time:", os.time())
  508. local res,ddzx_data = ddzxSocketClient:recv(ddzxWaitRecvMsgMaxTime*1000)
  509. if not res then
  510. log.info("longLinkSocketTask.ddzxSocketClient", "ddzxSocketClient:recv(10000) wait timeout, time:", os.time())
  511. else
  512. --TODO:处理收到的数据data
  513. log.info("longLinkSocketTask.ddzxSocketClient", "receive server message, time: ", os.time(), ", message:", ddzx_data:toHex())
  514. --解析数据并响应结果
  515. local res,parseData = parseRespPacket(ddzx_data)
  516. if not res then
  517. log.info("longLinkSocketTask.ddzxSocketClient","parseRespPacket failed!!")
  518. else
  519. log.info("longLinkSocketTask.ddzxSocketClient","publish ON_MESSAGE_DDZX_AUTH_SUCCESS,task finish,wait ON_MESSAGE_DO_DDZX_TASK ...")
  520. sys.publish("ON_MESSAGE_DDZX_AUTH_SUCCESS",parseData)
  521. --进入阻塞状态,等待下一次连接调度中心的任务
  522. while true do
  523. local result,msg = sys.waitUntil("ON_MESSAGE_DO_DDZX_TASK", 3600*1000)
  524. if result and msg ~="CLOSED" then
  525. log.info("longLinkSocketTask.ddzxSocketClient","receive ON_MESSAGE_DO_DDZX_TASK message, msg:", msg)
  526. break
  527. else
  528. log.info("longLinkSocketTask.ddzxSocketClient","wait ON_MESSAGE_DO_DDZX_TASK timeout")
  529. end
  530. end
  531. end
  532. end
  533. else
  534. retryConnectCnt = retryConnectCnt+1
  535. log.info("longLinkSocketTask.ddzxSocketClient",">>>>>>> socket.send failed")
  536. --sys.wait(5000)
  537. end
  538. end
  539. else
  540. log.info("longLinkSocketTask.ddzxSocketClient","connect fail")
  541. --连接失败
  542. retryConnectCnt = retryConnectCnt+1 --失败次数加一
  543. end
  544. ddzxSocketClient:close() --断开socket连接
  545. if retryConnectCnt>=5 then --失败次数大于五次了
  546. link.shut() --强制断开TCP/UDP连接
  547. retryConnectCnt=0 --失败次数清零
  548. end
  549. sys.wait(5000)
  550. else
  551. retryConnectCnt = 0 --没连上网,失败次数清零
  552. --没连上网
  553. --等待网络环境准备就绪,超时时间是5分钟
  554. sys.waitUntil("IP_READY_IND",300000)
  555. --等完了还没连上?
  556. if not socket.isReady() then
  557. --进入飞行模式,20秒之后,退出飞行模式
  558. net.switchFly(true)
  559. sys.wait(20000)
  560. net.switchFly(false)
  561. end
  562. end
  563. end
  564. end)
  565. sys.subscribe("ON_MESSAGE_DDZX_AUTH_SUCCESS", function()
  566. qzjFrameSn = 0x0001
  567. local res, qzjConnPacket = createPacket(qzjFrameSn,0x01,0x0003,0x00000000,"")
  568. if res then
  569. insertMsg(qzjConnPacket)
  570. else
  571. log.info("longLinkSocketTask.qzjLogin","createPacket failed!!")
  572. end
  573. end)
  574. --设备发送心跳程序
  575. sys.taskInit(
  576. function()
  577. while true do
  578. log.info("longLinkSocketTask.qzjTask","wait MESSAGE_TYPE_START_HEARTBEAT message ...")
  579. local res,data = sys.waitUntil("MESSAGE_TYPE_START_HEARTBEAT", 3600*1000)
  580. if res then
  581. log.info("longLinkSocketTask.qzjTask","receive MESSAGE_TYPE_START_HEARTBEAT message")
  582. break
  583. else
  584. log.info("longLinkSocketTask.qzjTask","wait MESSAGE_TYPE_START_HEARTBEAT timeout")
  585. end
  586. end
  587. sys.wait(120000)
  588. while true do
  589. if socket.isReady() then --连上网再开始运行
  590. local timeBin = getFormatTimeBin()
  591. local content = string.char(0x05)..string.char(0x00)..timeBin..hex2bin("010048000100010002")
  592. qzjFrameSn = qzjFrameSn + 1
  593. local res, qzjHeartbeatPacket = createPacket(qzjFrameSn,0x1,0x0007,0x00000000,content)
  594. if res then
  595. insertMsg(qzjHeartbeatPacket)
  596. else
  597. log.error("longLinkSocketTask.inMsgProcess","createPacket qzjHeartbeatPacket failed!!")
  598. end
  599. sys.wait(120000) --等待一段时间发下次心跳
  600. else --没连上网别忘了延时!不然会陷入while true死循环,导致模块无法运行其他代码
  601. sys.wait(1000) --等待1秒
  602. end
  603. end
  604. end)
  605. -- 解析并上报rfid数据
  606. sys.taskInit(function()
  607. --等心跳开启时,再开始上报rfid数据
  608. while true do
  609. log.info("longLinkSocketTask.parse_packet","wait MESSAGE_TYPE_START_HEARTBEAT message ...")
  610. local res,data = sys.waitUntil("MESSAGE_TYPE_START_HEARTBEAT", 3600*1000)
  611. if res then
  612. log.info("longLinkSocketTask.parse_packet","receive MESSAGE_TYPE_START_HEARTBEAT message")
  613. break
  614. else
  615. log.info("longLinkSocketTask.parse_packet","wait MESSAGE_TYPE_START_HEARTBEAT timeout")
  616. end
  617. end
  618. local rfidFrameSn = 0
  619. while true do
  620. --log.info("socketTask.pub_msg",">>>>>>>>>>> waitUntil pub_packet_data_tiandiren ")
  621. --阻塞监听监听串口接收数据
  622. local cur_time = os.time()
  623. local result, packet_data = sys.waitUntil("pub_packet_data_tiandiren",300*1000)
  624. if result then
  625. --log.info("longLinkSocketTask.pub_msg",">>>>>>>>> recv pub_packet_data_tiandiren, times(s):", os.time()-cur_time, json.encode(packet_data))
  626. cur_time = os.time()
  627. local tmp_bin = ""
  628. for key, rfid in pairs(packet_data["buf"]) do
  629. if type(rfid) == "table" then
  630. if not rfid.time then
  631. log.info("longLinkSocketTask.parse_packet",">>>>>>>>> rfid.time empty! ", type(rfid))
  632. for k, v in pairs(rfid) do
  633. log.info("longLinkSocketTask.parse_packet",">>>>>>>>> rfid", "k:", k, ", v:", v)
  634. end
  635. else
  636. local timeBin = getFormatTimeBin(rfid.time)
  637. local content = string.char(0x03)..string.char(0xf0)..timeBin..hex2bin("008004")..hex2bin(key)..hex2bin("01ffff000100")
  638. rfidFrameSn = rfidFrameSn + 1
  639. local res, qzjRfidPacket = createPacket(rfidFrameSn,0x1,0x0007,0x07008004,content)
  640. if res then
  641. insertMsg(qzjRfidPacket)
  642. else
  643. log.error("longLinkSocketTask.parse_packet","createPacket qzjRfidPacket failed!!")
  644. end
  645. end
  646. else
  647. log.info("longLinkSocketTask.parse_packet",">>>>>>>>> rfid error! key = ", key)
  648. end
  649. end
  650. else
  651. log.info("longLinkSocketTask.parse_packet",">>>>>>>>> wait pub_packet_data_tiandiren timeout")
  652. --sys.wait(1000)
  653. end
  654. end
  655. end)
  656. -- 监听并上报rfid数据
  657. sys.taskInit(function()
  658. --等心跳开启时,再开始上报rfid数据
  659. while true do
  660. log.info("longLinkSocketTask.parse_packet","wait MESSAGE_TYPE_START_HEARTBEAT message ...")
  661. local res,data = sys.waitUntil("MESSAGE_TYPE_START_HEARTBEAT", 3600*1000)
  662. if res then
  663. log.info("longLinkSocketTask.parse_packet","receive MESSAGE_TYPE_START_HEARTBEAT message")
  664. break
  665. else
  666. log.info("longLinkSocketTask.parse_packet","wait MESSAGE_TYPE_START_HEARTBEAT timeout")
  667. end
  668. end
  669. local rfidFrameSn = 0
  670. while true do
  671. --log.info("socketTask.pub_msg",">>>>>>>>>>> waitUntil pub_packet_data_tiandiren_rfid_info ")
  672. --阻塞监听监听rfid接收数据
  673. local cur_time = os.time()
  674. local result, rfid = sys.waitUntil("pub_packet_data_tiandiren_rfid_info",300*1000)
  675. if result then
  676. --log.info("longLinkSocketTask.upload_tiandiren_rfid_info",">>>>>>>>> recv pub_packet_data_tiandiren_rfid_info, times(s):", os.time()-cur_time, json.encode(rfid))
  677. if type(rfid) == "table" then
  678. if not rfid.time then
  679. log.info("longLinkSocketTask.upload_tiandiren_rfid_info",">>>>>>>>> rfid.time empty! ")
  680. for k, v in pairs(rfid) do
  681. log.info("longLinkSocketTask.upload_tiandiren_rfid_info",">>>>>>>>> rfid", "k:", k, ", v:", v)
  682. end
  683. elseif not rfid.id then
  684. log.info("longLinkSocketTask.upload_tiandiren_rfid_info",">>>>>>>>> rfid.id empty! ")
  685. else
  686. log.info("longLinkSocketTask.upload_tiandiren_rfid_info","rfid.id:",rfid.id,",rfid.time:",rfid.time,",rfid.id_dec:",tonumber(rfid.id, 16))
  687. local timeBin = getFormatTimeBin(rfid.time)
  688. local content = string.char(0x03)..string.char(0xf0)..timeBin..hex2bin("008004")..hex2bin(rfid.id)..hex2bin("01ffff000100")
  689. rfidFrameSn = rfidFrameSn + 1
  690. local res, qzjRfidPacket = createPacket(rfidFrameSn,0x1,0x0007,0x07008004,content)
  691. if res then
  692. insertMsg(qzjRfidPacket)
  693. else
  694. log.error("longLinkSocketTask.upload_tiandiren_rfid_info","createPacket qzjRfidPacket failed!!")
  695. end
  696. end
  697. else
  698. log.info("longLinkSocketTask.upload_tiandiren_rfid_info",">>>>>>>>> rfid error! key = ", key)
  699. end
  700. else
  701. log.info("longLinkSocketTask.upload_tiandiren_rfid_info",">>>>>>>>> wait pub_packet_data_tiandiren timeout")
  702. --sys.wait(1000)
  703. end
  704. end
  705. end)