Skip to content

Avoid race conditions when reading from serial #127

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 12, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 23 additions & 13 deletions bufferflow_timed.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type BufferflowTimed struct {
Port string
Output chan []byte
Input chan string
done chan bool
ticker *time.Ticker
}

Expand All @@ -23,22 +24,31 @@ func (b *BufferflowTimed) Init() {
log.Println("Initting timed buffer flow (output once every 16ms)")
bufferedOutput = ""

go func() {
for data := range b.Input {
bufferedOutput = bufferedOutput + data
}
}()

go func() {
b.ticker = time.NewTicker(16 * time.Millisecond)
for _ = range b.ticker.C {
if bufferedOutput != "" {
m := SpPortMessage{bufferedOutput}
buf, _ := json.Marshal(m)
b.Output <- []byte(buf)
bufferedOutput = ""
b.done = make(chan bool)
Loop:
for {
select {
case data := <-b.Input:
bufferedOutput = bufferedOutput + data
case <-b.ticker.C:
if bufferedOutput != "" {
m := SpPortMessage{bufferedOutput}
buf, _ := json.Marshal(m)
// data is now encoded in base64 format
// need a decoder on the other side
b.Output <- []byte(buf)
bufferedOutput = ""
}
case <-b.done:
break Loop
}
}

close(b.Input)
close(b.done)

}()

}
Expand Down Expand Up @@ -97,5 +107,5 @@ func (b *BufferflowTimed) IsBufferGloballySendingBackIncomingData() bool {

func (b *BufferflowTimed) Close() {
b.ticker.Stop()
close(b.Input)
b.done <- true
}