From 978f47a1c54a947e5475d2b8864179c78222cfb7 Mon Sep 17 00:00:00 2001 From: Florian Thienel Date: Sun, 26 Sep 2021 14:26:07 +0200 Subject: [PATCH] add method to COM to shutdown gracefully --- com/com.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/com/com.go b/com/com.go index 8d2321e..44dc4d4 100644 --- a/com/com.go +++ b/com/com.go @@ -26,6 +26,7 @@ func New(device io.ReadWriter) *COM { commands := make(chan command) result := &COM{ commands: commands, + closing: make(chan struct{}), closed: make(chan struct{}), indications: make(map[string]indicationConfig), } @@ -43,6 +44,8 @@ func New(device io.ReadWriter) *COM { for { select { + case <-result.closing: + return case line, valid := <-lines: if !valid { return @@ -102,6 +105,7 @@ func New(device io.ReadWriter) *COM { // COM allows to communicate with a radio's PEI using AT commands. type COM struct { commands chan<- command + closing chan struct{} closed chan struct{} tracer io.Writer @@ -148,6 +152,14 @@ func readLoop(r io.Reader) <-chan string { return lines } +func (c *COM) Close() { + select { + case <-c.closing: + default: + close(c.closing) + } +} + func (c *COM) Closed() bool { select { case <-c.closed: @@ -157,6 +169,13 @@ func (c *COM) Closed() bool { } } +func (c *COM) WaitUntilClosed(ctx context.Context) { + select { + case <-c.closed: + case <-ctx.Done(): + } +} + func (c *COM) AddIndication(prefix string, trailingLines int, handler func(lines []string)) error { config := indicationConfig{ prefix: strings.ToUpper(prefix),