github.com/serge-v/zero@v1.0.2-0.20220911142406-af4b6a19e68a/examples/chart/parser.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "net/http" 7 "strconv" 8 "strings" 9 "time" 10 ) 11 12 type record struct { 13 ts time.Time 14 moisture int 15 battery float64 16 hall int 17 } 18 19 func fetchSensorLog(fname string) ([]string, error) { 20 resp, err := http.Get("https://zero.voilokov.com/log/log?f=" + fname) 21 if err != nil { 22 return nil, fmt.Errorf("generate: %w", err) 23 } 24 defer resp.Body.Close() 25 26 buf, err := ioutil.ReadAll(resp.Body) 27 lines := strings.Split(string(buf), "\n") 28 return lines, nil 29 } 30 31 func parseLogLines(lines []string) ([]record, error) { 32 var list []record 33 34 for _, line := range lines { 35 cc := strings.Split(line, " ") 36 if len(cc) < 8 { 37 continue 38 } 39 40 var err error 41 var r record 42 43 timestr := cc[0] + " " + cc[1] + " " + cc[2] 44 r.ts, err = time.Parse("2006-01-02 15:04:05 MST", timestr) 45 if err != nil { 46 return nil, fmt.Errorf(": %w", err) 47 } 48 49 for _, c := range cc { 50 kv := strings.Split(c, ":") 51 if len(kv) != 2 { 52 continue 53 } 54 switch kv[0] { 55 case "moisture": 56 r.moisture, _ = strconv.Atoi(kv[1]) 57 case "hall": 58 r.hall, _ = strconv.Atoi(kv[1]) 59 case "batv": 60 r.battery, _ = strconv.ParseFloat(strings.TrimSuffix(kv[1], "V"), 64) 61 } 62 } 63 64 list = append(list, r) 65 } 66 return list, nil 67 }