main.lua 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "gnss_udp"
  3. VERSION = "1.0.0"
  4. -- sys库是标配
  5. _G.sys = require("sys")
  6. -- GNSS数据从uart2输入, 通常的波特率是9600,这里写的是115200
  7. -- 9600读取太慢了, 最好能设置到115200
  8. uart.on(2, "recv", function(id, len)
  9. local data = uart.read(2, 1024)
  10. --log.info("uart2", data)
  11. libgnss.parse(data)
  12. end)
  13. uart.setup(2, 115200) -- 如果没数据,那就改成9600试试吧
  14. -- 定时打印一下最新的坐标
  15. sys.timerLoopStart(function()
  16. log.info("GPS", libgnss.getIntLocation())
  17. end, 2000) -- 两秒打印一次
  18. -- 联网上报任务
  19. sys.taskInit(function()
  20. while 1 do
  21. if socket.isReady() then
  22. sys.wait(2000)
  23. -- 以下地址luatos提供的一个测试服务
  24. local netc = socket.udp()
  25. --netc:host("devtrack.luatos.io")
  26. netc:host("39.105.203.30")
  27. netc:port(9170)
  28. netc:on("connect", function(id, re)
  29. log.info("udp", "connect ok", id, re)
  30. if re then
  31. -- 连接成功, 发送注册包
  32. netc:send(nbiot.imei() .. "#" .. string.char(0x01, 0x03) .. nbiot.iccid())
  33. end
  34. end)
  35. netc:on("recv", function(id, data)
  36. -- 服务器会下发点数据,当前就"OK"两个字节,没什么左右
  37. log.info("udp", "recv", #data, data)
  38. end)
  39. if (netc:start()) == 0 then
  40. while netc:closed() == 0 do
  41. sys.waitUntil("NETC_END_" .. netc:id(), 30000)
  42. if (netc:closed()) == 0 then
  43. -- 定位成功,发送定位信息
  44. if libgnss.isFix() then
  45. local data = nbiot.imei() .. "#" .. string.char(0x01, 0x01)
  46. local lat, lng, speed = libgnss.getIntLocation()
  47. log.info("udp", "send gnss loc", lat, lng)
  48. data = data .. pack.pack(">bIIIHHbbbHH", 0x01, os.time(), lng, lat, 0 ,0 ,speed/1000, 0, 0, 0, 0)
  49. log.info("udp", data:toHex())
  50. netc:send(data)
  51. -- 定位失败, 就发个心跳吧
  52. else
  53. log.info("udp", "send heartbeat")
  54. netc:send(nbiot.imei() .. "#" .. string.char(0x01, 0x02))
  55. end
  56. end
  57. end
  58. end
  59. netc:clean()
  60. netc:close()
  61. log.info("udp", "all close, sleep 30s")
  62. sys.wait(300000)
  63. else
  64. sys.wait(1000)
  65. end
  66. end
  67. end)
  68. -- 用户代码已结束---------------------------------------------
  69. -- 结尾总是这一句
  70. sys.run()
  71. -- sys.run()之后后面不要加任何语句!!!!!