From 0d263179b47429f738ddf775745c894a508d4e7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Rudowicz?= Date: Tue, 13 Feb 2024 23:20:15 +0100 Subject: [PATCH] FilterByType() --- filters.go | 23 +++++++++++++++++++++++ filters_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 filters.go create mode 100644 filters_test.go diff --git a/filters.go b/filters.go new file mode 100644 index 0000000..62b78f0 --- /dev/null +++ b/filters.go @@ -0,0 +1,23 @@ +package main + +import ( + "github.com/probakowski/go-satel" +) + +func FilterByType(ev <-chan satel.Event, allowedTypes []satel.ChangeType) <-chan satel.Event { + returnChan := make(chan satel.Event) + + go func() { + for e := range ev { + for _, allowedType := range allowedTypes { + if allowedType == e.Type { + returnChan <- e + continue + } + } + } + close(returnChan) + }() + + return returnChan +} diff --git a/filters_test.go b/filters_test.go new file mode 100644 index 0000000..b36f4dd --- /dev/null +++ b/filters_test.go @@ -0,0 +1,37 @@ +package main + +import ( + "sync" + "testing" + + "github.com/probakowski/go-satel" + "github.com/stretchr/testify/assert" +) + +func TestSatelEventTypeFiltering(t *testing.T) { + testEvents := make(chan satel.Event) + receivedEvents := make([]satel.Event, 0) + wg := sync.WaitGroup{} + + go func() { + wg.Add(1) + for e := range FilterByType(testEvents, []satel.ChangeType{satel.ArmedPartition, satel.PartitionFireAlarm}) { + receivedEvents = append(receivedEvents, e) + } + wg.Done() + }() + + testEvents <- satel.Event{Type: satel.ArmedPartition, Index: 1, Value: true} + testEvents <- satel.Event{Type: satel.DoorOpened, Index: 2, Value: true} + testEvents <- satel.Event{Type: satel.PartitionAlarm, Index: 3, Value: true} + testEvents <- satel.Event{Type: satel.PartitionFireAlarm, Index: 4, Value: true} + testEvents <- satel.Event{Type: satel.TroublePart1, Index: 5, Value: true} + testEvents <- satel.Event{Type: satel.ZoneTamper, Index: 6, Value: true} + + close(testEvents) + wg.Wait() + + assert.Len(t, receivedEvents, 2) + assert.Contains(t, receivedEvents, satel.Event{Type: satel.ArmedPartition, Index: 1, Value: true}) + assert.Contains(t, receivedEvents, satel.Event{Type: satel.PartitionFireAlarm, Index: 4, Value: true}) +}