97 lines
2.1 KiB
Go
97 lines
2.1 KiB
Go
|
package logfile
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"os"
|
||
|
|
||
|
"github.com/go-flucky/flucky/pkg/types"
|
||
|
)
|
||
|
|
||
|
type jsonLogfile struct {
|
||
|
logfile string
|
||
|
}
|
||
|
|
||
|
func (jl *jsonLogfile) GetLogfile() string {
|
||
|
return jl.logfile
|
||
|
}
|
||
|
|
||
|
func (jl *jsonLogfile) ReadHumidities() ([]*types.Humidity, error) {
|
||
|
if _, err := os.Stat(jl.logfile); os.IsNotExist(err) {
|
||
|
return nil, fmt.Errorf("%v: %v", ErrLogfileNotFound, jl.logfile)
|
||
|
}
|
||
|
|
||
|
humidities := make([]*types.Humidity, 0)
|
||
|
|
||
|
f, err := os.Open(jl.logfile)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("%v: %v", ErrLogfileOpen, jl.logfile)
|
||
|
}
|
||
|
defer f.Close()
|
||
|
|
||
|
jsonDecoder := json.NewDecoder(f)
|
||
|
err = jsonDecoder.Decode(&humidities)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("%v: %v", ErrLogfileDecode, err)
|
||
|
}
|
||
|
|
||
|
return humidities, nil
|
||
|
}
|
||
|
|
||
|
func (jl *jsonLogfile) ReadTemperatures() ([]*types.Temperature, error) {
|
||
|
if _, err := os.Stat(jl.logfile); os.IsNotExist(err) {
|
||
|
return nil, fmt.Errorf("%v: %v", ErrLogfileNotFound, jl.logfile)
|
||
|
}
|
||
|
|
||
|
temperatures := make([]*types.Temperature, 0)
|
||
|
|
||
|
f, err := os.Open(jl.logfile)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("%v: %v", ErrLogfileOpen, jl.logfile)
|
||
|
}
|
||
|
defer f.Close()
|
||
|
|
||
|
jsonDecoder := json.NewDecoder(f)
|
||
|
err = jsonDecoder.Decode(&temperatures)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("%v: %v", ErrLogfileDecode, err)
|
||
|
}
|
||
|
|
||
|
return temperatures, nil
|
||
|
}
|
||
|
|
||
|
func (jl *jsonLogfile) WriteHumidities(humidities []*types.Humidity) error {
|
||
|
|
||
|
f, err := os.Create(jl.logfile)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("%v: %v", ErrLogileCreate, jl.logfile)
|
||
|
}
|
||
|
defer f.Close()
|
||
|
|
||
|
jsonEncoder := json.NewEncoder(f)
|
||
|
jsonEncoder.SetIndent("", " ")
|
||
|
err = jsonEncoder.Encode(humidities)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("%v: %v", ErrLogfileEncode, err)
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (jl *jsonLogfile) WriteTemperatures(temperatures []*types.Temperature) error {
|
||
|
f, err := os.Create(jl.logfile)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("%v: %v", ErrLogileCreate, jl.logfile)
|
||
|
}
|
||
|
defer f.Close()
|
||
|
|
||
|
writeCreationDate(temperatures)
|
||
|
|
||
|
jsonEncoder := json.NewEncoder(f)
|
||
|
jsonEncoder.SetIndent("", " ")
|
||
|
err = jsonEncoder.Encode(temperatures)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("%v: %v", ErrLogfileEncode, err)
|
||
|
}
|
||
|
return nil
|
||
|
}
|