Files

74 lines
1.6 KiB
Go

package robot
import (
"bytes"
"encoding/xml"
"errors"
"time"
)
type schedEntry struct {
Name string `xml:"n,attr"`
On string `xml:"o,attr"`
Time string `xml:"t,attr"`
Repeat string `xml:"r,attr"`
Flag string `xml:"f,attr"`
Action struct {
TD string `xml:"td,attr"`
Type string `xml:"type,attr"`
} `xml:"ctl"`
}
// parseSchedulesImpl implements ScheduleParser.
func ScheduleParserHook(inner []byte) ([]Schedule, error) {
if len(bytes.TrimSpace(inner)) == 0 {
return []Schedule{}, nil
}
// Because `inner` contains a sequence of `<s>...</s>` elements,
// we wrap it in a dummy root to use standard xml.Unmarshal.
wrapped := []byte("<root>")
wrapped = append(wrapped, inner...)
wrapped = append(wrapped, []byte("</root>")...)
var root struct {
Entries []schedEntry `xml:"s"`
}
if err := xml.Unmarshal(wrapped, &root); err != nil {
return nil, err
}
var schedules []Schedule
var errs []error
for _, entry := range root.Entries {
if entry.Action.Type != "auto" {
errs = append(errs, errors.New("unsupported schedule type: "+entry.Action.Type))
continue
}
s := Schedule{
Name: entry.Name,
On: entry.On == "1",
Time: entry.Time,
Repeat: entry.Repeat,
Flag: entry.Flag,
Action: ScheduleAction{
TD: entry.Action.TD,
Type: entry.Action.Type,
},
}
schedules = append(schedules, s)
}
var err error
if len(errs) > 0 {
err = errors.Join(errs...)
}
return schedules, err
}
// RepeatIndex returns the Sunday-first index for the given weekday.
func RepeatIndex(d time.Weekday) int {
return int(d)
}