main.lua 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "httpdemo"
  3. VERSION = "1.0.0"
  4. --[[
  5. 本demo需要http库, 大部分能联网的设备都具有这个库
  6. http也是内置库, 无需require
  7. ]]
  8. -- sys库是标配
  9. _G.sys = require("sys")
  10. --[[特别注意, 使用http库需要下列语句]]
  11. _G.sysplus = require("sysplus")
  12. -- Air780E的AT固件默认会为开机键防抖, 导致部分用户刷机很麻烦
  13. if rtos.bsp() == "EC618" and pm and pm.PWK_MODE then
  14. pm.power(pm.PWK_MODE, false)
  15. end
  16. sys.taskInit(function()
  17. -----------------------------
  18. -- 统一联网函数, 可自行删减
  19. ----------------------------
  20. if rtos.bsp():startsWith("ESP32") then
  21. -- wifi 联网, ESP32系列均支持
  22. local ssid = "uiot"
  23. local password = "12345678"
  24. log.info("wifi", ssid, password)
  25. -- TODO 改成esptouch配网
  26. LED = gpio.setup(12, 0, gpio.PULLUP)
  27. wlan.init()
  28. wlan.setMode(wlan.STATION)
  29. wlan.connect(ssid, password, 1)
  30. local result, data = sys.waitUntil("IP_READY", 30000)
  31. log.info("wlan", "IP_READY", result, data)
  32. device_id = wlan.getMac()
  33. elseif rtos.bsp() == "AIR105" then
  34. -- w5500 以太网, 当前仅Air105支持
  35. w5500.init(spi.HSPI_0, 24000000, pin.PC14, pin.PC01, pin.PC00)
  36. w5500.config() --默认是DHCP模式
  37. w5500.bind(socket.ETH0)
  38. LED = gpio.setup(62, 0, gpio.PULLUP)
  39. sys.wait(1000)
  40. -- TODO 获取mac地址作为device_id
  41. elseif rtos.bsp() == "EC618" then
  42. -- Air780E/Air600E系列
  43. --mobile.simid(2)
  44. LED = gpio.setup(27, 0, gpio.PULLUP)
  45. device_id = mobile.imei()
  46. log.info("ipv6", mobile.ipv6(true))
  47. sys.waitUntil("IP_READY", 30000)
  48. end
  49. log.info("已联网")
  50. sys.publish("net_ready")
  51. end)
  52. function demo_http_get()
  53. -- 最普通的Http GET请求
  54. local code, headers, body = http.request("GET", "https://www.air32.cn/").wait()
  55. log.info("http.get", code, headers, body)
  56. local code, headers, body = http.request("GET", "https://mirrors6.tuna.tsinghua.edu.cn/", nil, nil, {ipv6=true}).wait()
  57. log.info("http.get", code, headers, body)
  58. sys.wait(100)
  59. local code, headers, body = http.request("GET", "https://www.luatos.com/").wait()
  60. log.info("http.get", code, headers, body)
  61. -- 按需打印
  62. -- code 响应值, 若大于等于 100 为服务器响应, 小于的均为错误代码
  63. -- headers是个table, 一般作为调试数据存在
  64. -- body是字符串. 注意lua的字符串是带长度的byte[]/char*, 是可以包含不可见字符的
  65. -- log.info("http", code, json.encode(headers or {}), #body > 512 and #body or body)
  66. end
  67. function demo_http_post_json()
  68. -- POST request 演示
  69. local req_headers = {}
  70. req_headers["Content-Type"] = "application/json"
  71. local body = json.encode({name="LuatOS"})
  72. local code, headers, body = http.request("POST","http://site0.cn/api/httptest/simple/date",
  73. req_headers,
  74. body -- POST请求所需要的body, string, zbuff, file均可
  75. ).wait()
  76. log.info("http.post", code, headers, body)
  77. end
  78. function demo_http_post_form()
  79. -- POST request 演示
  80. local req_headers = {}
  81. req_headers["Content-Type"] = "application/x-www-form-urlencoded"
  82. local params = {
  83. ABC = "123",
  84. DEF = 345
  85. }
  86. local body = ""
  87. for k, v in pairs(params) do
  88. body = body .. tostring(k) .. "=" .. tostring(v):urlEncode() .. "&"
  89. end
  90. local code, headers, body = http.request("POST","http://echohttp.wendal.cn/post",
  91. req_headers,
  92. body -- POST请求所需要的body, string, zbuff, file均可
  93. ).wait()
  94. log.info("http.post.form", code, headers, body)
  95. end
  96. function demo_http_download()
  97. -- POST and download, task内的同步操作
  98. local opts = {} -- 额外的配置项
  99. opts["dst"] = "/data.bin" -- 下载路径,可选
  100. opts["timeout"] = 30 -- 超时时长,单位秒,可选
  101. opts["adapter"] = socket.ETH0 -- 使用哪个网卡,可选
  102. local code, headers, body = http.request("POST","http://site0.cn/api/httptest/simple/date",
  103. {}, -- 请求所添加的 headers, 可以是nil
  104. "",
  105. opts
  106. ).wait()
  107. log.info("http.post", code, headers, body) -- 只返回code和headers
  108. local f = io.open("/data.bin", "rb")
  109. if f then
  110. local data = f:read("*a")
  111. log.info("fs", "data", data, data:toHex())
  112. end
  113. -- GET request, 开个task让它自行执行去吧, 不管执行结果了
  114. sys.taskInit(http.request("GET","http://site0.cn/api/httptest/simple/time").wait)
  115. end
  116. function demo_http_post_file()
  117. -- -- POST multipart/form-data模式 上传文件---手动拼接
  118. local boundary = "----WebKitFormBoundary"..os.time()
  119. local req_headers = {
  120. ["Content-Type"] = "multipart/form-data; boundary="..boundary,
  121. }
  122. local body = "--"..boundary.."\r\n"..
  123. "Content-Disposition: form-data; name=\"uploadFile\"; filename=\"luatos_uploadFile_TEST01.txt\""..
  124. "\r\nContent-Type: text/plain\r\n\r\n"..
  125. "1111http_测试一二三四654zacc\r\n"..
  126. "--"..boundary
  127. log.info("headers: ", "\r\n"..json.encode(req_headers))
  128. log.info("body: ", "\r\n"..body)
  129. local code, headers, body = http.request("POST","http://airtest.openluat.com:2900/uploadFileToStatic",
  130. req_headers,
  131. body -- POST请求所需要的body, string, zbuff, file均可
  132. ).wait()
  133. log.info("http.post", code, headers, body)
  134. -- 也可用postMultipartFormData(url, params) 上传文件
  135. postMultipartFormData(
  136. "http://airtest.openluat.com:2900/uploadFileToStatic",
  137. {
  138. -- texts =
  139. -- {
  140. -- ["imei"] = "862991234567890",
  141. -- ["time"] = "20180802180345"
  142. -- },
  143. files =
  144. {
  145. ["uploadFile"] = "/luadb/luatos_uploadFile.txt",
  146. }
  147. }
  148. )
  149. end
  150. sys.taskInit(function()
  151. sys.wait(100)
  152. -- 打印一下支持的加密套件, 通常来说, 固件已包含常见的99%的加密套件
  153. -- if crypto.cipher_suites then
  154. -- log.info("cipher", "suites", json.encode(crypto.cipher_suites()))
  155. -- end
  156. -------------------------------------
  157. -------- HTTP 演示代码 --------------
  158. -------------------------------------
  159. sys.waitUntil("net_ready") -- 等联网
  160. while 1 do
  161. -- 演示GET请求
  162. -- demo_http_get()
  163. -- 表单提交
  164. demo_http_post_form()
  165. -- POST一个json字符串
  166. -- demo_http_post_json()
  167. -- 上传文件, mulitform形式
  168. -- demo_http_post_file()
  169. -- 文件下载
  170. -- demo_http_download()
  171. sys.wait(1000)
  172. -- 打印一下内存状态
  173. log.info("sys", rtos.meminfo("sys"))
  174. log.info("lua", rtos.meminfo("lua"))
  175. sys.wait(600000)
  176. end
  177. end)
  178. ---- MultipartForm上传文件
  179. -- url string 请求URL地址
  180. -- req_headers table 请求头
  181. -- params table 需要传输的数据参数
  182. function postMultipartFormData(url, params)
  183. local boundary = "----WebKitFormBoundary"..os.time()
  184. local req_headers = {
  185. ["Content-Type"] = "multipart/form-data; boundary="..boundary,
  186. }
  187. local body = {}
  188. -- 解析拼接 body
  189. for k,v in pairs(params) do
  190. if k=="texts" then
  191. local bodyText = ""
  192. for kk,vv in pairs(v) do
  193. print(kk,vv)
  194. bodyText = bodyText.."--"..boundary.."\r\nContent-Disposition: form-data; name=\""..kk.."\"\r\n\r\n"..vv.."\r\n"
  195. end
  196. table.insert(body, bodyText)
  197. elseif k=="files" then
  198. local contentType =
  199. {
  200. txt = "text/plain", -- 文本
  201. jpg = "image/jpeg", -- JPG 格式图片
  202. jpeg = "image/jpeg", -- JPEG 格式图片
  203. png = "image/png", -- PNG 格式图片
  204. gif = "image/gif", -- GIF 格式图片
  205. html = "image/html", -- HTML
  206. json = "application/json" -- JSON
  207. }
  208. for kk,vv in pairs(v) do
  209. if type(vv) == "table" then
  210. for i=1, #vv do
  211. print(kk,vv[i])
  212. table.insert(body, "--"..boundary.."\r\nContent-Disposition: form-data; name=\""..kk.."\"; filename=\""..vv[i]:match("[^%/]+%w$").."\"\r\nContent-Type: "..contentType[vv[i]:match("%.(%w+)$")].."\r\n\r\n")
  213. table.insert(body, io.readFile(vv[i]))
  214. table.insert(body, "\r\n")
  215. end
  216. else
  217. print(kk,vv)
  218. table.insert(body, "--"..boundary.."\r\nContent-Disposition: form-data; name=\""..kk.."\"; filename=\""..vv:match("[^%/]+%w$").."\"\r\nContent-Type: "..contentType[vv:match("%.(%w+)$")].."\r\n\r\n")
  219. table.insert(body, io.readFile(vv))
  220. table.insert(body, "\r\n")
  221. end
  222. end
  223. end
  224. end
  225. table.insert(body, "--"..boundary.."--\r\n")
  226. body = table.concat(body)
  227. log.info("headers: ", "\r\n" .. json.encode(req_headers), type(body))
  228. log.info("body: " .. body:len() .. "\r\n" .. body)
  229. local code, headers, body = http.request("POST",url,
  230. req_headers,
  231. body
  232. ).wait()
  233. log.info("http.post", code, headers, body)
  234. end
  235. -- 用户代码已结束---------------------------------------------
  236. -- 结尾总是这一句
  237. sys.run()
  238. -- sys.run()之后后面不要加任何语句!!!!!