dmesg-notify/main.go

74 lines
1.6 KiB
Go
Raw Normal View History

2021-07-08 20:04:37 +00:00
package main
import (
"fmt"
"log"
"os/exec"
"regexp"
"strings"
"time"
"github.com/euank/go-kmsg-parser/kmsgparser"
)
func notify(msg string) {
cmd := exec.Command("notify-send", "-t", "5000", "dmesg", msg)
err := cmd.Run()
if err != nil {
log.Println(err)
}
}
func main() {
parser, err := kmsgparser.NewParser()
if err != nil {
panic(err)
}
working := false
go func(){
time.Sleep(1 * time.Second)
working = true
}()
usbPattern := regexp.MustCompile("usb (\\d+-\\d+): (.*)")
usbManufacturer := map[string]string{}
usbProduct := map[string]string{}
for m := range parser.Parse() {
msg := ""
// log.Println("owo", m.Message)
if sm := usbPattern.FindStringSubmatch(m.Message); len(sm) > 0 {
addr := sm[1]
message := sm[2]
if strings.HasPrefix(message, "Manufacturer: ") {
usbManufacturer[addr] = message[14:]
}
if strings.HasPrefix(message, "Product: ") {
usbProduct[addr] = message[9:]
msg = fmt.Sprintf(
"New USB device: %s %s",
usbManufacturer[addr],
usbProduct[addr],
)
}
if strings.HasPrefix(message, "USB disconnect") {
msg = fmt.Sprintf(
"USB disconnect: %s %s",
usbManufacturer[addr],
usbProduct[addr],
)
}
}
if working && msg != "" {
notify(msg)
}
}
}