Skip to content

Commit b7f70f1

Browse files
committed
enhanced a bit how the logic of the serial works
1 parent dfcc14e commit b7f70f1

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

serialport.go

+11-14
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,11 @@ type SpPortMessageRaw struct {
9595
func (p *serport) reader(buftype string) {
9696

9797
//var buf bytes.Buffer
98-
ch := make([]byte, 1024)
9998
timeCheckOpen := time.Now()
10099
var buffered_ch bytes.Buffer
101100

102101
for {
103-
102+
ch := make([]byte, 1024) //a new array of bytes is initilized everytime because we pass it (as a pointer) in a channel, it can be improved
104103
n, err := p.portIo.Read(ch)
105104

106105
//if we detect that port is closing, break out of this for{} loop.
@@ -111,16 +110,11 @@ func (p *serport) reader(buftype string) {
111110
break
112111
}
113112

114-
if err == nil {
115-
ch = append(buffered_ch.Bytes(), ch[:n]...)
116-
n += len(buffered_ch.Bytes())
117-
buffered_ch.Reset()
118-
}
119-
120113
// read can return legitimate bytes as well as an error
121-
// so process the n bytes if n > 0
122-
if n > 0 {
123-
log.Print("Read " + strconv.Itoa(n) + " bytes ch: " + string(ch))
114+
// so process the n bytes red, if n > 0
115+
if n > 0 && err == nil {
116+
117+
log.Print("Read " + strconv.Itoa(n) + " bytes ch: " + string(ch[:n]))
124118

125119
data := ""
126120
switch buftype {
@@ -129,11 +123,15 @@ func (p *serport) reader(buftype string) {
129123
p.bufferwatcher.OnIncomingData(data)
130124
case "timedbinary":
131125
p.bufferwatcher.OnIncomingDataBinary(ch[:n])
132-
case "default":
126+
case "default": // the bufferbuftype is actually called default 🤷‍♂️
127+
// save the left out bytes for the next iteration due to UTF-8 encoding
128+
ch = append(buffered_ch.Bytes(), ch[:n]...) // TODO ch is not handled correctly: doing this way it's length is messed up. Use ch2
129+
n += len(buffered_ch.Bytes())
130+
buffered_ch.Reset()
133131
for i, w := 0, 0; i < n; i += w {
134132
runeValue, width := utf8.DecodeRune(ch[i:n]) // try to decode the first i bytes in the buffer (UTF8 runes do not have a fixed lenght)
135133
if runeValue == utf8.RuneError {
136-
buffered_ch.Write(append(ch[i:n]))
134+
buffered_ch.Write(ch[i:n])
137135
break
138136
}
139137
if i == n {
@@ -146,7 +144,6 @@ func (p *serport) reader(buftype string) {
146144
// to read/translate the data to see if it wants to block
147145
// writes to the serialport. each bufferflow type will decide
148146
// this on its own based on its logic, i.e. tinyg vs grbl vs others
149-
//p.b.bufferwatcher..OnIncomingData(data)
150147
p.bufferwatcher.OnIncomingData(data)
151148
default:
152149
log.Panicf("unknown buffer type %s", buftype)

0 commit comments

Comments
 (0)