/
sensor.go
268 lines (240 loc) · 7.19 KB
/
sensor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package plantowerpms5003
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"time"
coreio "github.com/go-sensors/core/io"
"github.com/go-sensors/core/pm"
"github.com/go-sensors/core/units"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
)
// Sensor represents a configured Plantower PMS5003 particulate matter sensor
type Sensor struct {
concentrations chan *pm.Concentration
portFactory coreio.PortFactory
reconnectTimeout time.Duration
errorHandlerFunc ShouldTerminate
}
// Option is a configured option that may be applied to a Sensor
type Option struct {
apply func(*Sensor)
}
type ChecksumError struct {
Bytes []byte
ReportedChecksum uint16
ActualChecksum uint16
}
func (ce *ChecksumError) Error() string {
return fmt.Sprintf("checksum of measurement %v was reported as %v, but calculated as %v",
ce.Bytes,
ce.ReportedChecksum,
ce.ActualChecksum)
}
// NewSensor creates a Sensor with optional configuration
func NewSensor(portFactory coreio.PortFactory, options ...*Option) *Sensor {
concentrations := make(chan *pm.Concentration)
s := &Sensor{
concentrations: concentrations,
portFactory: portFactory,
reconnectTimeout: DefaultReconnectTimeout,
errorHandlerFunc: nil,
}
for _, o := range options {
o.apply(s)
}
return s
}
// WithReconnectTimeout specifies the duration to wait before reconnecting after a recoverable error
func WithReconnectTimeout(timeout time.Duration) *Option {
return &Option{
apply: func(s *Sensor) {
s.reconnectTimeout = timeout
},
}
}
// ReconnectTimeout is the duration to wait before reconnecting after a recoverable error
func (s *Sensor) ReconnectTimeout() time.Duration {
return s.reconnectTimeout
}
// ShouldTerminate is a function that returns a result indicating whether the Sensor should terminate after a recoverable error
type ShouldTerminate func(error) bool
// WithRecoverableErrorHandler registers a function that will be called when a recoverable error occurs
func WithRecoverableErrorHandler(f ShouldTerminate) *Option {
return &Option{
apply: func(s *Sensor) {
s.errorHandlerFunc = f
},
}
}
// RecoverableErrorHandler a function that will be called when a recoverable error occurs
func (s *Sensor) RecoverableErrorHandler() ShouldTerminate {
return s.errorHandlerFunc
}
var (
// Header of a valid measurement
ReadingHeader = []byte{0x42, 0x4D}
)
const (
PM01_0UpperBoundSize = 1 * units.Micrometer
PM02_5UpperBoundSize = 2_500 * units.Nanometer
PM10_0UpperBoundSize = 10 * units.Micrometer
)
type measurement struct {
// Frame length
Length uint16
// PM1.0 concentration unit μ g/m3 (CF=1,standard particle)
Pm10Std uint16
// PM2.5 concentration unit μ g/m3 (CF=1,standard particle)
Pm25Std uint16
// PM10 concentration unit μ g/m3 (CF=1,standard particle)
Pm100Std uint16
// PM1.0 concentration unit μ g/m3 (under atmospheric environment)
Pm10Env uint16
// PM2.5 concentration unit μ g/m3 (under atmospheric environment)
Pm25Env uint16
// PM10 concentration unit μ g/m3 (under atmospheric environment)
Pm100Env uint16
// Number of particles with diameter beyond 0.3 um in 0.1L of air.
Particles3um uint16
// Number of particles with diameter beyond 0.5 um in 0.1L of air.
Particles5um uint16
// Number of particles with diameter beyond 1.0 um in 0.1L of air.
Particles10um uint16
// Number of particles with diameter beyond 2.5 um in 0.1L of air.
Particles25um uint16
// Number of particles with diameter beyond 5.0 um in 0.1L of air.
Particles50um uint16
// Number of particles with diameter beyond 10.0 um in 0.1L of air.
Particles100um uint16
// Reserved
Unused uint16
// Check code
Checksum uint16
}
// Run begins reading from the sensor and blocks until either an error occurs or the context is completed
func (s *Sensor) Run(ctx context.Context) error {
defer close(s.concentrations)
for {
port, err := s.portFactory.Open()
if err != nil {
return errors.Wrap(err, "failed to open port")
}
group, innerCtx := errgroup.WithContext(ctx)
group.Go(func() error {
<-innerCtx.Done()
return port.Close()
})
group.Go(func() error {
reader := bufio.NewReader(port)
for {
nextHeaderIndex := 0
for {
b, err := reader.ReadByte()
if err != nil {
if err == io.EOF {
return err
}
return errors.Wrap(err, "failed to read while seeking measurement header")
}
if b == ReadingHeader[nextHeaderIndex] {
nextHeaderIndex++
if nextHeaderIndex == len(ReadingHeader) {
break
}
continue
}
nextHeaderIndex = 0
}
measurement := &measurement{}
err = binary.Read(reader, binary.BigEndian, measurement)
if err != nil {
return errors.Wrap(err, "failed to read measurement")
}
var bb bytes.Buffer
bb.Write(ReadingHeader)
binary.Write(&bb, binary.BigEndian, measurement)
expectedChecksum := uint16(0)
for _, b := range bb.Bytes()[:bb.Len()-2] {
expectedChecksum += uint16(b)
}
if measurement.Checksum != expectedChecksum {
if s.errorHandlerFunc != nil {
err := &ChecksumError{
Bytes: bb.Bytes(),
ReportedChecksum: measurement.Checksum,
ActualChecksum: expectedChecksum,
}
if s.errorHandlerFunc(err) {
return err
}
}
continue
}
concentrations := []*pm.Concentration{
{
UpperBoundSize: PM01_0UpperBoundSize,
Amount: units.MassConcentration(measurement.Pm10Env) * units.MicrogramPerCubicMeter,
},
{
UpperBoundSize: PM02_5UpperBoundSize,
Amount: units.MassConcentration(measurement.Pm25Env) * units.MicrogramPerCubicMeter,
},
{
UpperBoundSize: PM10_0UpperBoundSize,
Amount: units.MassConcentration(measurement.Pm100Env) * units.MicrogramPerCubicMeter,
},
}
for _, concentration := range concentrations {
select {
case <-innerCtx.Done():
return nil
case s.concentrations <- concentration:
}
}
}
})
err = group.Wait()
if s.errorHandlerFunc != nil {
if s.errorHandlerFunc(err) {
return err
}
}
select {
case <-ctx.Done():
return nil
case <-time.After(s.reconnectTimeout):
}
}
}
// Concentrations returns a channel of PM concentration readings as they become available from the sensor
func (s *Sensor) Concentrations() <-chan *pm.Concentration {
return s.concentrations
}
// ConcentrationSpecs returns a collection of specified measurement ranges supported by the sensor
func (*Sensor) ConcentrationSpecs() []*pm.ConcentrationSpec {
return []*pm.ConcentrationSpec{
{
UpperBoundSize: PM01_0UpperBoundSize,
Resolution: 1 * units.MicrogramPerCubicMeter,
MinConcentration: 0 * units.MicrogramPerCubicMeter,
MaxConcentration: 1000 * units.MicrogramPerCubicMeter,
},
{
UpperBoundSize: PM02_5UpperBoundSize,
Resolution: 1 * units.MicrogramPerCubicMeter,
MinConcentration: 0 * units.MicrogramPerCubicMeter,
MaxConcentration: 1000 * units.MicrogramPerCubicMeter,
},
{
UpperBoundSize: PM10_0UpperBoundSize,
Resolution: 1 * units.MicrogramPerCubicMeter,
MinConcentration: 0 * units.MicrogramPerCubicMeter,
MaxConcentration: 1000 * units.MicrogramPerCubicMeter,
},
}
}