@@ -95,12 +95,11 @@ type SpPortMessageRaw struct {
95
95
func (p * serport ) reader (buftype string ) {
96
96
97
97
//var buf bytes.Buffer
98
- ch := make ([]byte , 1024 )
99
98
timeCheckOpen := time .Now ()
100
99
var buffered_ch bytes.Buffer
101
100
102
101
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
104
103
n , err := p .portIo .Read (ch )
105
104
106
105
//if we detect that port is closing, break out of this for{} loop.
@@ -111,16 +110,11 @@ func (p *serport) reader(buftype string) {
111
110
break
112
111
}
113
112
114
- if err == nil {
115
- ch = append (buffered_ch .Bytes (), ch [:n ]... )
116
- n += len (buffered_ch .Bytes ())
117
- buffered_ch .Reset ()
118
- }
119
-
120
113
// 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 ]))
124
118
125
119
data := ""
126
120
switch buftype {
@@ -129,11 +123,15 @@ func (p *serport) reader(buftype string) {
129
123
p .bufferwatcher .OnIncomingData (data )
130
124
case "timedbinary" :
131
125
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 ()
133
131
for i , w := 0 , 0 ; i < n ; i += w {
134
132
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)
135
133
if runeValue == utf8 .RuneError {
136
- buffered_ch .Write (append ( ch [i :n ]) )
134
+ buffered_ch .Write (ch [i :n ])
137
135
break
138
136
}
139
137
if i == n {
@@ -146,7 +144,6 @@ func (p *serport) reader(buftype string) {
146
144
// to read/translate the data to see if it wants to block
147
145
// writes to the serialport. each bufferflow type will decide
148
146
// this on its own based on its logic, i.e. tinyg vs grbl vs others
149
- //p.b.bufferwatcher..OnIncomingData(data)
150
147
p .bufferwatcher .OnIncomingData (data )
151
148
default :
152
149
log .Panicf ("unknown buffer type %s" , buftype )
0 commit comments