Skip to content

Commit 09b1dbd

Browse files
authored
Merge pull request #13 from lazy-electron-consulting/idle-timeout
Idle timeout
2 parents b1dae73 + 49ce271 commit 09b1dbd

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

internal/exporter/exporter.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"fmt"
66
"sync"
77

8+
_ "net/http/pprof"
9+
810
"github.com/lazy-electron-consulting/victron-bluetooth/internal/exporter/prom"
911
"github.com/lazy-electron-consulting/victron-bluetooth/pkg/devices"
1012
"github.com/lazy-electron-consulting/victron-bluetooth/pkg/scanner"

pkg/scanner/scanner.go

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package scanner
33
import (
44
"context"
55
"fmt"
6+
"sync"
67
"time"
78

89
"github.com/lazy-electron-consulting/victron-bluetooth/pkg/scanner/idle"
@@ -36,16 +37,24 @@ func Run(ctx context.Context, h Handler) error {
3637
if err := adapter.Enable(); err != nil {
3738
return fmt.Errorf("adapter not enabled: %w", err)
3839
}
40+
var once sync.Once // StopScan is not re-entrant, ensure we only stop once
41+
stop := func() {
42+
once.Do(func() {
43+
if err := adapter.StopScan(); err != nil {
44+
slog.Error("failed to stop scan: ", err)
45+
}
46+
})
47+
}
48+
defer stop()
3949

4050
timer := idle.New(5 * time.Minute)
4151

4252
g, ctx := errgroup.WithContext(ctx)
4353

44-
g.Go(func() error { return timer.Run(ctx) })
45-
4654
g.Go(func() error {
47-
<-ctx.Done()
48-
return ctx.Err()
55+
defer slog.Warn("idle timer expired")
56+
defer stop()
57+
return timer.Run(ctx)
4958
})
5059

5160
g.Go(func() error {
@@ -68,10 +77,5 @@ func Run(ctx context.Context, h Handler) error {
6877

6978
slog.Info("scanning devices")
7079
defer slog.Info("stopped scanning")
71-
defer func() {
72-
if err := adapter.StopScan(); err != nil {
73-
slog.Error("failed to stop scan while shutting down", err)
74-
}
75-
}()
7680
return g.Wait()
7781
}

0 commit comments

Comments
 (0)