dhcp4d: Add vendor Identifier to mqtt

Add username and password for mqtt server
This commit is contained in:
lordwelch 2022-05-01 18:56:51 -07:00
parent c5a72342f2
commit 9c800af52e
3 changed files with 29 additions and 9 deletions

View File

@ -435,13 +435,17 @@ func newSrv(permDir string) (*srv, error) {
// Publish the DHCP lease as JSON to MQTT, if configured:
leaseVal := struct {
Addr string `json:"addr"`
HardwareAddr string `json:"hardware_addr"`
Expiration time.Time `json:"expiration"`
Addr string `json:"addr"`
HardwareAddr string `json:"hardware_addr"`
Expiration time.Time `json:"expiration"`
Start time.Time `json:"start"`
VendorIdentifier string `json:"vendor_identifier"`
}{
Addr: latest.Addr.String(),
HardwareAddr: latest.HardwareAddr,
Expiration: latest.Expiry.In(time.UTC),
Addr: latest.Addr.String(),
HardwareAddr: latest.HardwareAddr,
Expiration: latest.Expiry.In(time.UTC),
Start: latest.Start.In(time.UTC),
VendorIdentifier: latest.VendorIdentifier,
}
leaseJSON, err := json.Marshal(leaseVal)
if err != nil {

View File

@ -3,6 +3,7 @@ package main
import (
"fmt"
"io/ioutil"
"path"
"strings"
mqtt "github.com/eclipse/paho.mqtt.golang"
@ -16,7 +17,7 @@ type PublishRequest struct {
}
func publisherLoop(requests <-chan PublishRequest) error {
const configFn = "/perm/dhcp4d/mqtt-broker.txt"
configFn := path.Join(*perm, "/dhcp4d/mqtt-broker.txt")
b, err := ioutil.ReadFile(configFn)
if err != nil {
// discard requests:
@ -24,11 +25,26 @@ func publisherLoop(requests <-chan PublishRequest) error {
}
return nil
}
var (
broker string
username string
password string
)
cfg := strings.Split(string(b), "\n")
// e.g. tcp://10.0.0.54:1883, which is a static DHCP lease for the dr.lan
// Raspberry Pi, which is running an MQTT broker in my network.
broker := strings.TrimSpace(string(b))
broker = strings.TrimSpace(cfg[0])
if len(cfg) > 1 {
username = cfg[1]
}
if len(cfg) > 2 {
password = cfg[2]
}
log.Printf("Connecting to MQTT broker %q (configured in %s)", broker, configFn)
opts := mqtt.NewClientOptions().AddBroker(broker)
opts.SetUsername(username)
opts.SetPassword(password)
opts.SetClientID("dhcp4d")
opts.SetConnectRetry(true)
mqttClient := mqtt.NewClient(opts)

View File

@ -345,7 +345,7 @@ func (h *Handler) serveDHCP(p dhcp4.Packet, msgType dhcp4.MessageType, options d
Expiry: now.Add(h.leasePeriodForDevice(hwAddr)),
Hostname: string(options[dhcp4.OptionHostName]),
Start: now,
VendorIdentifier: string(options[dhcp4.OptionVendorClassIdentifier]),
VendorIdentifier: string(bytes.ToValidUTF8(bytes.ReplaceAll(options[dhcp4.OptionVendorClassIdentifier], []byte{0}, []byte{}), []byte{})),
}
copy(lease.Addr, reqIP.To4())