Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle "N/A" as valid value of the XOFFBATT field. Fixes #2. #3

Merged
merged 3 commits into from
Apr 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions status.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,19 +242,19 @@ func (s *Status) parseKVTime(k string, v string) (bool, error) {
var err error
switch k {
case keyDate:
s.Date, err = time.Parse(timeFormatLong, v)
s.Date, err = parseOptionalTime(timeFormatLong, v)
case keyStartTime:
s.StartTime, err = time.Parse(timeFormatLong, v)
s.StartTime, err = parseOptionalTime(timeFormatLong, v)
case keyXOnBat:
s.XOnBattery, err = time.Parse(timeFormatLong, v)
s.XOnBattery, err = parseOptionalTime(timeFormatLong, v)
case keyXOffBat:
s.XOffBattery, err = time.Parse(timeFormatLong, v)
s.XOffBattery, err = parseOptionalTime(timeFormatLong, v)
case keyLastStest:
s.LastSelftest, err = time.Parse(timeFormatLong, v)
s.LastSelftest, err = parseOptionalTime(timeFormatLong, v)
case keyBattDate:
s.BatteryDate, err = time.Parse(timeFormatShort, v)
s.BatteryDate, err = parseOptionalTime(timeFormatShort, v)
case keyEndAPC:
s.EndAPC, err = time.Parse(timeFormatLong, v)
s.EndAPC, err = parseOptionalTime(timeFormatLong, v)
default:
return false, nil
}
Expand Down Expand Up @@ -312,3 +312,15 @@ func parseDuration(d string) (time.Duration, error) {

return time.ParseDuration(fmt.Sprintf("%s%s", num, unit))
}

// parseOptionalTime parses a time string.
// In addition to the specified layout, it also accepts the special value "N/A"
// (which apcupsd reports for some values and conditions); this value is mapped
// to time.Time{}. The caller can check for this with time.IsZero().
func parseOptionalTime(layout, value string) (time.Time, error) {
if value == "N/A" {
return time.Time{}, nil
}

return time.Parse(layout, value)
}
7 changes: 7 additions & 0 deletions status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ func TestStatus_parseKV(t *testing.T) {
BatteryDate: time.Date(2016, time.September, 6, 0, 0, 0, 0, time.UTC),
},
},
{
desc: "N/A time.Time",
kv: "XOFFBATT : N/A",
s: &Status{
XOnBattery: time.Time{},
},
},
{
desc: "OK time.Duration",
kv: "TIMELEFT: 10.5 Minutes",
Expand Down