<p>This is the code</p>
<pre><code>package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"time"
"github.com/lucavallin/yfirbord-grovepi/pkg/connections"
"github.com/lucavallin/yfirbord-grovepi/pkg/io"
"github.com/lucavallin/yfirbord-grovepi/pkg/sensors"
"github.com/lucavallin/yfirbord-grovepi/pkg/sensors/parsers"
)
const (
grovePiAddress = 0x04
secondsWait = 360
)
// config should have pinNumber -> sensors, in a way that sensors are mapped to pins
var loadedSensors map[string][]sensors.Sensor
func main() {
// Load sensors
config, err := ioutil.ReadFile("./sensors.json")
if err != nil {
fmt.Printf("Sensors configuration file not found.\nERROR: %s \n", err)
os.Exit(1)
}
if json.Unmarshal(config, &loadedSensors); err != nil {
fmt.Printf("Sensors configuration is invalid.\nERROR: %s \n", err)
os.Exit(1)
}
// Init GrovePi on address
g, err := connections.NewGrovePi(grovePiAddress)
if err != nil {
fmt.Printf("Couldn't create connection with device.\nERROR: %s \n", err)
os.Exit(1)
}
defer g.Close()
// Create readers
reader := io.NewReader(parsers.GetParsers(), g)
// Create channel
c := make(chan parsers.Measurement)
// Start reading!
for _, sensor := range loadedSensors["input"] {
// Go read the sensor every 5 minutes
go func(r *io.Reader, s sensors.Sensor, c chan<- parsers.Measurement) {
for {
measurement, err := r.Read(s)
if err != nil {
log.Panicln(err)
} else {
c <- measurement
}
// Read every secondsWait minutes
time.Sleep(time.Second * secondsWait)
}
}(reader, sensor, c)
}
// Create API manager
// Print out
go func(c chan parsers.Measurement) {
measurement := <-c
for item, measure := range measurement {
fmt.Printf("%s: %v\n", item, measure)
}
}(c)
time.Sleep(time.Minute)
}
</code></pre>
<p>Nothing is printed :|</p>
<hr/>**评论:**<br/><br/>JHunz: <pre><p>If that's your whole code, your problem is probably that there's nothing blocking in the main thread. Goroutines terminate when the main thread does, which it will because it has nothing to do after launching the goroutines.</p></pre>theGeekPirate: <pre><p><a href="https://youtu.be/f6kdp27TYZs?t=456" rel="nofollow">This</a> will explain everything.</p>
<p>main() does not wait for all goroutines to finish before exiting the program.</p></pre>epiris: <pre><p>You might find sync.errgroup useful for waiting for your goroutines to finish. It's essentially a more convenient WaitGroup.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传