PKGBUILD/pkg/logfile/xml.go

125 lines
2.7 KiB
Go
Raw Normal View History

package logfile
import (
"encoding/xml"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/go-flucky/flucky/pkg/types"
)
type xmlLogfile struct {
logfile string
}
func (xl *xmlLogfile) GetLogfile() string {
return xl.logfile
}
func (xl *xmlLogfile) ReadHumidities() ([]*types.Humidity, error) {
if _, err := os.Stat(xl.logfile); os.IsNotExist(err) {
2019-06-21 09:48:44 +00:00
return nil, fmt.Errorf("%v: %v", errorLogfileNotFound, xl.logfile)
}
humidities := make([]*types.Humidity, 0)
f, err := os.Open(xl.logfile)
if err != nil {
2019-06-21 09:48:44 +00:00
return nil, fmt.Errorf("%v: %v", errorLogfileOpen, xl.logfile)
}
defer f.Close()
xmlDecoder := xml.NewDecoder(f)
err = xmlDecoder.Decode(&humidities)
if err != nil {
2019-06-21 09:48:44 +00:00
return nil, fmt.Errorf("%v: %v", errorLogfileDecode, err)
}
return humidities, nil
}
func (xl *xmlLogfile) ReadTemperatures() ([]*types.Temperature, error) {
if _, err := os.Stat(xl.logfile); os.IsNotExist(err) {
2019-06-21 09:48:44 +00:00
return nil, fmt.Errorf("%v: %v", errorLogfileNotFound, xl.logfile)
}
f, err := os.Open(xl.logfile)
if err != nil {
2019-06-21 09:48:44 +00:00
return nil, fmt.Errorf("%v: %v", errorLogfileOpen, xl.logfile)
}
defer f.Close()
bytes, err := ioutil.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("%v: %v", errorLogfileRead, err)
}
tmpTemperatures := new(Temperatures)
err = xml.Unmarshal(bytes, tmpTemperatures)
if err != nil {
return nil, fmt.Errorf("%v: %v", errorLogfileUnmarshal, err)
}
log.Println(len(tmpTemperatures.Temperatures))
temperatures := make([]*types.Temperature, 0)
for _, tmpTemperature := range tmpTemperatures.Temperatures {
temperatures = append(temperatures, tmpTemperature.Temperature)
}
return temperatures, nil
}
func (xl *xmlLogfile) WriteHumidities(humidities []*types.Humidity) error {
f, err := os.Create(xl.logfile)
if err != nil {
2019-06-21 09:48:44 +00:00
return fmt.Errorf("%v: %v", errorLogfileCreate, xl.logfile)
}
defer f.Close()
xmlEncoder := xml.NewEncoder(f)
xmlEncoder.Indent("", " ")
err = xmlEncoder.Encode(humidities)
if err != nil {
2019-06-21 09:48:44 +00:00
return fmt.Errorf("%v: %v", errorLogfileEncode, err)
}
return nil
}
func (xl *xmlLogfile) WriteTemperatures(temperatures []*types.Temperature) error {
f, err := os.Create(xl.logfile)
if err != nil {
2019-06-21 09:48:44 +00:00
return fmt.Errorf("%v: %v", errorLogfileCreate, xl.logfile)
}
defer f.Close()
writeCreationDate(temperatures)
tmpTemperatures := new(Temperatures)
for _, temperature := range temperatures {
tmpTemperature := &Temperature{
Temperature: temperature,
}
tmpTemperatures.Temperatures = append(tmpTemperatures.Temperatures, tmpTemperature)
}
bytes, err := xml.MarshalIndent(tmpTemperatures, "", " ")
if err != nil {
return fmt.Errorf("%v: %v", errorLogfileMarshal, err)
}
_, err = f.Write(bytes)
if err != nil {
return fmt.Errorf("%v: %v", errorLogfileWrite, err)
}
return nil
}