1
0

inital commit

This commit is contained in:
2023-10-15 19:12:06 +02:00
commit 873ecb87db
7 changed files with 137 additions and 0 deletions

73
main.go Normal file
View File

@@ -0,0 +1,73 @@
package main
import (
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"time"
"os/exec"
"os"
"flag"
)
//mqtt Event listener
var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
RecievedPayload := string(msg.Payload())
cmd := exec.Command("ir-ctl","-S" + RecievedPayload)
out, err := cmd.Output()
if err != nil {
fmt.Println("could not run command: ", err)
}
fmt.Println("Output: ", string(out))
}
var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
fmt.Println("Connected")
}
var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
fmt.Printf("Connect lost: %v", err)
}
func main() {
//Set variables
var DeviceName string
var broker = "192.168.1.4"
var port = 1883
var CoreTopic = "KodiIR"
//Get the hostname as sane default for mqtt topic/device id
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
//innput flag -DeviceName
flag.StringVar(&DeviceName, "DeviceName", hostname, "The name that will be used as the topic an mqtt DeviceID")
flag.Parse()
//Set Mqtt Client options
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
opts.SetClientID(DeviceName)
opts.SetDefaultPublishHandler(messagePubHandler)
opts.SetWill(CoreTopic + "/" + DeviceName + "/status", "Offline", 0, true)
opts.OnConnect = connectHandler
opts.OnConnectionLost = connectLostHandler
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
//Subscribe to command toptic
client.Subscribe(CoreTopic + "/" + DeviceName + "/cmd", 1, nil).Wait()
//Publish connect msg
client.Publish(CoreTopic + "/" + DeviceName + "/status", 0, true, "Online")
//Print status
fmt.Printf("Mqtt subscribed")
//Loop so the program keeps running
for {
time.Sleep(time.Hour)
}
//Publish disconnect msg
client.Publish(CoreTopic + "/" + DeviceName + "/status", 0, true, "Offline")
client.Disconnect(250)
}