123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- 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()
- }
|