gyrogpsc/core/collectors.go

106 lines
2.0 KiB
Go

package core
import (
"fmt"
"log"
"net"
"os"
"git.timovolkmann.de/gyrogpsc/ublox"
"go.bug.st/serial"
)
func TcpCollector(proc Processor, tcpPort string) {
log.Println("start tcp collectors")
listener, err := net.Listen("tcp", tcpPort)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
// Close the listener when the application closes.
defer listener.Close()
for {
// Listen for an incoming connection.
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
}
log.Println("...new incoming tcp connection...")
// Handle connections in a new goroutine.
go jsonHandler(conn, proc)
}
}
// handles incoming tcp connections with json payload.
func jsonHandler(conn net.Conn, proc Processor) {
defer conn.Close()
// TRY reader := bufio.NewReader(conn) OR NewScanner(conn)
buf := make([]byte, 2048)
for {
// Read the incoming connection into the buffer.
n, err := conn.Read(buf)
if err != nil {
fmt.Println("TCP error - reading from connection:", n, err.Error())
break
}
//json := pretty.Pretty(buf[:n])
//fmt.Println(string(json))
//fmt.Println(string(buf[:n]))
sd, err := ConvertSensorDataPhone(buf[:n])
if err != nil {
log.Println(err)
continue
}
err = proc.Process(sd)
if err != nil {
log.Println(err)
continue
}
}
}
func SerialCollector(proc Processor, serialPort string) {
log.Println("start serial collectors")
mode := &serial.Mode{
BaudRate: 115200,
}
port, err := serial.Open(serialPort, mode)
if err != nil {
log.Fatalln(err.Error())
}
decoder := ublox.NewDecoder(port)
for {
meas, err := decoder.Decode()
if err != nil {
if err.Error() == "NMEA not implemented" {
continue
}
log.Println(err)
continue
}
sd, err := ConvertUbxToSensorData(meas)
if err != nil {
log.Println("convert err:", err, meas)
continue
}
if sd == nil {
continue
}
err = proc.Process(sd)
if err != nil {
log.Println("process err:", err, *sd)
continue
}
}
}