I have this method that I want to read the buffer until it reaches the prompt. It works fine when the prompt available in the output but I don't know how can I tell when the end of the buffer is reached.
Also, I want to add a timeout in case the device didn't respond.
func (device *Device) readUntil(pattern string) (*string, error) {
stdoutBuf := make([]byte, 65*1024)
output := ""
var validID = regexp.MustCompile(pattern)
for {
byteCount, err := device.reader.Read(stdoutBuf)
if err != nil {
log.Println("Reader read err:%s", err.Error())
break
}
output += string(stdoutBuf[:byteCount])
//fmt.Println(byteCount, err, io.EOF)
if validID.MatchString(string(stdoutBuf[:byteCount])) {
return &output, nil
}
}
return &output, nil
}
You can use a ticker in a select loop to break from your loop
func (device *Device) readUntil(pattern string) (*string, error) {
stdoutBuf := make([]byte, 65*1024)
output := ""
var validID = regexp.MustCompile(pattern)
timeout := time.After(1 * time.Second)
for {
select {
case <-timeout:
return nil, errors.New("error timeout")
default:
byteCount, err := device.reader.Read(stdoutBuf)
if err != nil {
log.Println("Reader read err:%s", err.Error())
break
}
output += string(stdoutBuf[:byteCount])
//fmt.Println(byteCount, err, io.EOF)
if validID.MatchString(string(stdoutBuf[:byteCount])) {
return &output, nil
}
}
}
return &output, nil
}