我通过串口(使用Arduino)接收输入,我想解析数据。以下是我到目前为止的情况:
package main
import (
"log"
"github.com/tarm/serial"
"bufio"
"sync"
"fmt"
)
func readFirstLine(data []string, wg *sync.WaitGroup){
defer wg.Done()
fmt.Printf("This is the sensor data:\n%q\n%q", data[0], data[1])
}
func readSecondLine(data []string, wg *sync.WaitGroup){
defer wg.Done()
fmt.Printf("This is the actuator data:\n%q", data[2])
}
func main() {
usbRead := &serial.Config{Name: "COM5", Baud: 9600, ReadTimeout: 0}
port, err := serial.OpenPort(usbRead)
var wg sync.WaitGroup
wg.Add(2)
if err != nil {
log.Fatal(err)
}
data := []string{}
scanner := bufio.NewScanner(port)
for scanner.Scan() {
data = append(data, scanner.Text())
}
for {
go readFirstLine(data, &wg)
go readSecondLine(data, &wg)
wg.Wait()
}
}
串口当前打印(循环):
{"temperature":[27.7],"humidity":[46.9],"sensor":"DHT22"}
{"temperature":[25.41545],"sensor":"LM35DZ"}
{"blink":["true"],"actuator":"arduinoLED"}
我正在尝试使用goroutines来解析数据,然后打印它(也应该循环):
This is the sensor data:
{"temperature":[27.7],"humidity":[46.9],"sensor":"DHT22"}
{"temperature":[25.41545],"sensor":"LM35DZ"}
This is the actuator data:
{"blink":["true"],"actuator":"arduinoLED"}
但是,我不获得输出。该程序根本不打印。我认为这与我保存数据的方式有关。有谁知道如何解决这一问题?如果它已经修复,那么使用goroutines是否是实现我想要的正确方法?
非常感谢你。
答案 0 :(得分:1)
代码的明显问题是无效使用waitgroup - 你用2启动它然后在无限循环中等待它...同样,你的代码永远不会到达它调用readFirstLine
的部分并且readSecondLine
,它卡在扫描仪循环中
我认为您之后的基本结构如下:
func main() {
// create channels for data
sensor := make(chan string)
actuator := make(chan string)
// launch goroutines which process the data
var wg, pg sync.WaitGroup
pg.Add(2)
go func() {
defer pg.Done()
processSensorData(sensor)
}()
go func() {
defer pg.Done()
processActuatorData(actuator)
}()
// read from the data source
usbRead := &serial.Config{Name: "COM5", Baud: 9600, ReadTimeout: 0}
port, err := serial.OpenPort(usbRead)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(port)
for scanner.Scan() {
data := scanner.Text()
wg.Add(1)
go func(data string) {
defer wg.Done()
// figure out data packet type and
// send it into approprioate channel
if strings.Contains(data, `"sensor"`) {
sensor <- data
} else {
actuator <- data
}
}(data)
}
// wait for all data to be sent for processing
wg.Wait()
// close the channels so goroutines terminate
close(sensor)
close(actuator)
// wait for all data to be processed
pg.Wait()
}
处理数据的goroutines就像:
func processSensorData(data chan string) {
for d := range data {
// do something with data
}
}