aboutsummaryrefslogtreecommitdiff
path: root/config/config.go
diff options
context:
space:
mode:
Diffstat (limited to 'config/config.go')
-rw-r--r--config/config.go66
1 files changed, 66 insertions, 0 deletions
diff --git a/config/config.go b/config/config.go
new file mode 100644
index 0000000..2d19506
--- /dev/null
+++ b/config/config.go
@@ -0,0 +1,66 @@
+package config
+
+import (
+ "encoding/json"
+ "io/ioutil"
+ "net"
+)
+
+type (
+ Config struct {
+ Broker string
+
+ MACsByTopic map[string]net.HardwareAddr
+ }
+
+ config struct {
+ MQTTBroker string `json:"mqttBroker"`
+ Devices map[string]struct {
+ MAC mac `json:"mac"`
+ Topic string `json:"topic"`
+ } `json:"devices"`
+ }
+
+ mac struct {
+ net.HardwareAddr
+ }
+)
+
+func ParseFile(path string) (*Config, error) {
+ bytes, err := ioutil.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+
+ raw := config{}
+ if err := json.Unmarshal(bytes, &raw); err != nil {
+ return nil, err
+ }
+
+ return configFromConfig(raw), nil
+}
+
+func configFromConfig(raw config) *Config {
+ c := &Config{
+ Broker: raw.MQTTBroker,
+ MACsByTopic: map[string]net.HardwareAddr{},
+ }
+
+ for _, v := range raw.Devices {
+ c.MACsByTopic[v.Topic] = v.MAC.HardwareAddr
+ }
+
+ return c
+}
+
+func (m mac) MarshalText() ([]byte, error) {
+ return []byte(m.String()), nil
+}
+func (m *mac) UnmarshalText(raw []byte) error {
+ mm, err := net.ParseMAC(string(raw))
+ if err != nil {
+ return err
+ }
+ m.HardwareAddr = mm
+ return nil
+}