Skip to content

Commit

Permalink
Avoid race conditions when reading from serial
Browse files Browse the repository at this point in the history
  • Loading branch information
matteosuppo committed Oct 12, 2016
1 parent 244ca6b commit b771ce7
Showing 1 changed file with 23 additions and 13 deletions.
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
}

0 comments on commit b771ce7

Please sign in to comment.