socketCh395.lua 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. --- 模块功能:数据链路激活、SOCKET管理(创建、连接、数据收发、状态维护)
  2. -- @module socket
  3. -- @author openLuat
  4. -- @license MIT
  5. -- @copyright openLuat
  6. -- @release 2017.9.25
  7. require "link"
  8. require "utils"
  9. module(..., package.seeall)
  10. local sockets = {}
  11. -- 单次发送数据最大值
  12. local SENDSIZE = 1024
  13. -- 缓冲区最大下标
  14. local INDEX_MAX = 2048
  15. -- 是否有socket正处在链接
  16. local socketsConnected = 0
  17. -- CH395配置信息
  18. local configurationCh395 = nil
  19. -- 以太网模块供电设置函数
  20. local powerCbFnc = nil
  21. -- 获取芯片版本(使用0x44以上版本)
  22. local ch395Version = nil
  23. -- 芯片MAC地址
  24. local CH395MAC = nil
  25. local resvnum = 0
  26. TCPCLIENT = 0
  27. UDPCLIENT = 1
  28. RAW = 3
  29. TCPSERVER = 4
  30. local function str2short(str)
  31. local f, n = pack.unpack(str, '<H')
  32. return f and f > 0 and n or 0
  33. end
  34. local function shorts(n)
  35. return pack.pack('<H', n)
  36. end
  37. local function sub_z(data, num)
  38. return string.sub(data, num + 1, data:len())
  39. end
  40. local function ip2num(str)
  41. if (not (str and #str == 4)) then
  42. return ''
  43. end
  44. local t = {pack.unpack(str, 'bbbb')}
  45. return string.format('%d.%d.%d.%d', t[2], t[3], t[4], t[5])
  46. end
  47. local function iptostr(ip)
  48. local d1, d2, d3, d4 = string.match(ip, '(%d+)%.(%d+)%.(%d+).(%d+)')
  49. return {string.sub(shorts(d1), 1, 1), string.sub(shorts(d2), 1, 1), string.sub(shorts(d3), 1, 1),
  50. string.sub(shorts(d4), 1, 1)}
  51. end
  52. ------------
  53. local function spiSend(id, data)
  54. --log.info('send SPI data:', data:toHex())
  55. local dataSpi
  56. if configurationCh395['spiCs'] then
  57. local setSpi_CS = pins.setup(configurationCh395['spiCs'], 0)
  58. dataSpi = spi.send_recv(id, data)
  59. setSpi_CS(1)
  60. else
  61. dataSpi = spi.send_recv(id, data)
  62. end
  63. -- log.info('recv SPI data', dataSpi:toHex())
  64. return dataSpi
  65. end
  66. -- 命令执行查询
  67. local function inquire2c(time)
  68. local num = 0
  69. while true do
  70. sys.wait(time or 10)
  71. local data = string.sub(spiSend(spi.SPI_1, '\x2c\xff'), 2, 2)
  72. if data ~= '\x10' then
  73. return data
  74. end
  75. num = num + 1
  76. if num > 100 then
  77. return data
  78. end
  79. end
  80. end
  81. -- 获取MAC地址
  82. function getMac()
  83. return CH395MAC
  84. end
  85. -- 本地端口,初始化默认端口
  86. local socketLocalPort = 0
  87. -- 动态获取本地端口号,每次获取累加
  88. local function socketTcpClientPort()
  89. -- socketLocalPort = socketLocalPort + 123
  90. -- if socketLocalPort > 65535 then
  91. -- socketLocalPort = 1000
  92. -- end
  93. -- return socketLocalPort
  94. local time = string.sub(rtos.tick(), 3)
  95. if socketLocalPort < 8 then
  96. socketLocalPort = socketLocalPort + 1
  97. else
  98. socketLocalPort = 0
  99. end
  100. return (socketLocalPort + time) * 5
  101. end
  102. -- 初始化socket
  103. local function SocketClientInit(type, socketId, soalAddress, soalPort, localPort)
  104. localPort = localPort or socketTcpClientPort()
  105. local addr = iptostr(soalAddress)
  106. -- 设置协议类型
  107. if type == TCPCLIENT then
  108. spiSend(spi.SPI_1, string.char(0x34, socketId, 3))
  109. elseif type == UDPCLIENT then
  110. spiSend(spi.SPI_1, string.char(0x34, socketId, 2))
  111. end
  112. -- 设置本地端口
  113. spiSend(spi.SPI_1, '\x33' .. string.char(socketId) .. shorts(tonumber(localPort)))
  114. -- 设置目的端口号
  115. spiSend(spi.SPI_1, '\x32' .. string.char(socketId) .. shorts(tonumber(soalPort)))
  116. -- 设置目的地址
  117. spiSend(spi.SPI_1, string.char(0x31, socketId) .. addr[1] .. addr[2] .. addr[3] .. addr[4])
  118. -- 打开socket
  119. spiSend(spi.SPI_1, string.char(0x35, socketId))
  120. -- 查询执行状态
  121. local state = inquire2c(50)
  122. log.info('socketCh395', 'open socket' .. socketId .. state:toHex())
  123. if state ~= '\x00' or type == UDPCLIENT then
  124. if type ~= UDPCLIENT then
  125. log.info('socketCh395', 'open socket err', state:toHex())
  126. else
  127. sys.timerStart(function()
  128. sys.publish('SOCK_CONN_CNF', {
  129. ['socket_index'] = socketId,
  130. ['id'] = 34,
  131. ['result'] = 0
  132. })
  133. end, 200)
  134. end
  135. return state
  136. end
  137. spiSend(spi.SPI_1, string.char(0x37, socketId))
  138. state = inquire2c()
  139. if state == '\x00' then
  140. sys.publish('SOCK_CONN_CNF', {
  141. ['socket_index'] = socketId,
  142. ['id'] = 34,
  143. ['result'] = 0
  144. })
  145. else
  146. log.info('socketCh395', 'open socket' .. socketId, state:toHex())
  147. end
  148. return state
  149. end
  150. -- 配置8路socket收发缓存
  151. local function socketBufferConfig()
  152. -- 只有硬件版本大于47才有4-7路
  153. local b = 0
  154. for i = 0, 7 do
  155. spiSend(spi.SPI_1, string.char(0x52, i, b, 4))
  156. b = b + 4
  157. spiSend(spi.SPI_1, string.char(0x53, i, b, 2))
  158. b = b + 2
  159. sys.wait(500)
  160. end
  161. end
  162. -- 关闭套接字连接
  163. local function sockectCh395Close(socketId)
  164. if sockets[socketId] == nil or sockets[socketId] == true then
  165. log.info('socketCh395', 'close err, not socket ' .. socketId)
  166. end
  167. if sockets[socketId] == true or sockets[socketId].protocol == 'TCPSERVERCLIENT' then
  168. -- server客户端断开连接
  169. spiSend(spi.SPI_1, string.char(0x38, socketId))
  170. local state = inquire2c()
  171. log.info('socketCh395', 'close server socket ' .. socketId)
  172. sys.publish('SOCK_CLOSE_CNF', {
  173. ['socket_index'] = socketId,
  174. ['id'] = 33,
  175. ['result'] = 0
  176. })
  177. elseif sockets[socketId].protocol == 'TCPSERVER' then
  178. -- server关闭,断开连接,关闭所有server通道
  179. log.info('socketCh395', 'close server ' .. socketId)
  180. for i, v in ipairs(sockets) do
  181. if sockets[i] ~= true and not sockets[i] and sockets[i].protocol == 'TCPSERVERCLIENT' then
  182. local id = sockets[i].id
  183. spiSend(spi.SPI_1, string.char(0x38, sockets[i].id))
  184. spiSend(spi.SPI_1, string.char(0x3D, socketId))
  185. sockets[i] = nil
  186. log.info('socketCh395', 'close server socket ' .. id)
  187. end
  188. end
  189. spiSend(spi.SPI_1, string.char(0x3D, socketId))
  190. log.info('socketCh395', 'close server ' .. socketId)
  191. local state = inquire2c()
  192. sys.publish('SOCK_CLOSE_CNF', {
  193. ['socket_index'] = socketId,
  194. ['id'] = 33,
  195. ['result'] = 0
  196. })
  197. else
  198. spiSend(spi.SPI_1, string.char(0x3D, socketId))
  199. local stateClose = inquire2c(10)
  200. log.info('sockectCh395', 'close socket' .. socketId .. 'true' .. stateClose:toHex())
  201. sys.publish('SOCK_CLOSE_CNF', {
  202. ['socket_index'] = socketId,
  203. ['id'] = 33,
  204. ['result'] = 0
  205. })
  206. end
  207. end
  208. local function ipError()
  209. if link.isReady() and link.getNetwork() == link.CH395 then
  210. link.setReady(link.CH395, false)
  211. sys.publish('IP_ERROR_IND')
  212. log.info('socketCh395', 'IP_ERROR_IND')
  213. end
  214. end
  215. -- 处理中断
  216. local function interruptProcess()
  217. local intAll = string.sub(spiSend(spi.SPI_1, '\x19\xff\xff'), 2, -1)
  218. -- log.info('INT30', intAll:toHex())
  219. intAll = str2short(intAll)
  220. if intAll == 0 or intAll == 65535 then
  221. return
  222. end
  223. -- 处理PHY中断
  224. if bit.isset(intAll, 2) then
  225. local statePhy = string.sub(spiSend(spi.SPI_1, '\x26\xff'), 2, -1)
  226. if statePhy == '\x01' then
  227. log.info('socketCh395', 'phy false')
  228. ipError()
  229. elseif statePhy == '\x08' then
  230. log.info('socketCh395', 'phy true')
  231. end
  232. end
  233. -- 处理DHCP中断
  234. if bit.isset(intAll, 3) then
  235. -- DHCP中断
  236. local stateDhcp = string.sub(spiSend(spi.SPI_1, '\x42\xff'), 2, -1)
  237. if stateDhcp == '\x00' then
  238. log.info('socketCh395', 'DHCP true')
  239. elseif stateDhcp == '\x01' then
  240. log.info('socketCh395', 'DHCP false')
  241. ipError()
  242. end
  243. end
  244. -- 处理不可达中断
  245. if bit.isset(intAll, 0) then
  246. -- 读取不可达信息?
  247. log.info('socketCh395', 'Unreachable interrupt')
  248. -- getUnreachIpport()
  249. end
  250. -- 处理IP冲突中断
  251. if bit.isset(intAll, 1) then
  252. log.info("IP", 'IP conflict')
  253. -- 建议重新修改本地IP,并初始化芯片(未加)
  254. end
  255. -- socket0-7中断
  256. local socketIntId = {}
  257. for i = 4, 11 do
  258. if bit.isset(intAll, i) then
  259. table.insert(socketIntId, (i - 4))
  260. end
  261. end
  262. local socketCloss = {}
  263. -- 逐个socket查询中断并处理
  264. for q = 1, #socketIntId do
  265. local socketState = string.sub(spiSend(spi.SPI_1, string.char(0x30, socketIntId[q], 0xff, 0xff)), 3, -1)
  266. -- log.info('INT19:' .. socketIntId[q], socketState:toHex())
  267. socketState = str2short(socketState)
  268. -- TCP连接
  269. if bit.isset(socketState, 3) then
  270. -- sockets[socketIntId[q]].connected = true
  271. if sockets[socketIntId[q]] == true then
  272. local data = string.sub(spiSend(spi.SPI_1,
  273. string.char(0x2d, socketIntId[q], 0xff, 0xff, 0xff, 0xff, 0xff, 0xff)), 3, 8)
  274. -- server
  275. local socketData = {
  276. id = socketIntId[q],
  277. ip = ip2num(string.sub(data, 1, 4)),
  278. port = str2short(string.sub(data, 5, 6))
  279. }
  280. sys.publish('tcpServer', socketData)
  281. else
  282. sys.publish('SOCK_CONN_CNF', {
  283. ['socket_index'] = socketIntId[q],
  284. ['id'] = 34,
  285. ['result'] = 0
  286. })
  287. end
  288. end
  289. -- 接收缓冲区非空
  290. if bit.isset(socketState, 2) then
  291. local data_leng
  292. local data
  293. data_leng = string.sub(spiSend(spi.SPI_1, string.char(0x3b, socketIntId[q], 0xff, 0xff)), 3, -1)
  294. -- if data_leng == '\x00\x00' then
  295. -- break
  296. -- end
  297. data = string.sub(spiSend(spi.SPI_1, string.char(0x3c, socketIntId[q]) .. data_leng ..
  298. string.rep('\xff', str2short(data_leng))), 5, -1)
  299. sys.timerStart(function()
  300. sys.publish('MSG_SOCK_RECV_IND', {
  301. ['socket_index'] = socketIntId[q],
  302. ['id'] = 31,
  303. ['result'] = 0,
  304. ['recv_len'] = str2short(data_leng),
  305. ['recv_data'] = data
  306. })
  307. end, 10)
  308. -- data_leng = string.sub(spiSend(spi.SPI_1, string.char(0x3b, socketIntId[q], 0xff, 0xff)), 3, -1)
  309. -- data = string.sub(spiSend(spi.SPI_1, string.char(0x3c, socketIntId[q]) .. data_leng ..
  310. -- string.rep('\xff', str2short(data_leng))), 5, -1)
  311. -- sys.publish('MSG_SOCK_RECV_IND', {
  312. -- ['socket_index'] = socketIntId[q],
  313. -- ['id'] = 31,
  314. -- ['result'] = 0,
  315. -- ['recv_len'] = str2short(data_leng),
  316. -- ['recv_data'] = data
  317. -- })
  318. end
  319. -- 发送缓冲区空闲
  320. if bit.isset(socketState, 0) then
  321. if sockets[socketIntId[q]] and sockets[socketIntId[q]] ~= true then
  322. sockets[socketIntId[q]].sendstate = true
  323. else
  324. log.info('socketCh395', 'sendstate err:' .. socketIntId[q])
  325. end
  326. end
  327. -- 发送成功
  328. if bit.isset(socketState, 1) then
  329. sys.publish('SOCK_SEND_CNF', {
  330. ['socket_index'] = socketIntId[q],
  331. ['id'] = 32,
  332. ['result'] = 0
  333. })
  334. end
  335. -- TCP断开
  336. if bit.isset(socketState, 4) then
  337. table.insert(socketCloss, {
  338. ['socket_index'] = socketIntId[q],
  339. ['id'] = 33,
  340. ['result'] = 0
  341. })
  342. end
  343. -- 超时
  344. if bit.isset(socketState, 6) then
  345. -- 超时处理,重新开启重新连接(未加)
  346. -- 打开socket
  347. log.info('socketCh395', 'socket conn timeout' .. socketIntId[q], sockets[socketIntId[q]], socketIntId[q])
  348. -- if not sockets[socketIntId[q]] then
  349. -- sockectCh395Close(socketIntId[q])
  350. -- elseif sockets[socketIntId[q]] ~= 0 then
  351. -- local ty = sockets[socketIntId[q]].protocol
  352. -- local soalAddress = sockets[socketIntId[q]].address
  353. -- local soalPort = sockets[socketIntId[q]].port
  354. -- local localPort = sockets[socketIntId[q]].localPort
  355. -- sockectCh395Close(socketIntId[q])
  356. -- if ty == 'TCP' then
  357. -- ty = TCPCLIENT
  358. -- elseif ty == 'UDP' then
  359. -- ty = UDPCLIENT
  360. -- end
  361. -- SocketClientInit(ty, socketIntId[q], soalAddress, soalPort, localPort)
  362. -- end
  363. end
  364. end
  365. for i = 0, 7 do
  366. if sockets[i] then
  367. local data_leng
  368. local data
  369. data_leng = string.sub(spiSend(spi.SPI_1, string.char(0x3b, i, 0xff, 0xff)), 3, -1)
  370. if data_leng ~= "\x00\x00" then
  371. data = string.sub(spiSend(spi.SPI_1,
  372. string.char(0x3c, i) .. data_leng .. string.rep('\xff', str2short(data_leng))), 5, -1)
  373. sys.timerStart(function()
  374. sys.publish('MSG_SOCK_RECV_IND', {
  375. ['socket_index'] = i,
  376. ['id'] = 31,
  377. ['result'] = 0,
  378. ['recv_len'] = str2short(data_leng),
  379. ['recv_data'] = data
  380. })
  381. end, 10)
  382. end
  383. end
  384. end
  385. for w = 1, #socketCloss do
  386. local data =
  387. string.sub(spiSend(spi.SPI_1, string.char(0x2F, socketCloss[w]['socket_index'], 0xff, 0xff)), 3, -1)
  388. local data1 = string.sub(data, 1, 1)
  389. local data2 = string.sub(data, 2, 2)
  390. -- if data1 == '\x00' then
  391. if not sockets[socketCloss[w]['socket_index']] or sockets[socketCloss[w]['socket_index']] == true then
  392. sys.timerStart(function(...)
  393. log.info('socketCh395', 'socket ' .. socketCloss[w]['socket_index'] .. 'state' .. data:toHex())
  394. sys.publish('MSG_SOCK_CLOSE_IND', socketCloss[w])
  395. log.info('socketCh395', 'Disconnection socket ', socketCloss[w]['socket_index'])
  396. end, 200)
  397. elseif sockets[socketCloss[w]['socket_index']].protocol == 'TCPSERVERCLIENT' then
  398. -- sockets[socketCloss[w]['socket_index']]=true
  399. sys.timerStart(function(...)
  400. log.info('socketCh395', 'socket ' .. socketCloss[w]['socket_index'] .. 'state' .. data:toHex())
  401. sys.publish('MSG_SOCK_CLOSE_IND', socketCloss[w])
  402. log.info('socketCh395', 'Disconnection socket ', socketCloss[w]['socket_index'])
  403. end, 200)
  404. else
  405. sys.timerStart(function(...)
  406. log.info('socketCh395', 'socket ' .. socketCloss[w]['socket_index'] .. 'state' .. data:toHex())
  407. sys.publish('MSG_SOCK_CLOSE_IND', socketCloss[w])
  408. log.info('socketCh395', 'Disconnection socket ', socketCloss[w]['socket_index'])
  409. end, 200)
  410. end
  411. -- end
  412. end
  413. sys.wait(10)
  414. end
  415. local number = 0
  416. sys.taskInit(function()
  417. while true do
  418. if number > 0 or sys.waitUntil("interruptProcess") then
  419. interruptProcess()
  420. number = number - 1
  421. -- sys.wait(5)
  422. end
  423. end
  424. end)
  425. -- 配置中断检测
  426. local function setInt(state)
  427. if state then
  428. pio.pin.setdebounce(5)
  429. pins.setup(configurationCh395['intPin'], function(a)
  430. if a == 2 then
  431. number = number + 2
  432. sys.publish("interruptProcess")
  433. else
  434. end
  435. end)
  436. pio.pin.setdebounce(20)
  437. else
  438. pins.close(configurationCh395['intPin'])
  439. end
  440. end
  441. --- 初始化CG395模块
  442. -- @table para,取值如下:
  443. -- para为table类型,表示以太网的配置参数,参数结构如下:
  444. -- {
  445. -- mode = 1, --1表示客户端;2表示服务器;默认为1
  446. -- intPin = pio.P0_22, --以太网芯片中断通知引脚
  447. -- rstPin = pio.P0_23, --复位以太网芯片引脚
  448. -- clientNum = 6, -- server可连路数
  449. -- spiCs = pio.P0_23, --SPI片选
  450. -- CH395MAC = "84C2E4A82950", --MAC地址
  451. -- localAddr = "192.168.1.112", --本机的地址
  452. -- localPort = 1888, --server本机的端口
  453. -- spiCs=pio.P0_7, --spi片选
  454. -- localGateway = "192.168.1.1", --本机的网关地址
  455. -- func=function(id, msg, dat)end, --中断处理函数,处理server中断事件
  456. -- powerFunc=function(state) end --控制以太网模块的供电开关函数,ret为true开启供电,false关闭供电
  457. -- spi = {spi.SPI_1,0,0,8,800000}, --SPI通道参数,id,cpha,cpol,dataBits,clock,默认spi.SPI_1,0,0,8,800000
  458. -- }
  459. -- @return result 数据接收结果
  460. -- true表示成功
  461. -- false表示失败
  462. -- @usage
  463. -- socketCh395.open(para)
  464. function open(para)
  465. configurationCh395 = para
  466. powerCbFnc = nil or para['powerFunc']
  467. -- 供电及其他前置条件
  468. if powerCbFnc then
  469. powerCbFnc(true)
  470. end
  471. -- 复位芯片
  472. spiSend(spi.SPI_1, '\x05')
  473. -- 开启SPI
  474. if not spi.setup(para['spi'][1], para['spi'][2], para['spi'][3], para['spi'][4], para['spi'][5], 1) == 1 then
  475. log.info('socketCh395', 'open spi err')
  476. return ''
  477. end
  478. -- 设置中断
  479. setInt(true)
  480. -- 芯片进入SPI模式
  481. local setGpioFnc_RSTI = pins.setup(para['rstPin'], 0)
  482. setGpioFnc_RSTI(0)
  483. sys.wait(100)
  484. setGpioFnc_RSTI(1)
  485. sys.wait(200)
  486. -- 测试是否成功建立通讯
  487. local state06 = string.sub(spiSend(spi.SPI_1, '\x06\x55\xff'), 3, 3)
  488. state06 = state06 == '\xaa'
  489. log.info('CH395 state', state06)
  490. if not state06 then
  491. log.info('socketCh395', 'err cannot work')
  492. return ''
  493. end
  494. -- server多连接设置
  495. if para['mode'] == 2 then
  496. spiSend(spi.SPI_1, '\x55\x02')
  497. local stateInit = inquire2c(50)
  498. if stateInit ~= '\x00' then
  499. log.info('open server')
  500. else
  501. log.info('open server err', stateInit:toHex())
  502. end
  503. end
  504. -- 获取芯片版本
  505. ch395Version = string.sub(spiSend(spi.SPI_1, '\x01\xff'), 2, 2)
  506. -- 配置芯片信息
  507. if para['localAddr'] and para['localGateway'] then
  508. -- 配置本地信息
  509. local gateway = iptostr(para['localGateway'])
  510. local addr = iptostr(para['localAddr'])
  511. spiSend(spi.SPI_1, '\x22' .. addr[1] .. addr[2] .. addr[3] .. addr[4])
  512. spiSend(spi.SPI_1, '\x23' .. gateway[1] .. gateway[2] .. gateway[3] .. gateway[4])
  513. if para['localSubnetMas'] then
  514. local subnetMas = iptostr(para['localSubnetMas'])
  515. spiSend(spi.SPI_1, '\x24' .. subnetMas[1] .. subnetMas[2] .. subnetMas[3] .. subnetMas[4])
  516. end
  517. end
  518. -- 设置收发缓存(默认8路)
  519. socketBufferConfig()
  520. -- 模块初始化
  521. spiSend(spi.SPI_1, '\x27')
  522. local stateInit = inquire2c(50)
  523. if stateInit ~= '\x00' then
  524. log.info('socketCh395', 'ch395 INIT err' .. stateInit:toHex())
  525. return ''
  526. end
  527. -- 设置MAC地址
  528. if para['CH395MAC'] and string.len(para['CH395MAC']) == 12 then
  529. spiSend(spi.SPI_1, '\x21' .. string.fromHex(para['CH395MAC']))
  530. sys.wait(200)
  531. end
  532. -- 获取芯片MAC
  533. CH395MAC = string.sub(spiSend(spi.SPI_1, string.fromHex('40FFFFFFFFFFFF2cff')), 2, 7)
  534. if CH395MAC == string.char(0, 0, 0, 0, 0, 0) then
  535. CH395MAC = nil
  536. end
  537. -- DHCP
  538. if not (para['localAddr'] and para['localGateway']) then
  539. spiSend(spi.SPI_1, '\x41\x01')
  540. local stateDhcp = inquire2c(30)
  541. if stateDhcp ~= '\x00' then
  542. log.info('socketCh395', 'ch395 INIT err' .. stateDhcp:toHex())
  543. return ''
  544. end
  545. end
  546. -- 获取本地IP
  547. for q = 1, 20 do
  548. sys.wait(500)
  549. local dataIp = string.sub(spiSend(spi.SPI_1, string.fromHex('43ffffffffffffffffffffffffffffffffffffffff')), 2,
  550. -1)
  551. if link.getNetwork() == link.CH395 and string.sub(dataIp, 1, 4) ~= '\xff\xff\xff\xff' and
  552. string.sub(dataIp, 1, 4) ~= '\x00\x00\x00\x00' then
  553. local ch395Ip = ip2num(string.sub(dataIp, 1, 4))
  554. log.info('ip', ch395Ip)
  555. link.setReady(link.CH395, true)
  556. sys.publish('IP_READY_IND')
  557. return ch395Ip
  558. end
  559. end
  560. return ''
  561. end
  562. --- 开关模块
  563. function close()
  564. link.setReady(link.CH395, false)
  565. sys.publish('IP_ERROR_IND')
  566. -- 关闭所有socket
  567. for i = 0, 7 do
  568. spiSend(spi.SPI_1, string.char(0x3D, i))
  569. sockets[i] = nil
  570. end
  571. -- 关闭中断检测
  572. setInt(false)
  573. -- 关闭SPI
  574. if not spi.close(configurationCh395['spi'][1]) == 1 then
  575. log.info('socketCh395 close spi err', configurationCh395['spi'][1], configurationCh395['spi'][2],
  576. configurationCh395['spi'][3], configurationCh395['spi'][4], configurationCh395['spi'][5], 1)
  577. return false
  578. end
  579. -- 关闭模块
  580. if powerCbFnc then
  581. powerCbFnc(false)
  582. end
  583. return true
  584. end
  585. ---建立套接字连接
  586. local function sockectCh395Conn(type, addr, port, lcoalPort, data)
  587. local socketId = nil
  588. for i = 0, 7 do
  589. if not sockets[i] then
  590. socketId = i
  591. data.id=i
  592. sockets[i] = data
  593. break
  594. end
  595. if i == 7 then
  596. log.info('socketCh395', 'No socket available ')
  597. return nil
  598. end
  599. end
  600. if type == TCPCLIENT or type == UDPCLIENT then
  601. local tcpClientState = SocketClientInit(type, socketId, addr, port, lcoalPort)
  602. if tcpClientState == '\x00' then
  603. return socketId
  604. else
  605. spiSend(spi.SPI_1, string.char(0x3D, socketId))
  606. local stateClose = inquire2c(50)
  607. if stateClose == '\x00' then
  608. log.info('sockectCh395', 'close socket' .. socketId .. 'true')
  609. end
  610. sockets[socketId] = nil
  611. return nil
  612. end
  613. elseif type == TCPSERVER then
  614. end
  615. end
  616. -- 发送数据
  617. local function sockectCh395Send(socketId, data)
  618. for i = 1, 10 do
  619. if sockets[socketId] and sockets[socketId] ~= true and sockets[socketId].sendstate then
  620. spiSend(spi.SPI_1, '\x39' .. string.char(socketId) .. shorts(#data) .. data)
  621. local state = inquire2c(50)
  622. if state == '\x00' then
  623. sys.publish('SOCK_SEND_CNF', {
  624. ['socket_index'] = socketId,
  625. ['id'] = 32,
  626. ['result'] = 0
  627. })
  628. else
  629. sys.publish('SOCK_SEND_CNF', {
  630. ['socket_index'] = socketId,
  631. ['id'] = 32,
  632. ['result'] = 1
  633. })
  634. end
  635. log.info('socketCh395', socketId .. 'send state' .. state:toHex())
  636. break
  637. elseif not sockets[socketId] or sockets[socketId] == true then
  638. -- log.info('socketCh395', 'send err, not socket ' .. socketId)
  639. else
  640. sys.wait(100)
  641. end
  642. end
  643. end
  644. -- 接收数据
  645. local function sockectCh395Recv(socketId, buffLen)
  646. local data_leng = string.sub(spiSend(spi.SPI_1, string.char(0x3b, socketId, 0xff, 0xff)), 3, -1)
  647. local data = string.sub(spiSend(spi.SPI_1, string.char(0x3c, socketId) .. data_leng ..
  648. string.rep('\xff', str2short(data_leng))), 5, -1)
  649. return data
  650. end
  651. -- table 深拷贝
  652. local function clone(tb)
  653. local ret = {}
  654. for k, v in pairs(tb) do
  655. ret[k] = type(v) == "table" and clone(v) or v
  656. end
  657. return ret
  658. end
  659. -- 创建server
  660. local function initServer(port, num, data)
  661. if num > 7 then
  662. return
  663. end
  664. local dd = true
  665. local serverTable = {}
  666. local serverid = nil
  667. for i = 0, 7 do
  668. if not sockets[i] then
  669. table.insert(serverTable, i)
  670. if dd then
  671. sockets[i] = data
  672. dd = false
  673. else
  674. sockets[i] = clone(data)
  675. end
  676. if #serverTable == num + 1 then
  677. break
  678. end
  679. end
  680. if i == 7 then
  681. log.info('socketCh395', 'No socket available ')
  682. for q = 1, #serverTable do
  683. sockets[serverTable[q]] = nil
  684. end
  685. return nil
  686. end
  687. end
  688. for i = 1, #serverTable do
  689. spiSend(spi.SPI_1, string.char(0x34, serverTable[i], 3))
  690. spiSend(spi.SPI_1, string.char(0x33, serverTable[i]) .. shorts(port))
  691. if i == 1 then
  692. spiSend(spi.SPI_1, string.char(0x35, serverTable[i]))
  693. sockets[i].id = serverTable[i]
  694. serverid = serverTable[i]
  695. local state = inquire2c(50)
  696. if state == '\x00' then
  697. sockets[serverTable[i]].id = serverTable[i]
  698. sockets[serverTable[i]].protocol = 'TCPSERVER'
  699. else
  700. log.info('socket open err', state:toHex())
  701. log.info('socketCh395', 'socket open err')
  702. end
  703. else
  704. local state = inquire2c(50)
  705. if state == '\x00' then
  706. log.info('socketCh395', 'server open' .. serverTable[i])
  707. sockets[serverTable[i]].protocol = 'TCPSERVERCLIENT' .. serverTable[i]
  708. sockets[serverTable[i]] = true
  709. end
  710. if i == num + 1 then
  711. spiSend(spi.SPI_1, string.char(0x36, serverid))
  712. local state = inquire2c(50)
  713. if state == '\x00' then
  714. return serverid
  715. end
  716. end
  717. end
  718. end
  719. end
  720. ------------------------
  721. local function errorInd(error)
  722. local coSuspended = {}
  723. for _, c in pairs(sockets) do -- IP状态出错时,通知所有已连接的socket
  724. if c ~= true then
  725. c.error = error
  726. -- 不能打开如下3行代码,IP出错时,会通知每个socket,socket会主动close
  727. -- 如果设置了connected=false,则主动close时,直接退出,不会执行close动作,导致core中的socket资源没释放
  728. -- 会引发core中socket耗尽以及socket id重复的问题
  729. -- c.connected = false
  730. -- socketsConnected = c.connected or socketsConnected
  731. -- if error == 'CLOSED' then sys.publish("SOCKET_ACTIVE", socketsConnected) end
  732. if c.co and coroutine.status(c.co) == "suspended" then
  733. -- coroutine.resume(c.co, false)
  734. table.insert(coSuspended, c.co)
  735. end
  736. end
  737. end
  738. for k, v in pairs(coSuspended) do
  739. if v and coroutine.status(v) == "suspended" then
  740. coroutine.resume(v, false, error)
  741. end
  742. end
  743. end
  744. sys.subscribe("IP_ERROR_IND", function()
  745. errorInd('IP_ERROR_IND')
  746. end)
  747. -- sys.subscribe('IP_SHUT_IND', function()errorInd('CLOSED') end)
  748. -- 创建socket函数
  749. local mt = {}
  750. mt.__index = mt
  751. local function socket(protocol, cert, tCoreExtPara)
  752. local ssl = protocol:match("SSL")
  753. local co = coroutine.running()
  754. if not co then
  755. log.warn("socket.socket: socket must be called in coroutine")
  756. return nil
  757. end
  758. -- if protocol == 'TCPSERVER' and type(tCoreExtPara) == 'table' then
  759. -- protocol
  760. -- end
  761. -- 实例的属性参数表
  762. local o = {
  763. id = nil,
  764. protocol = protocol,
  765. tCoreExtPara = tCoreExtPara,
  766. ssl = ssl,
  767. cert = cert,
  768. co = co,
  769. input = {},
  770. output = {},
  771. wait = "",
  772. connected = false,
  773. iSubscribe = false,
  774. subMessage = nil,
  775. isBlock = false,
  776. msg = nil,
  777. rcvProcFnc = nil,
  778. sendstate = true, -- 发送缓冲区状态,true为空闲,可发送数据
  779. localPort = nil -- 本地端口
  780. }
  781. if tCoreExtPara and tCoreExtPara['localport'] and type(tCoreExtPara['localport']) == 'number' then
  782. o.localPort = tCoreExtPara['port']
  783. end
  784. if protocol == 'TCPSERVER' and tCoreExtPara['type']== 'TCPSERVER' then
  785. o.port = configurationCh395["localPort"]
  786. local id = initServer(configurationCh395["localPort"], configurationCh395["clientNum"], setmetatable(o, mt))
  787. if not id then
  788. log.info('socketCh395', 'server socket err')
  789. return
  790. end
  791. elseif protocol == 'TCPSERVER' and tCoreExtPara['type']~= 'TCPSERVER' then
  792. o.address = tCoreExtPara['ip']
  793. o.port = tCoreExtPara['port']
  794. o.id = tCoreExtPara['id']
  795. o.protocol = 'TCPSERVERCLIENT'
  796. sockets[tCoreExtPara['id']] = setmetatable(o, mt)
  797. end
  798. return setmetatable(o, mt)
  799. end
  800. --- 创建基于TCP的socket对象
  801. -- @bool[opt=nil] ssl,是否为ssl连接,true表示是,其余表示否
  802. -- @table[opt=nil] cert,保留参数,ssl功能还未实现。
  803. -- @table[opt=nil] tCoreExtPara, 建立链接扩展参数
  804. -- {
  805. -- id =0, --server socket索引ID
  806. -- ip ="192.168.1.1", --server socket client ip
  807. -- port ="8000", --server socket client port
  808. -- type ="TCPSERVER", --server socket type
  809. -- localport ="8000", -- socket client port
  810. -- }
  811. -- @return client,创建成功返回socket客户端对象;创建失败返回nil
  812. function tcp(ssl, cert, tCoreExtPara)
  813. if tCoreExtPara and tCoreExtPara['type'] == "TCPSERVER" then
  814. return socket("TCPSERVER", nil, tCoreExtPara)
  815. elseif tCoreExtPara and tCoreExtPara['type'] ~= "TCPSERVER" then
  816. return socket("TCPSERVER", nil, tCoreExtPara)
  817. end
  818. return socket("TCP" .. (ssl == true and "SSL" or ""), (ssl == true) and cert or nil, tCoreExtPara)
  819. end
  820. --- 创建基于UDP的socket对象
  821. -- @return client,创建成功返回socket客户端对象;创建失败返回nil
  822. -- @usage c = socket.udp()
  823. function udp(localPort)
  824. return socket("UDP", nil, localPort)
  825. end
  826. --- 连接服务器
  827. -- @string address 服务器地址,支持ip和域名
  828. -- @param port string或者number类型,服务器端口
  829. -- @number[opt=120] timeout 可选参数,连接超时时间,单位秒
  830. -- @return bool result true - 成功,false - 失败
  831. -- @return string ,id '0' -- '8' ,返回通道ID编号
  832. -- @usage
  833. -- socketClient = socket.tcp()
  834. -- socketClient:connect("www.baidu.com","80")
  835. function mt:connect(address, port, timeout)
  836. assert(self.co == coroutine.running(), "socket:connect: coroutine mismatch")
  837. log.info('socketCh395', 'socket data' .. self.protocol, address, port)
  838. if not link.isReady() then
  839. log.info("socket.connect: ip not ready")
  840. return false
  841. end
  842. self.address = address
  843. self.port = port
  844. local tCoreExtPara = self.tCoreExtPara or {}
  845. -- 默认缓冲区大小
  846. local rcvBufferSize = tCoreExtPara.rcvBufferSize or 0
  847. local d1, d2, d3, d4 = string.match(address, '(%d+)%.(%d+)%.(%d+).(%d+)')
  848. if not (d1 == nil or d2 == nil or d3 == nil or d4 == nil) then
  849. if self.protocol == 'TCP' then
  850. self.id = sockectCh395Conn(TCPCLIENT, address, port, self.localPort, self)
  851. elseif self.protocol == 'TCPSSL' then
  852. -- 未实现
  853. log.info("socketCh395", "no ssl")
  854. else
  855. self.id = sockectCh395Conn(UDPCLIENT, address, port, self.localPort, self)
  856. end
  857. else
  858. self.id = -2
  859. end
  860. if type(socketcore.sock_conn_ext) == "function" then
  861. if not self.id or self.id < 0 then
  862. if self.id == -2 then
  863. require "http"
  864. -- 请求腾讯云免费HttpDns解析
  865. http.request("GET", "119.29.29.29/d?dn=" .. address, nil, nil, nil, 40000,
  866. function(result, statusCode, head, body)
  867. log.info("socket.httpDnsCb", result, statusCode, head, body)
  868. sys.publish("SOCKET_HTTPDNS_RESULT_" .. address .. "_" .. port, result, statusCode, head, body)
  869. end)
  870. local _, result, statusCode, head, body = sys.waitUntil(
  871. "SOCKET_HTTPDNS_RESULT_" .. address .. "_" .. port)
  872. -- DNS解析成功
  873. if result and statusCode == "200" and body and body:match("^[%d%.]+") then
  874. return self:connect(body:match("^([%d%.]+)"), port, timeout)
  875. end
  876. end
  877. self.id = nil
  878. end
  879. end
  880. if not self.id then
  881. log.info("socket:connect: core sock conn error", self.protocol, address, port, self.cert)
  882. return false
  883. end
  884. log.info("socket:connect-coreid,prot,addr,port,cert,timeout", self.id, self.protocol, address, port, self.cert,
  885. timeout or 120)
  886. sockets[self.id] = self
  887. self.wait = "SOCKET_CONNECT"
  888. self.timerId = sys.timerStart(coroutine.resume, (timeout or 120) * 1000, self.co, false, "TIMEOUT")
  889. local result, reason = coroutine.yield()
  890. if not result and reason == 'server close' then
  891. return false
  892. end
  893. if self.timerId and reason ~= "TIMEOUT" then
  894. sys.timerStop(self.timerId)
  895. end
  896. if not result then
  897. log.info("socket:connect: connect fail" .. self.id, reason)
  898. if reason == "RESPONSE" then
  899. sockets[self.id] = nil
  900. self.id = nil
  901. end
  902. sys.publish("LIB_SOCKET_CONNECT_FAIL_IND", self.ssl, self.protocol, address, port)
  903. return false
  904. end
  905. log.info("socket:connect: connect ok")
  906. if not self.connected then
  907. self.connected = true
  908. socketsConnected = socketsConnected + 1
  909. sys.publish("SOCKET_ACTIVE", socketsConnected > 0)
  910. end
  911. return true, self.id
  912. end
  913. function mt:serverClose()
  914. if not self then
  915. return false
  916. end
  917. if self.error then
  918. log.warn('socket.client:asyncSelect', 'error', self.error)
  919. return false
  920. end
  921. coroutine.resume(self.co, false, 'server close')
  922. end
  923. --- server发送数据
  924. -- @number[opt=nil] keepAlive,服务器和客户端最大通信间隔时间,也叫心跳包最大时间,单位秒
  925. -- @string[opt=nil] pingreq,心跳包的字符串
  926. -- @return boole,false 失败,true 表示成功
  927. -- @usage
  928. -- socketClient = socket.tcp()
  929. -- socketClient:connect("www.baidu.com","80")
  930. -- while socketClient:serverSelect() do end
  931. function mt:serverSelect(keepAlive, pingreq)
  932. assert(self.co == coroutine.running(), "socket:asyncSelect: coroutine mismatch")
  933. if self.error then
  934. log.warn('socket.client:asyncSelect', 'error', self.error)
  935. return false
  936. end
  937. self.wait = "SOCKET_SEND"
  938. local dataLen = 0
  939. -- log.info("socket.asyncSelect #self.output",#self.output)
  940. while #self.output ~= 0 do
  941. local data = table.concat(self.output)
  942. dataLen = string.len(data)
  943. self.output = {}
  944. local sendSize = SENDSIZE
  945. for i = 1, dataLen, sendSize do
  946. -- 按最大MTU单元对data分包
  947. sockectCh395Send(self.id, data:sub(i, i + sendSize - 1))
  948. if self.timeout then
  949. self.timerId = sys.timerStart(coroutine.resume, self.timeout * 1000, self.co, false, "TIMEOUT")
  950. end
  951. -- log.info("socket.asyncSelect self.timeout",self.timeout)
  952. local result, reason = coroutine.yield()
  953. if not result and reason == 'server close' then
  954. return false
  955. end
  956. log.info('发送结果', result, reason)
  957. if self.timerId and reason ~= "TIMEOUT" then
  958. sys.timerStop(self.timerId)
  959. end
  960. sys.publish("SOCKET_ASYNC_SEND", result)
  961. if not result then
  962. sys.publish("LIB_SOCKET_SEND_FAIL_IND", self.ssl, self.protocol, self.address, self.port)
  963. log.warn('socket.asyncSelect', 'send error', data:sub(i, i + sendSize - 1))
  964. return false
  965. end
  966. end
  967. end
  968. self.wait = "SOCKET_WAIT"
  969. -- log.info("socket.asyncSelect",dataLen,self.id)
  970. if dataLen > 0 then
  971. sys.publish("SOCKET_SEND", self.id, true)
  972. end
  973. if keepAlive and keepAlive ~= 0 then
  974. if type(pingreq) == "function" then
  975. sys.timerStart(pingreq, keepAlive * 1000)
  976. else
  977. sys.timerStart(self.asyncSend, keepAlive * 1000, self, pingreq or "\0")
  978. end
  979. end
  980. local result, reason = coroutine.yield()
  981. if not result and reason == 'server close' then
  982. return false
  983. end
  984. return result, reason
  985. end
  986. --- 异步发送数据
  987. -- @number[opt=nil] keepAlive,服务器和客户端最大通信间隔时间,也叫心跳包最大时间,单位秒
  988. -- @string[opt=nil] pingreq,心跳包的字符串
  989. -- @return boole,false 失败,true 表示成功
  990. -- @usage
  991. -- socketClient = socket.tcp()
  992. -- socketClient:connect("www.baidu.com","80")
  993. -- while socketClient:asyncSelect() do end
  994. function mt:asyncSelect(keepAlive, pingreq)
  995. assert(self.co == coroutine.running(), "socket:asyncSelect: coroutine mismatch")
  996. if self.error then
  997. log.warn('socket.client:asyncSelect', 'error', self.error)
  998. return false
  999. end
  1000. self.wait = "SOCKET_SEND"
  1001. local dataLen = 0
  1002. -- log.info("socket.asyncSelect #self.output",#self.output)
  1003. while #self.output ~= 0 do
  1004. local data = table.concat(self.output)
  1005. dataLen = string.len(data)
  1006. self.output = {}
  1007. local sendSize = self.protocol == "UDP" and 1472 or SENDSIZE
  1008. for i = 1, dataLen, sendSize do
  1009. -- 按最大MTU单元对data分包
  1010. socketcore.sock_send(self.id, data:sub(i, i + sendSize - 1))
  1011. if self.timeout then
  1012. self.timerId = sys.timerStart(coroutine.resume, self.timeout * 1000, self.co, false, "TIMEOUT")
  1013. end
  1014. -- log.info("socket.asyncSelect self.timeout",self.timeout)
  1015. local result, reason = coroutine.yield()
  1016. if not result and reason == 'server close' then
  1017. return false
  1018. end
  1019. if self.timerId and reason ~= "TIMEOUT" then
  1020. sys.timerStop(self.timerId)
  1021. end
  1022. sys.publish("SOCKET_ASYNC_SEND", result)
  1023. if not result then
  1024. sys.publish("LIB_SOCKET_SEND_FAIL_IND", self.ssl, self.protocol, self.address, self.port)
  1025. -- log.warn('socket.asyncSelect', 'send error')
  1026. return false
  1027. end
  1028. end
  1029. end
  1030. self.wait = "SOCKET_WAIT"
  1031. -- log.info("socket.asyncSelect",dataLen,self.id)
  1032. if dataLen > 0 then
  1033. sys.publish("SOCKET_SEND", self.id, true)
  1034. end
  1035. if keepAlive and keepAlive ~= 0 then
  1036. if type(pingreq) == "function" then
  1037. sys.timerStart(pingreq, keepAlive * 1000)
  1038. else
  1039. sys.timerStart(self.asyncSend, keepAlive * 1000, self, pingreq or "\0")
  1040. end
  1041. end
  1042. local result, reason = coroutine.yield()
  1043. if not result and reason == 'server close' then
  1044. return false
  1045. end
  1046. return result, reason
  1047. end
  1048. function mt:getAsyncSend()
  1049. if self.error then
  1050. return 0
  1051. end
  1052. return #(self.output)
  1053. end
  1054. --- server缓存待发送的数据
  1055. -- @string data 数据
  1056. -- @number[opt=nil] timeout 可选参数,发送超时时间,单位秒;为nil时表示不支持timeout
  1057. -- @return result true - 成功,false - 失败
  1058. -- @usage
  1059. -- socketClient = socket.tcp()
  1060. -- socketClient:connect("www.baidu.com","80")
  1061. -- socketClient:serverSend("12345678")
  1062. function mt:serverSend(data, timeout)
  1063. if self.error then
  1064. log.warn('socket.client:asyncSend', 'error', self.error)
  1065. return false
  1066. end
  1067. self.timeout = timeout
  1068. table.insert(self.output, data or "")
  1069. -- log.info("socket.asyncSend",self.wait)
  1070. if self.wait == "SOCKET_WAIT" then
  1071. coroutine.resume(self.co, true)
  1072. end
  1073. return true
  1074. end
  1075. --- server接收数据
  1076. -- @return data 表示接收到的数据(如果是UDP,返回最新的一包数据;如果是TCP,返回所有收到的数据)
  1077. -- ""表示未收到数据
  1078. -- @usage
  1079. -- socketClient = socket.tcp()
  1080. -- socketClient:connect("www.baidu.com","80")
  1081. -- data = socketClient:serverRecv()
  1082. function mt:serverRecv()
  1083. if #self.input == 0 then
  1084. return ""
  1085. end
  1086. if self.protocol == "UDP" then
  1087. return table.remove(self.input)
  1088. else
  1089. local s = table.concat(self.input)
  1090. self.input = {}
  1091. if self.isBlock then
  1092. table.insert(self.input, recv(self.msg.socket_index, self.msg.recv_len))
  1093. end
  1094. return s
  1095. end
  1096. end
  1097. --- 异步缓存待发送的数据
  1098. -- @string data 数据
  1099. -- @number[opt=nil] timeout 可选参数,发送超时时间,单位秒;为nil时表示不支持timeout
  1100. -- @return result true - 成功,false - 失败
  1101. -- @usage
  1102. -- socketClient = socket.tcp()
  1103. -- socketClient:connect("www.baidu.com","80")
  1104. -- socketClient:asyncSend("12345678")
  1105. function mt:asyncSend(data, timeout)
  1106. if self.error then
  1107. log.warn('socket.client:asyncSend', 'error', self.error)
  1108. return false
  1109. end
  1110. self.timeout = timeout
  1111. table.insert(self.output, data or "")
  1112. -- log.info("socket.asyncSend",self.wait)
  1113. if self.wait == "SOCKET_WAIT" then
  1114. coroutine.resume(self.co, true)
  1115. end
  1116. return true
  1117. end
  1118. --- 异步接收数据
  1119. -- @return data 表示接收到的数据(如果是UDP,返回最新的一包数据;如果是TCP,返回所有收到的数据)
  1120. -- ""表示未收到数据
  1121. -- @usage
  1122. -- socketClient = socket.tcp()
  1123. -- socketClient:connect("www.baidu.com","80")
  1124. -- data = socketClient:asyncRecv()
  1125. function mt:asyncRecv()
  1126. if #self.input == 0 then
  1127. return ""
  1128. end
  1129. if self.protocol == "UDP" then
  1130. return table.remove(self.input)
  1131. else
  1132. local s = table.concat(self.input)
  1133. self.input = {}
  1134. if self.isBlock then
  1135. table.insert(self.input, socketcore.sock_recv(self.msg.socket_index, self.msg.recv_len))
  1136. end
  1137. return s
  1138. end
  1139. end
  1140. --- 同步发送数据
  1141. -- @string data 数据
  1142. -- 此处传入的数据长度和剩余可用内存有关,只要内存够用,可以随便传入数据
  1143. -- 虽然说此处的数据长度没有特别限制,但是调用core中的socket发送接口时,每次最多发送11200字节的数据
  1144. -- 例如此处传入的data长度是112000字节,则在这个send接口中,会循环10次,每次发送11200字节的数据
  1145. -- @number[opt=120] timeout 可选参数,发送超时时间,单位秒
  1146. -- @return result true - 成功,false - 失败
  1147. -- @usage
  1148. -- socketClient = socket.tcp()
  1149. -- socketClient:connect("www.baidu.com","80")
  1150. -- socketClient:send("12345678")
  1151. function mt:send(data, timeout)
  1152. assert(self.co == coroutine.running(), "socket:send: coroutine mismatch")
  1153. if self.error then
  1154. log.warn('socket.client:send', 'error', self.error)
  1155. return false
  1156. end
  1157. log.debug("socket.send", "total " .. string.len(data or "") .. " bytes", "first 30 bytes", (data or ""):sub(1, 30))
  1158. local sendSize = self.protocol == "UDP" and 1472 or SENDSIZE
  1159. for i = 1, string.len(data or ""), sendSize do
  1160. -- 按最大MTU单元对data分包
  1161. self.wait = "SOCKET_SEND"
  1162. sockectCh395Send(self.id, data:sub(i, i + sendSize - 1))
  1163. self.timerId = sys.timerStart(coroutine.resume, (timeout or 120) * 1000, self.co, false, "TIMEOUT")
  1164. local result, reason = coroutine.yield()
  1165. if not result and reason == 'server close' then
  1166. return false
  1167. end
  1168. if self.timerId and reason ~= "TIMEOUT" then
  1169. sys.timerStop(self.timerId)
  1170. end
  1171. if not result then
  1172. log.info("socket:send" .. self.id, "send fail", reason)
  1173. sys.publish("LIB_SOCKET_SEND_FAIL_IND", self.ssl, self.protocol, self.address, self.port)
  1174. return false
  1175. end
  1176. end
  1177. return true
  1178. end
  1179. --- 同步接收数据
  1180. -- @number[opt=0] timeout 可选参数,接收超时时间,单位毫秒
  1181. -- @string[opt=nil] msg 可选参数,控制socket所在的线程退出recv阻塞状态
  1182. -- @bool[opt=nil] msgNoResume 可选参数,控制socket所在的线程退出recv阻塞状态
  1183. -- false或者nil表示“在recv阻塞状态,收到msg消息,可以退出阻塞状态”,true表示不退出
  1184. -- 此参数仅lib内部使用,应用脚本不要使用此参数
  1185. -- @return result 数据接收结果
  1186. -- true表示成功(接收到了数据)
  1187. -- false表示失败(没有接收到数据)
  1188. -- @return data
  1189. -- 如果result为true,data表示接收到的数据(如果是UDP,返回最新的一包数据;如果是TCP,返回所有收到的数据)
  1190. -- 如果result为false,超时失败,data为"timeout"
  1191. -- 如果result为false,msg控制退出,data为msg的字符串
  1192. -- 如果result为false,socket连接被动断开控制退出,data为"CLOSED"
  1193. -- 如果result为false,PDP断开连接控制退出,data为"IP_ERROR_IND"
  1194. -- @return param 如果是msg控制退出,param的值是msg的参数
  1195. -- @usage
  1196. -- socketClient = socket.tcp()
  1197. -- socketClient:connect("www.baidu.com","80")
  1198. -- result,data = socketClient:recv(60000,"APP_SOCKET_SEND_DATA")
  1199. function mt:recv(timeout, msg, msgNoResume)
  1200. assert(self.co == coroutine.running(), "socket:recv: coroutine mismatch")
  1201. if self.error then
  1202. log.warn('socket.client:recv', 'error', self.error)
  1203. return false
  1204. end
  1205. self.msgNoResume = msgNoResume
  1206. if msg and not self.iSubscribe then
  1207. self.iSubscribe = msg
  1208. self.subMessage = function(data)
  1209. -- if data then table.insert(self.output, data) end
  1210. if self.wait == "+RECEIVE" and not self.msgNoResume then
  1211. if data then
  1212. table.insert(self.output, data)
  1213. end
  1214. coroutine.resume(self.co, 0xAA)
  1215. end
  1216. end
  1217. sys.subscribe(msg, self.subMessage)
  1218. end
  1219. if msg and #self.output > 0 then
  1220. sys.publish(msg, false)
  1221. end
  1222. if #self.input == 0 then
  1223. self.wait = "+RECEIVE"
  1224. if timeout and timeout > 0 then
  1225. local r, s = sys.wait(timeout)
  1226. if r == nil then
  1227. return false, "timeout"
  1228. elseif r == 0xAA then
  1229. local dat = table.concat(self.output)
  1230. self.output = {}
  1231. return false, msg, dat
  1232. else
  1233. return r, s
  1234. end
  1235. else
  1236. local r, s = coroutine.yield()
  1237. if not r and s == 'server close' then
  1238. return false
  1239. end
  1240. if r == 0xAA then
  1241. local dat = table.concat(self.output)
  1242. self.output = {}
  1243. return false, msg, dat
  1244. else
  1245. return r, s
  1246. end
  1247. end
  1248. end
  1249. if self.protocol == "UDP" then
  1250. local s = table.remove(self.input)
  1251. return true, s
  1252. else
  1253. log.warn("-------------------使用缓冲区---------------")
  1254. local s = table.concat(self.input)
  1255. self.input = {}
  1256. if self.isBlock then
  1257. table.insert(self.input, sockectCh395Recv(self.msg.socket_index, self.msg.recv_len))
  1258. end
  1259. return true, s
  1260. end
  1261. end
  1262. --- 主动关闭并且销毁一个socket
  1263. -- @return nil
  1264. -- @usage
  1265. -- socketClient = socket.tcp()
  1266. -- socketClient:connect("www.baidu.com","80")
  1267. -- socketClient:close()
  1268. function mt:close()
  1269. assert(self.co == coroutine.running(), "socket:close: coroutine mismatch")
  1270. if self.iSubscribe then
  1271. sys.unsubscribe(self.iSubscribe, self.subMessage)
  1272. self.iSubscribe = false
  1273. end
  1274. -- log.info('socketCh395', 'close' .. self.id)
  1275. -- 此处不要再判断状态,否则在连接超时失败时,conneted状态仍然是未连接,会导致无法close
  1276. -- if self.connected then
  1277. log.info("socket:sock_close", self.id)
  1278. local result, reason
  1279. if self.id then
  1280. sockectCh395Close(self.id)
  1281. self.wait = "SOCKET_CLOSE"
  1282. while true do
  1283. result, reason = coroutine.yield()
  1284. if not result and reason == 'server close' then
  1285. return false
  1286. end
  1287. if reason == "RESPONSE" then
  1288. break
  1289. end
  1290. end
  1291. end
  1292. if self.connected then
  1293. self.connected = false
  1294. if socketsConnected > 0 then
  1295. socketsConnected = socketsConnected - 1
  1296. end
  1297. sys.publish("SOCKET_ACTIVE", socketsConnected > 0)
  1298. end
  1299. if self.input then
  1300. self.input = {}
  1301. end
  1302. if self.protocol == 'TCPSERVERCLIENT' then
  1303. sockets[self.id] = true
  1304. else
  1305. if self.id ~= nil then
  1306. sockets[self.id] = nil
  1307. end
  1308. end
  1309. end
  1310. -- socket接收自定义控制处理
  1311. -- @function[opt=nil] rcvCbFnc,socket接收到数据后,执行的回调函数,回调函数的调用形式为:
  1312. -- rcvCbFnc(readFnc,socketIndex,rcvDataLen)
  1313. -- rcvCbFnc内部,会判断是否读取数据,如果读取,执行readFnc(socketIndex,rcvDataLen),返回true;否则返回false或者nil
  1314. function mt:setRcvProc(rcvCbFnc)
  1315. assert(self.co == coroutine.running(), "socket:setRcvProc: coroutine mismatch")
  1316. self.rcvProcFnc = rcvCbFnc
  1317. end
  1318. function on_response(msg)
  1319. local t = {
  1320. [rtos.MSG_SOCK_CLOSE_CNF] = 'SOCKET_CLOSE',
  1321. -- 33
  1322. [rtos.MSG_SOCK_SEND_CNF] = 'SOCKET_SEND',
  1323. -- 32
  1324. [rtos.MSG_SOCK_CONN_CNF] = 'SOCKET_CONNECT'
  1325. -- 34
  1326. }
  1327. if not sockets[msg.socket_index] then
  1328. log.warn('response on nil socket', msg.socket_index, t[msg.id], msg.result)
  1329. return
  1330. end
  1331. if sockets[msg.socket_index] == true then
  1332. return
  1333. end
  1334. log.info(sockets[msg.socket_index].wait, t[msg.id], msg.socket_index, msg.id)
  1335. if sockets[msg.socket_index].wait ~= t[msg.id] then
  1336. log.warn('response on invalid wait', sockets[msg.socket_index].id, sockets[msg.socket_index].wait, t[msg.id],
  1337. msg.socket_index)
  1338. return
  1339. end
  1340. log.info('socket:on_response:', msg.socket_index, t[msg.id], msg.result)
  1341. if sockets[msg.socket_index].protocol == 'TCPSERVERCLIENT' then
  1342. msg.result=0
  1343. end
  1344. coroutine.resume(sockets[msg.socket_index].co, msg.result == 0, 'RESPONSE')
  1345. end
  1346. sys.subscribe('SOCK_CONN_CNF', on_response)
  1347. sys.subscribe('SOCK_CLOSE_CNF', on_response)
  1348. sys.subscribe('SOCK_SEND_CNF', on_response)
  1349. -- 被动关闭
  1350. sys.subscribe('MSG_SOCK_CLOSE_IND', function(msg)
  1351. local data = string.sub(spiSend(spi.SPI_1, string.char(0x2F, msg.socket_index, 0xff, 0xff)), 3, -1)
  1352. log.info('socketCh395', 'close socket ' .. msg.socket_index .. 'state', data:toHex())
  1353. if string.sub(data, 1, 1) ~= '\x00' then
  1354. return
  1355. end
  1356. log.info('socket.rtos.MSG_SOCK_CLOSE_IND',msg.socket_index)
  1357. if not sockets[msg.socket_index] then
  1358. return
  1359. elseif sockets[msg.socket_index] == true then
  1360. return
  1361. elseif sockets[msg.socket_index].protocol == 'TCPSERVERCLIENT' then
  1362. coroutine.resume(sockets[msg.socket_index].co, false, 'CLOSED')
  1363. sockets[msg.socket_index] = true
  1364. return
  1365. end
  1366. if not sockets[msg.socket_index] then
  1367. log.warn('close ind on nil socket', msg.socket_index, msg.id)
  1368. return
  1369. end
  1370. if sockets[msg.socket_index].connected then
  1371. sockets[msg.socket_index].connected = false
  1372. if socketsConnected > 0 then
  1373. socketsConnected = socketsConnected - 1
  1374. end
  1375. sys.publish('SOCKET_ACTIVE', socketsConnected > 0)
  1376. end
  1377. sockets[msg.socket_index].error = 'CLOSED'
  1378. --[[
  1379. if type(socketcore.sock_destroy) == "function" then
  1380. socketcore.sock_destroy(msg.socket_index)
  1381. end]]
  1382. sys.publish('LIB_SOCKET_CLOSE_IND', sockets[msg.socket_index].ssl, sockets[msg.socket_index].protocol,
  1383. sockets[msg.socket_index].address, sockets[msg.socket_index].port)
  1384. coroutine.resume(sockets[msg.socket_index].co, false, 'CLOSED')
  1385. end)
  1386. sys.subscribe('MSG_SOCK_RECV_IND', function(msg)
  1387. if type(sockets[msg.socket_index])~='table' then
  1388. log.warn('close ind on nil socket', msg.socket_index, msg.id)
  1389. return
  1390. end
  1391. log.debug('socket.recv', msg.recv_len, sockets[msg.socket_index].rcvProcFnc)
  1392. if sockets[msg.socket_index].rcvProcFnc then
  1393. sockets[msg.socket_index].rcvProcFnc(msg.recv_data)
  1394. else
  1395. if sockets[msg.socket_index].wait == '+RECEIVE' then
  1396. coroutine.resume(sockets[msg.socket_index].co, true, msg.recv_data)
  1397. else -- 数据进缓冲区,缓冲区溢出采用覆盖模式
  1398. if #sockets[msg.socket_index].input > INDEX_MAX then
  1399. log.error('socket recv', 'out of stack', 'block')
  1400. -- sockets[msg.socket_index].input = {}
  1401. sockets[msg.socket_index].isBlock = true
  1402. sockets[msg.socket_index].msg = msg
  1403. else
  1404. sockets[msg.socket_index].isBlock = false
  1405. table.insert(sockets[msg.socket_index].input, msg.recv_data)
  1406. end
  1407. sys.publish('SOCKET_RECV', msg.socket_index)
  1408. end
  1409. end
  1410. end)
  1411. --- 设置TCP层自动重传的参数
  1412. -- @number[opt=4] retryCnt,重传次数;取值范围0到12
  1413. -- @number[opt=16] retryMaxTimeout,限制每次重传允许的最大超时时间(单位秒),取值范围1到16
  1414. -- @return nil
  1415. -- @usage
  1416. -- setTcpResendPara(3,8)
  1417. -- setTcpResendPara(4,16)
  1418. function setTcpResendPara(retryCnt, retryMaxTimeout)
  1419. ril.request("AT+TCPUSERPARAM=6," .. (retryCnt or 4) .. ",7200," .. (retryMaxTimeout or 16))
  1420. end
  1421. --- 设置域名解析参数
  1422. -- 注意:0027以及之后的core版本才支持此功能
  1423. -- @number[opt=4] retryCnt,重传次数;取值范围1到8
  1424. -- @number[opt=4] retryTimeoutMulti,重传超时时间倍数,取值范围1到5
  1425. -- 第n次重传超时时间的计算方式为:第n次的重传超时基数*retryTimeoutMulti,单位为秒
  1426. -- 重传超时基数表为{1, 1, 2, 4, 4, 4, 4, 4}
  1427. -- 第1次重传超时时间为:1*retryTimeoutMulti 秒
  1428. -- 第2次重传超时时间为:1*retryTimeoutMulti 秒
  1429. -- 第3次重传超时时间为:2*retryTimeoutMulti 秒
  1430. -- ...........................................
  1431. -- 第8次重传超时时间为:8*retryTimeoutMulti 秒
  1432. -- @return nil
  1433. -- @usage
  1434. -- socket.setDnsParsePara(8,5)
  1435. function setDnsParsePara(retryCnt, retryTimeoutMulti)
  1436. ril.request("AT*DNSTMOUT=" .. (retryCnt or 4) .. "," .. (retryTimeoutMulti or 4))
  1437. end
  1438. --- 打印所有socket的状态
  1439. -- @return 无
  1440. -- @usage socket.printStatus()
  1441. function printStatus()
  1442. for _, client in pairs(sockets) do
  1443. for k, v in pairs(client) do
  1444. log.info('socket.printStatus', 'client', client.id, k, v)
  1445. end
  1446. end
  1447. end
  1448. --- 设置数据传输后,允许进入休眠状态的延时时长
  1449. -- 3024版本以及之后的版本才支持此功能
  1450. -- 此功能设置的参数,设置成功后,掉电会自动保存
  1451. -- @number tm,数据传输后,允许进入休眠状态的延时时长,单位为秒,取值范围1到20
  1452. -- 注意:此时间越短,允许进入休眠状态越快,功耗越低;但是在某些网络环境中,此时间越短,可能会造成数据传输不稳定
  1453. -- 建议在可以接受的功耗范围内,此值设置的越大越好
  1454. -- 如果没有设置此参数,此延时时长是和基站的配置有关,一般来说是10秒左右
  1455. -- @return nil
  1456. -- @usage
  1457. -- socket.setLowPower(5)
  1458. function setLowPower(tm)
  1459. ril.request("AT*RTIME=" .. tm)
  1460. end