package main import ( "bufio" "fmt" "github.com/adrianmo/go-nmea" "github.com/gin-gonic/gin" "github.com/tarm/serial" "io" "net" "sync" ) type GPS struct { ConnectionType string `toml:"ConnectionType"` ConnectionString string `toml:"ConnectionString"` serial interface{} `toml:"-"` latitude float64 `toml:"-"` longitude float64 `toml:"-"` mutex sync.RWMutex `toml:"-"` } func (g *GPS) Open() (err error) { if g.ConnectionType == "serial" { g.serial, err = serial.OpenPort(&serial.Config{ Name: "/dev/ttyS3", Baud: 9600, }) if err != nil { return } g.latitude = 0 g.longitude = 0 g.mutex = sync.RWMutex{} go func() { for { scanner := bufio.NewScanner(g.serial.(io.Reader)) for scanner.Scan() { s, err := nmea.Parse(scanner.Text()) if err != nil { println(err.Error()) continue } if s.DataType() == nmea.TypeRMC { m := s.(nmea.RMC) g.mutex.Lock() g.latitude = m.Latitude g.longitude = m.Longitude g.mutex.Unlock() } } } }() } if g.ConnectionType == "TCP" { // 连接到 TCP 服务器 g.serial, err = net.Dial("tcp", g.ConnectionString) if err != nil { fmt.Println("Failed to connect to TCP server:", err) return } g.latitude = 0 g.longitude = 0 g.mutex = sync.RWMutex{} go func() { for { scanner := bufio.NewScanner(g.serial.(io.Reader)) for scanner.Scan() { s, err := nmea.Parse(scanner.Text()) if err != nil { println(err.Error()) continue } if s.DataType() == nmea.TypeRMC { m := s.(nmea.RMC) g.mutex.Lock() g.latitude = m.Latitude g.longitude = m.Longitude g.mutex.Unlock() } } } }() } return } func (g *GPS) close() (err error) { if g.ConnectionType == "serial" { return g.serial.(*serial.Port).Close() } else if g.ConnectionType == "TCP" { return g.serial.(net.Conn).Close() } return } func (g *GPS) ObtainLatitudeAndLongitude(ctx *gin.Context) { g.mutex.RLock() ctx.JSON(200, map[string]float64{ "latitude": g.latitude, "longitude": g.longitude, }) g.mutex.RUnlock() }