@@ -6,10 +6,14 @@ import "C"
6
6
7
7
import (
8
8
"bytes"
9
+ "context"
10
+ "errors"
9
11
"fmt"
10
12
"reflect"
11
13
"time"
12
14
"unsafe"
15
+
16
+ "github.com/d2r2/go-shell/shell"
13
17
)
14
18
15
19
type SensorType int
@@ -55,7 +59,7 @@ func dialDHTxxAndGetResponse(pin int, boostPerfFlag bool) ([]Pulse, error) {
55
59
// Return array: [pulse, duration, pulse, duration, ...]
56
60
r := C .dial_DHTxx_and_read (C .int32_t (pin ), boost , & arr , & arrLen )
57
61
if r == - 1 {
58
- err := fmt . Errorf ("Error during call C.dial_DHTxx_and_read()" )
62
+ err := errors . New ("Error during call C.dial_DHTxx_and_read()" )
59
63
return nil , err
60
64
}
61
65
defer C .free (unsafe .Pointer (arr ))
@@ -159,7 +163,7 @@ func decodeDHTxxPulses(sensorType SensorType, pulses []Pulse) (temperature float
159
163
return - 1 , - 1 , err
160
164
}
161
165
// Debug output for 5 bytes
162
- log .Debugf ("Five bytes from DHTxx: [%d, %d, %d, %d, %d]" , b0 , b1 , b2 , b3 , sum )
166
+ lg .Debugf ("Five bytes from DHTxx: [%d, %d, %d, %d, %d]" , b0 , b1 , b2 , b3 , sum )
163
167
// Extract temprature and humidity depending on sensor type
164
168
temperature , humidity = 0.0 , 0.0
165
169
if sensorType == DHT11 {
@@ -186,7 +190,7 @@ func printPulseArrayForDebug(pulses []Pulse) {
186
190
buf .WriteString (fmt .Sprintf ("pulse %3d: %v, %v\n " , i ,
187
191
pulse .Value , pulse .Duration ))
188
192
}
189
- log .Debugf ("Pulse count %d:\n %v" , len (pulses ), buf .String ())
193
+ lg .Debugf ("Pulse count %d:\n %v" , len (pulses ), buf .String ())
190
194
}
191
195
192
196
// Send activation request to DHTxx sensor via specific pin.
@@ -238,17 +242,25 @@ func ReadDHTxx(sensorType SensorType, pin int,
238
242
// 4) error if present.
239
243
func ReadDHTxxWithRetry (sensorType SensorType , pin int , boostPerfFlag bool ,
240
244
retry int ) (temperature float32 , humidity float32 , retried int , err error ) {
245
+ ctx , cancel := context .WithCancel (context .Background ())
246
+ shell .CloseContextOnKillSignal (cancel )
241
247
retried = 0
242
248
for {
243
249
temp , hum , err := ReadDHTxx (sensorType , pin , boostPerfFlag )
244
250
if err != nil {
245
251
if retry > 0 {
246
- log . Warningf ( "%v" , err )
252
+ lg . Warning ( err )
247
253
retry --
248
254
retried ++
249
- // Sleep before new attempt
250
- time .Sleep (1500 * time .Millisecond )
251
- continue
255
+ select {
256
+ case <- ctx .Done ():
257
+ // Interrupt loop, if pending termination
258
+ return - 1 , - 1 , retried , errors .New ("Termination pending..." )
259
+ default :
260
+ // Sleep before new attempt
261
+ time .Sleep (1500 * time .Millisecond )
262
+ continue
263
+ }
252
264
}
253
265
return - 1 , - 1 , retried , err
254
266
}
0 commit comments