Skip to content

Instantly share code, notes, and snippets.

@imduffy15
Created March 16, 2020 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imduffy15/2abc8d23b3ed6b297663f104299c43f9 to your computer and use it in GitHub Desktop.
Save imduffy15/2abc8d23b3ed6b297663f104299c43f9 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"github.com/eclipse/paho.mqtt.golang"
"github.com/hpcloud/tail"
"github.com/hpcloud/tail/watch"
"log"
"os"
"regexp"
"strings"
"time"
)
type MqttConfig struct {
Name string `json:"name"`
UniqueID string `json:"unique_id"`
StateTopic string `json:"state_topic"`
}
func main() {
watch.POLL_DURATION = 1 * time.Second
opts := mqtt.NewClientOptions().AddBroker("tcp://mqtt-broker:1883").SetClientID("magenta").SetUsername("MQTT USERNAME").SetPassword("MQTT PASSWORD")
c := mqtt.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
webcamPayload, _ := json.Marshal(&MqttConfig{Name: "Magenta Webcam", UniqueID: "magenta_webcam", StateTopic: "magenta/sensor/magenta_webcam/state"})
c.Publish("homeassistant/sensor/magenta_webcam/config", 0, false, webcamPayload)
re := regexp.MustCompile(`(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+) (?P<hour>\d+):(?P<minute>\d+):(?P<second>\d+) (?P<offset>[+-]\d+): (?P<device>\w+) device became (?P<status>\w+)`)
t, err := tail.TailFile("/Users/duffy/Library/Application Support/Objective-See/OverSight/OverSight.log", tail.Config{Follow: true, ReOpen: true, Poll: true, Location: &tail.SeekInfo{Offset: 0, Whence: os.SEEK_END}})
if err != nil {
log.Fatal(err)
}
defer t.Cleanup()
for line := range t.Lines {
text := strings.ToLower(line.Text)
log.Println(text)
match := re.FindStringSubmatch(text)
result := make(map[string]string)
for i, name := range re.SubexpNames() {
if i != 0 && name != "" {
result[name] = match[i]
}
}
log.Println(result["device"])
log.Println(result["status"])
if result["device"] == "video" {
log.Println("Handling video event")
if result["status"] == "active" {
c.Publish("magenta/sensor/magenta_webcam/state", 0, false, "ON")
} else {
c.Publish("magenta/sensor/magenta_webcam/state", 0, false, "OFF")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment