GPS.go 2.1 KB

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