GPS.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/adrianmo/go-nmea"
  6. "github.com/gin-gonic/gin"
  7. "github.com/tarm/serial"
  8. "io"
  9. "net"
  10. "sync"
  11. )
  12. type GPS struct {
  13. ConnectionType string `toml:"ConnectionType"`
  14. ConnectionString string `toml:"ConnectionString"`
  15. ConnectionSerial string `toml:"ConnectionSerial"`
  16. serial interface{} `toml:"-"`
  17. latitude float64 `toml:"-"`
  18. longitude float64 `toml:"-"`
  19. mutex sync.RWMutex `toml:"-"`
  20. }
  21. func (g *GPS) Open() (err error) {
  22. if g.ConnectionType == "serial" {
  23. g.serial, err = serial.OpenPort(&serial.Config{
  24. Name: g.ConnectionSerial, Baud: 9600,
  25. })
  26. if err != nil {
  27. return
  28. }
  29. g.latitude = 0
  30. g.longitude = 0
  31. g.mutex = sync.RWMutex{}
  32. go func() {
  33. for {
  34. scanner := bufio.NewScanner(g.serial.(io.Reader))
  35. for scanner.Scan() {
  36. s, err := nmea.Parse(scanner.Text())
  37. if err != nil {
  38. println(err.Error())
  39. continue
  40. }
  41. if s.DataType() == nmea.TypeRMC {
  42. m := s.(nmea.RMC)
  43. g.mutex.Lock()
  44. g.latitude = m.Latitude
  45. g.longitude = m.Longitude
  46. g.mutex.Unlock()
  47. }
  48. }
  49. }
  50. }()
  51. }
  52. if g.ConnectionType == "TCP" {
  53. // 连接到 TCP 服务器
  54. g.serial, err = net.Dial("tcp", g.ConnectionString)
  55. if err != nil {
  56. fmt.Println("Failed to connect to TCP server:", err)
  57. return
  58. }
  59. g.latitude = 0
  60. g.longitude = 0
  61. g.mutex = sync.RWMutex{}
  62. go func() {
  63. for {
  64. scanner := bufio.NewScanner(g.serial.(io.Reader))
  65. for scanner.Scan() {
  66. s, err := nmea.Parse(scanner.Text())
  67. if err != nil {
  68. println(err.Error())
  69. continue
  70. }
  71. if s.DataType() == nmea.TypeRMC {
  72. m := s.(nmea.RMC)
  73. g.mutex.Lock()
  74. g.latitude = m.Latitude
  75. g.longitude = m.Longitude
  76. g.mutex.Unlock()
  77. }
  78. }
  79. }
  80. }()
  81. }
  82. return
  83. }
  84. func (g *GPS) close() (err error) {
  85. if g.ConnectionType == "serial" {
  86. return g.serial.(*serial.Port).Close()
  87. } else if g.ConnectionType == "TCP" {
  88. return g.serial.(net.Conn).Close()
  89. }
  90. return
  91. }
  92. func (g *GPS) ObtainLatitudeAndLongitude(ctx *gin.Context) {
  93. g.mutex.RLock()
  94. ctx.JSON(200, map[string]float64{
  95. "latitude": g.latitude,
  96. "longitude": g.longitude,
  97. })
  98. g.mutex.RUnlock()
  99. }