main.lua 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "smsdemo"
  3. VERSION = "1.0.0"
  4. log.info("main", PROJECT, VERSION)
  5. -- 引入必要的库文件(lua编写), 内部库不需要require
  6. sys = require("sys")
  7. require "sysplus" -- http库需要这个sysplus
  8. if wdt then
  9. --添加硬狗防止程序卡死,在支持的设备上启用这个功能
  10. wdt.init(9000)--初始化watchdog设置为9s
  11. sys.timerLoopStart(wdt.feed, 3000)--3s喂一次狗
  12. end
  13. log.info("main", "sms demo")
  14. -- 辅助发送http请求, 因为http库需要在task里运行
  15. function http_post(url, headers, body)
  16. sys.taskInit(function()
  17. local code, headers, body = http.request("POST", url, headers, body).wait()
  18. log.info("resp", code)
  19. end)
  20. end
  21. function sms_handler(num, txt)
  22. -- num 手机号码
  23. -- txt 文本内容
  24. log.info("sms", num, txt, txt:toHex())
  25. -- http演示1, 发json
  26. local body = json.encode({phone=num, txt=txt})
  27. local headers = {}
  28. headers["Content-Type"] = "application/json"
  29. log.info("json", body)
  30. http_post("http://www.luatos.com/api/sms/blackhole", headers, body)
  31. -- http演示2, 发表单的
  32. headers = {}
  33. headers["Content-Type"] = "application/x-www-form-urlencoded"
  34. local body = string.format("phone=%s&txt=%s", num:urlEncode(), txt:urlEncode())
  35. log.info("params", body)
  36. http_post("http://www.luatos.com/api/sms/blackhole", headers, body)
  37. -- http演示3, 不需要headers,直接发
  38. http_post("http://www.luatos.com/api/sms/blackhole", nil, num .. "," .. txt)
  39. end
  40. --------------------------------------------------------------------
  41. -- 接收短信, 支持多种方式, 选一种就可以了
  42. -- 1. 设置回调函数
  43. --sms.setNewSmsCb(sms_handler)
  44. -- 2. 订阅系统消息
  45. --sys.subscribe("SMS_INC", sms_handler)
  46. -- 3. 在task里等着
  47. sys.taskInit(function()
  48. while 1 do
  49. local ret, num, txt = sys.waitUntil("SMS_INC", 300000)
  50. if num then
  51. -- 方案1, 交给自定义函数处理
  52. sms_handler(num, txt)
  53. -- 方案2, 因为这里是task内, 可以直接调用http.request
  54. -- local body = json.encode({phone=num, txt=txt})
  55. -- local headers = {}
  56. -- headers["Content-Type"] = "application/json"
  57. -- log.info("json", body)
  58. -- local code, headers, body = http.request("POST", "http://www.luatos.com/api/sms/blackhole", headers, body).wait()
  59. -- log.info("resp", code)
  60. end
  61. end
  62. end)
  63. -------------------------------------------------------------------
  64. -- 发送短信, 直接调用sms.send就行, 是不是task无所谓
  65. sys.taskInit(function()
  66. sys.wait(10000)
  67. -- 中移动卡查短信
  68. -- sms.send("+8610086", "301")
  69. -- 联通卡查话费
  70. sms.send("10010", "101")
  71. end)
  72. -- 用户代码已结束---------------------------------------------
  73. -- 结尾总是这一句
  74. sys.run()
  75. -- sys.run()之后后面不要加任何语句!!!!!