Skip to content

Commit

Permalink
Watchdog implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
joehil committed Mar 12, 2024
1 parent 3fd4c5d commit db380fa
Showing 1 changed file with 13 additions and 28 deletions.
41 changes: 13 additions & 28 deletions tibber2mqtt.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"net/http"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
Expand All @@ -23,7 +22,8 @@ import (
)

var do_trace bool = true
var bPanic bool = false

var counter uint64 = 0

var ownlog string
var jsonpath string
Expand Down Expand Up @@ -85,11 +85,7 @@ func main() {
if token := mclient.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
// getTibberPricesNew()
safeRun(getTibberPricesNew)
if bPanic {
panic("Program abend")
}
getTibberPricesNew()
os.Exit(0)
}
if a1 == "subPower" {
Expand All @@ -101,6 +97,7 @@ func main() {
if token := mclient.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
go watchDog()
getTibberSubUrl()
getTibberHomeId()
subTibberPower()
Expand Down Expand Up @@ -654,6 +651,8 @@ func subTibberPower() error {
token = mclient.Publish("tibber2mqtt/out/priceAvg", 0, false, fmt.Sprintf("%0.4f", priceAvg))
token.Wait()

counter++

return nil
})

Expand Down Expand Up @@ -693,28 +692,14 @@ func fileExists(filename string) bool {
return !info.IsDir()
}

func printStackTrace() {
buffer := make([]byte, 1024)
func watchDog() {
var old uint64 = counter
for {
n := runtime.Stack(buffer, false)
if n < len(buffer) {
buffer = buffer[:n]
break
time.Sleep(3 * time.Minute)
log.Printf("Watchdog counter: %d\n", counter)
if counter == old {
panic("Program seems to be frozen")
}
buffer = make([]byte, len(buffer)*2)
old = counter
}
fmt.Printf("Stack trace:\n%s\n", buffer)
}

func safeRun(f func()) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
printStackTrace()
fmt.Println("Wait for a minute")
time.Sleep(time.Minute)
bPanic = true
}
}()
f()
}

0 comments on commit db380fa

Please sign in to comment.