main.lua 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. -- 如需发送到钉钉, 参考 demo/dingding
  40. -- 如需发送到飞书, 参考 demo/feishu
  41. end
  42. --------------------------------------------------------------------
  43. -- 接收短信, 支持多种方式, 选一种就可以了
  44. -- 1. 设置回调函数
  45. --sms.setNewSmsCb(sms_handler)
  46. -- 2. 订阅系统消息
  47. --sys.subscribe("SMS_INC", sms_handler)
  48. -- 3. 在task里等着
  49. sys.taskInit(function()
  50. while 1 do
  51. local ret, num, txt = sys.waitUntil("SMS_INC", 300000)
  52. if num then
  53. -- 方案1, 交给自定义函数处理
  54. sms_handler(num, txt)
  55. -- 方案2, 因为这里是task内, 可以直接调用http.request
  56. -- local body = json.encode({phone=num, txt=txt})
  57. -- local headers = {}
  58. -- headers["Content-Type"] = "application/json"
  59. -- log.info("json", body)
  60. -- local code, headers, body = http.request("POST", "http://www.luatos.com/api/sms/blackhole", headers, body).wait()
  61. -- log.info("resp", code)
  62. end
  63. end
  64. end)
  65. -------------------------------------------------------------------
  66. -- 发送短信, 直接调用sms.send就行, 是不是task无所谓
  67. sys.taskInit(function()
  68. sys.wait(10000)
  69. -- 中移动卡查短信
  70. -- sms.send("+8610086", "301")
  71. -- 联通卡查话费
  72. sms.send("10010", "101")
  73. end)
  74. -- 用户代码已结束---------------------------------------------
  75. -- 结尾总是这一句
  76. sys.run()
  77. -- sys.run()之后后面不要加任何语句!!!!!