-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_linescanner.go
65 lines (53 loc) · 1.01 KB
/
main_linescanner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"bufio"
"encoding/json"
"io"
"sync"
"time"
"github.com/alecthomas/participle/v2"
)
type Datum struct {
Value float64 `@Float`
}
func (d Datum) Int() int {
return int(d.Value)
}
func (d Datum) MarshalJSON() ([]byte, error) {
return json.Marshal(int(d.Value))
}
type Line struct {
Time time.Time
ID Datum `"[" @@ "]" ":"`
Data []Datum `( @@ "," )+`
}
var parser = participle.MustBuild[Line]()
type lineScanner struct {
mutex sync.RWMutex
clock clock
}
func newLineScanner() *lineScanner {
return &lineScanner{
clock: defaultClockInstance,
}
}
func (ls *lineScanner) scan(s io.ReadWriter, ch chan Line) error {
if _, err := s.Write([]byte("viewLog\r\n")); err != nil {
return err
}
scanner := bufio.NewScanner(s)
for scanner.Scan() {
if l := ls.parse(scanner.Text()); l != nil {
ch <- *l
}
}
return scanner.Err()
}
func (ls *lineScanner) parse(s string) *Line {
l, err := parser.ParseString("", s)
l.Time = ls.clock.Time()
if err == nil {
return l
}
return nil
}