PKGBUILD/pkg/logfile/csv.go

133 lines
2.9 KiB
Go
Raw Normal View History

package logfile
import (
"encoding/csv"
"fmt"
"os"
"strconv"
"time"
"github.com/go-flucky/flucky/pkg/types"
)
type csvLogfile struct {
logfile string
}
func (cl *csvLogfile) Read() ([]*types.MeasuredValue, error) {
if _, err := os.Stat(cl.logfile); os.IsNotExist(err) {
return nil, fmt.Errorf("%v: %v", errorLogfileNotFound, cl.logfile)
}
f, err := os.Open(cl.logfile)
if err != nil {
return nil, fmt.Errorf("%v: %v", errorLogfileOpen, cl.logfile)
}
defer f.Close()
r := csv.NewReader(f)
records, err := r.ReadAll()
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorLogfileDecode, cl.logfile, err)
}
measuredValues := make([]*types.MeasuredValue, 0)
for _, record := range records {
// ValueType
valueType, err := types.SelectMeasuredValueType(record[1])
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseFloat, record[1], err)
}
// Value
value, err := strconv.ParseFloat(record[2], 64)
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseFloat, record[2], err)
}
// Times
times := make([]time.Time, 0)
for _, i := range []int{3, 4} {
time, err := time.Parse(timeFormat, record[i])
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseTime, record[i], err)
}
times = append(times, time)
}
measuredValue := &types.MeasuredValue{
ID: record[0],
ValueType: *valueType,
Value: value,
FromDate: times[0],
TillDate: times[1],
SensorID: record[5],
}
// Creation date
creationDate, err := time.Parse(timeFormat, record[6])
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseTime, record[6], err)
}
measuredValue.CreationDate = &creationDate
if record[7] != "null" {
updateDate, err := time.Parse(timeFormat, record[7])
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseTime, record[7], err)
}
measuredValue.UpdateDate = &updateDate
}
measuredValues = append(measuredValues, measuredValue)
}
return measuredValues, nil
}
func (cl *csvLogfile) Write(measuredValues []*types.MeasuredValue) error {
f, err := os.Create(cl.logfile)
if err != nil {
return fmt.Errorf("%v: %v", errorLogfileCreate, cl.logfile)
}
defer f.Close()
writeCreationDate(measuredValues)
w := csv.NewWriter(f)
for _, measuredValue := range measuredValues {
record := []string{
measuredValue.ID,
fmt.Sprintf("%v", measuredValue.ValueType),
fmt.Sprintf("%v", measuredValue.Value),
measuredValue.FromDate.Format(timeFormat),
measuredValue.TillDate.Format(timeFormat),
measuredValue.SensorID,
}
if measuredValue.CreationDate != nil {
record = append(record, measuredValue.CreationDate.Format(timeFormat))
} else {
record = append(record, "null")
}
if measuredValue.UpdateDate != nil {
record = append(record, measuredValue.UpdateDate.Format(timeFormat))
} else {
record = append(record, "null")
}
w.Write(record)
}
w.Flush()
return nil
}