kiast-drone-collector/pkg/drone/service.go
2019-08-06 09:54:55 +09:00

96 lines
2.5 KiB
Go

package drone
import (
"log"
"net"
"sync"
"time"
)
// An uninteresting service.
type Service struct {
ch chan bool
waitGroup *sync.WaitGroup
}
// Make a new Service.
func NewService() *Service {
s := &Service{
ch: make(chan bool),
waitGroup: &sync.WaitGroup{},
}
s.waitGroup.Add(1)
return s
}
// Accept connections and spawn a goroutine to serve each one. Stop listening
// if anything is received on the service's channel.
func (s *Service) Serve(listener *net.TCPListener) {
defer s.waitGroup.Done()
for {
select {
case <-s.ch:
log.Println("stopping listening on", listener.Addr())
listener.Close()
return
default:
}
listener.SetDeadline(time.Now().Add(1e9))
conn, err := listener.AcceptTCP()
if nil != err {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
continue
}
log.Println(err)
}
log.Println(conn.RemoteAddr(), "connected")
s.waitGroup.Add(1)
go s.serve(conn)
}
}
// Stop the service by closing the service's channel. Block until the service
// is really stopped.
func (s *Service) Stop() {
close(s.ch)
s.waitGroup.Wait()
}
// Serve a connection by reading and writing what was read. That's right, this
// is an echo service. Stop reading and writing if anything is received on the
// service's channel but only after writing what was read.
func (s *Service) serve(conn *net.TCPConn) {
defer conn.Close()
defer s.waitGroup.Done()
for {
select {
case <-s.ch:
log.Println("disconnecting", conn.RemoteAddr())
return
default:
}
conn.SetDeadline(time.Now().Add(1e9))
buf := make([]byte, 4096)
if _, err := conn.Read(buf); nil != err {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
continue
}
log.Println(err)
return
}
// fixed
// $$GPS, 년월일, 시분초, 위도, 경도, 고도, 속도, 방향, A, LTE 통신 상태, EMM 오류 정보, ESM 오류 정보, 신호세기, 위성 갯수, 위성 ID-신호세기, 위성 ID-신호세기, 위성 ID-신호세기, 위성 ID-신호세기
// $$GPS,20190718,050519,37396586,126968913,798,0,0,A,2,255,255,-53,13,17-44,19-43,6-42,28-41
// unfixed
// $$GPS,,,,,,,, V, LTE 통신 상태, EMM 오류 정보, ESM 오류 정보, 신호세기, 위성 갯수, 위성 ID-신호세기, 위성 ID-신호세기, 위성 ID-신호세기, 위성 ID-신호세기
// $$GPS,,,,,,,,V,2,255,255,-53,4,17-44,19-42,6-40,28-40
// if _, err := conn.Write(buf); nil != err {
// log.Println(err)
// return
// }
}
}