PKGBUILD/pkg/logs/temperature.go

91 lines
1.9 KiB
Go
Raw Normal View History

2018-11-28 17:07:20 +00:00
package logs
import (
2018-11-29 19:03:42 +00:00
"encoding/json"
2018-11-28 17:07:20 +00:00
"fmt"
2018-11-29 19:03:42 +00:00
"io/ioutil"
2018-11-28 17:07:20 +00:00
"os"
"path/filepath"
stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
"git.cryptic.systems/fh-trier/go-flucky/pkg/types"
)
2018-11-29 19:03:42 +00:00
// AppendTemperature write a given array of temperatures to a logfile
func AppendTemperature(temperatures []*stypes.Temperature, cnf *types.Config) error {
2018-11-28 17:07:20 +00:00
2018-11-29 19:03:42 +00:00
tLog, err := ReadTemperatures(cnf.TemperatureLogfile)
if err != nil {
return err
}
tLog = append(tLog, temperatures...)
err = WriteTemperatures(tLog, cnf.TemperatureLogfile)
if err != nil {
return err
}
return nil
}
// FlushTemperatures ...
func FlushTemperatures(logFile string) error {
if err := ioutil.WriteFile(logFile, []byte(""), 0644); err != nil {
return err
}
return nil
}
// ReadTemperatures ...
func ReadTemperatures(logFile string) ([]*stypes.Temperature, error) {
logPath := filepath.Dir(logFile)
2018-11-28 17:07:20 +00:00
// create log dir if not exist
2018-11-29 19:03:42 +00:00
if _, err := os.Stat(logFile); os.IsNotExist(err) {
if _, err := os.Stat(logPath); os.IsNotExist(err) {
err := os.MkdirAll(logPath, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("Can not create directory: %v", err)
}
2018-11-28 17:07:20 +00:00
}
2018-11-29 19:03:42 +00:00
if err := FlushTemperatures(logFile); err != nil {
return nil, err
}
2018-11-28 17:07:20 +00:00
}
2018-11-29 19:03:42 +00:00
// open config file
jsonFile, err := os.Open(logFile)
2018-11-28 17:07:20 +00:00
if err != nil {
2018-11-29 19:03:42 +00:00
return nil, fmt.Errorf("Can not open file %v: %v", logFile, err)
2018-11-28 17:07:20 +00:00
}
2018-11-29 19:03:42 +00:00
defer jsonFile.Close()
2018-11-28 17:07:20 +00:00
2018-11-29 19:03:42 +00:00
bytes, err := ioutil.ReadAll(jsonFile)
if err != nil {
return nil, fmt.Errorf("Can not read jsonfile %v: %v", logFile, err)
2018-11-28 17:07:20 +00:00
}
2018-11-29 19:03:42 +00:00
temperatures := []*stypes.Temperature{}
json.Unmarshal(bytes, &temperatures)
return temperatures, nil
}
// WriteTemperatures ...
func WriteTemperatures(temperatures []*stypes.Temperature, logFile string) error {
bytes, err := json.Marshal(temperatures)
2018-11-28 17:07:20 +00:00
if err != nil {
2018-11-29 19:03:42 +00:00
return err
}
if err := ioutil.WriteFile(logFile, bytes, 0644); err != nil {
return err
2018-11-28 17:07:20 +00:00
}
return nil
}