config.go 942 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package presence
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "time"
  7. "gopkg.in/yaml.v3"
  8. )
  9. type (
  10. MACAddress struct {
  11. net.HardwareAddr
  12. }
  13. Config struct {
  14. Interval time.Duration `yaml:"interval"`
  15. MACAddresses []MACAddress `yaml:"mac_addresses"`
  16. PingCount uint `yaml:"ping_count"`
  17. }
  18. )
  19. func ParseConfig(name string) (*Config, error) {
  20. f, err := os.Open(name)
  21. if err != nil {
  22. return nil, err
  23. }
  24. defer f.Close()
  25. d := yaml.NewDecoder(f)
  26. d.KnownFields(true)
  27. c := &Config{}
  28. err = d.Decode(c)
  29. if err != nil {
  30. return nil, err
  31. }
  32. if c.Interval < 0 {
  33. return nil, fmt.Errorf("negative interval (%v)", c.Interval)
  34. }
  35. if c.Interval == 0 {
  36. c.Interval = 30 * time.Second
  37. }
  38. if c.PingCount == 0 {
  39. c.PingCount = 1
  40. }
  41. return c, nil
  42. }
  43. func (a *MACAddress) UnmarshalYAML(value *yaml.Node) (err error) {
  44. var s string
  45. err = value.Decode(&s)
  46. if err != nil {
  47. return
  48. }
  49. a.HardwareAddr, err = net.ParseMAC(s)
  50. return
  51. }