dongpu2694 2018-06-01 18:34
浏览 94
已采纳

Go-使用goroutine解析的串行端口输入不打印

I am taking input through the serial port (using an Arduino) and I want to parse the data. Here is what I have so far:

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:
%q
%q", data[0], data[1])

}

func readSecondLine(data []string, wg *sync.WaitGroup){
    defer wg.Done()

    fmt.Printf("This is the actuator data:
%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()

    }
}   

The serial port currently prints this (looped):

{"temperature":[27.7],"humidity":[46.9],"sensor":"DHT22"}
{"temperature":[25.41545],"sensor":"LM35DZ"}
{"blink":["true"],"actuator":"arduinoLED"}

I am trying to use goroutines to parse the data, and print this (should be looped as well):

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"}

However, I am not getting an output. The program simply isn't printing. I think it has to do with the way I am saving the data. Does anyone know how to fix this? And if it's fixed, whether this use of goroutines is the correct method to achieving what I want?

Thank you so much.

  • 写回答

1条回答 默认 最新

  • doulu2576 2018-06-01 19:43
    关注

    The obvious problem with your code is invalid use of the waitgroup - you init it with 2 and then wait for it in infinite loop... also, your code never reaches to the part where it calls readFirstLine and readSecondLine, it is stuck in the scanner loop

    I think the basic structure youre after would be something like following:

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

    And the goroutines which process the data would be like:

    func processSensorData(data chan string) {
       for d := range data {
          // do something with data
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题