aboutsummaryrefslogtreecommitdiff
path: root/cmd/catbus-actuator-wakeonlan/main.go
blob: 6f4e62b927a304b4b44e0bb8039c284b9fc941b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// SPDX-FileCopyrightText: 2020 Ethel Morgan
//
// SPDX-License-Identifier: MIT

package main

import (
	"context"
	"flag"
	"log"

	"go.eth.moe/catbus-wakeonlan/catbus"
	"go.eth.moe/catbus-wakeonlan/config"
	"go.eth.moe/catbus-wakeonlan/logger"
	"go.eth.moe/catbus-wakeonlan/wakeonlan"
)

var (
	configPath = flag.String("config-path", "", "path to config")
)

func main() {
	flag.Parse()

	if *configPath == "" {
		log.Fatal("must set -config-path")
	}

	log, _ := logger.FromContext(context.Background())

	config, err := config.ParseFile(*configPath)
	if err != nil {
		log.AddField("config-path", *configPath)
		log.WithError(err).Fatal("could not parse config file")
	}

	log.AddField("broker-uri", config.BrokerURI)

	catbusOptions := catbus.ClientOptions{
		DisconnectHandler: func(_ *catbus.Client, err error) {
			log := log
			if err != nil {
				log = log.WithError(err)
			}
			log.Error("disconnected from MQTT broker")
		},
		ConnectHandler: func(client *catbus.Client) {
			log.Info("connected to MQTT broker")

			for topic := range config.MACsByTopic {
				err := client.Subscribe(topic, func(_ *catbus.Client, msg catbus.Message) {
					if string(msg.Payload()) != "on" {
						return
					}
					mac, ok := config.MACsByTopic[msg.Topic()]
					if !ok {
						return
					}

					log.AddField("mac", mac)
					log.AddField("topic", topic)
					if err := wakeonlan.Wake(mac); err != nil {
						log.WithError(err).Error("could not send wake-on-lan packet")
						return
					}
					log.Info("sent wake-on-lan packet")
				})
				if err != nil {
					log := log.WithError(err)
					log.AddField("topic", topic)
					log.Error("could not subscribe to MQTT topic")
				}
			}
		},
	}

	catbusOptions.RebroadcastDefaults = map[string][]byte{}
	for topic := range config.MACsByTopic {
		catbusOptions.RebroadcastDefaults[topic] = []byte("off")
	}

	catbus := catbus.NewClient(config.BrokerURI, catbusOptions)

	if err := catbus.Connect(); err != nil {
		log.WithError(err).Fatal("could not connect to MQTT broker")
	}
}