-
Notifications
You must be signed in to change notification settings - Fork 0
/
thermometer.go
261 lines (230 loc) · 7.45 KB
/
thermometer.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
package main
import (
"errors"
"fmt"
"math"
"sync"
"time"
"github.com/brutella/hc/accessory"
)
const (
// nanoFarads is the value of capacitor used for measuring the thermistor
nanoFarads = 100
// minTime and maxTime are the expectations for how long it should take for the capacitor to discharge
minTime = time.Duration(nanoFarads) * time.Microsecond
maxTime = time.Duration(nanoFarads) / 10 * time.Millisecond
)
// Thermometer reads a thermal resistance thermometer using the timings of a capacitor charge/discharge cycle
type Thermometer interface {
Name() string
Temperature() float64
Update() error
Calibrate(float64) error
Accessory() *accessory.Accessory
}
// SelectiveThermometer filters out certain data from a Thermometer to produce a better reading
type SelectiveThermometer struct {
name string
filter func() bool
thermometer Thermometer
accessory *accessory.Thermometer
}
// NewSelectiveThermometer creates a SelectiveThermometer
func NewSelectiveThermometer(name string, manufacturer string, thermometer Thermometer,
filter func() bool) *SelectiveThermometer {
acc := accessory.NewTemperatureSensor(AccessoryInfo(name, manufacturer), 0.0, -20.0, 100.0, 1.0)
thermometer.Update()
acc.TempSensor.CurrentTemperature.SetValue(thermometer.Temperature())
return &SelectiveThermometer{
name: name,
thermometer: thermometer,
filter: filter,
accessory: acc,
}
}
// Name returns the name of the SelectiveThermometer
func (t *SelectiveThermometer) Name() string {
return t.name
}
// Calibrate runs a calibration operation the thermometer
func (t *SelectiveThermometer) Calibrate(a float64) error {
return errors.New("not supported")
}
// Temperature returns the current temperature
func (t *SelectiveThermometer) Temperature() float64 {
return t.accessory.TempSensor.CurrentTemperature.GetValue()
}
// Update attempts to update the thermometer temperature
func (t *SelectiveThermometer) Update() error {
if t.filter() {
t.accessory.TempSensor.CurrentTemperature.SetValue(
t.thermometer.Temperature())
}
return nil
}
// Accessory returns the Apple HomeKit accessory
func (t *SelectiveThermometer) Accessory() *accessory.Accessory {
return t.accessory.Accessory
}
// GpioThermometer is used to measure the temperature of a given resistive thermometer
// using a capacitor.
type GpioThermometer struct {
name string
mutex sync.Mutex
pin PiPin
microfarads float64
adjust float64
updated time.Time
history History
accessory *accessory.Thermometer
}
// NewGpioThermometer returns a GpioThermometer
func NewGpioThermometer(name string, manufacturer string, gpio uint8) *GpioThermometer {
return newGpioThermometer(name, manufacturer, NewGpio(gpio))
}
// MillisecondFloat returns the float64 value associated with time.Millisecond time.Duration
const MillisecondFloat float64 = float64(time.Millisecond)
// Return the number of milliseconds represented by a given time.Duration
func ms(t time.Duration) float64 {
return float64(t) / float64(time.Millisecond)
}
// Return the number of microseconds represented by a given time.Duration
func us(t time.Duration) float64 {
return float64(t) / float64(time.Microsecond)
}
func newGpioThermometer(name string, manufacturer string, pin PiPin) *GpioThermometer {
acc := accessory.NewTemperatureSensor(AccessoryInfo(name, manufacturer), 0.0, -20.0, 100.0, 1.0)
th := GpioThermometer{
name: name,
mutex: sync.Mutex{},
pin: pin,
microfarads: float64(nanoFarads) / 1000.0,
adjust: 2.5,
history: *NewHistory(100),
updated: time.Now().Add(-24 * time.Hour),
accessory: acc,
}
return &th
}
// SetAdjustment provides a multiplier to the teperature sensor
func (t *GpioThermometer) SetAdjustment(a float64) {
t.adjust = a
}
// Name returns the name of the GpioThermometer
func (t *GpioThermometer) Name() string {
return t.name
}
// Accessory returns the Apple HomeKit accessory related to the GpioThermometer
func (t *GpioThermometer) Accessory() *accessory.Accessory {
return t.accessory.Accessory
}
func (t *GpioThermometer) getDischargeTime() time.Duration {
pull := Float
edge := RisingEdge
t.mutex.Lock()
defer t.mutex.Unlock()
// Discharge the capacitor (low temps could make this really long)
t.pin.Output(Low)
time.Sleep(2 * maxTime)
// Start polling
start := time.Now()
// Set to input
t.pin.InputEdge(pull, edge)
if !t.pin.WaitForEdge(maxTime) {
Debug("Thermometer %s, WaitForEdge(%s, %s) timed out", t.name, pull, edge)
return time.Duration(0)
}
dt := time.Since(start)
t.pin.Output(Low)
Debug("Discharge time for %s: %s", t.name, dt)
return dt
}
func (t *GpioThermometer) getTemp(ohms float64) float64 {
const a = 79463.85
const b = 0.1453676
const c = 2.517178e-15
const d = -132.2399
if ohms == 0.0 {
return 0.0
}
return d + (a-d)/(1+math.Pow(ohms/c, b))
}
func (t *GpioThermometer) getOhms(dischargeTime time.Duration) float64 {
uSec := t.adjust * us(dischargeTime)
return uSec / t.microfarads
}
// Calibrate asserts a specific resistance and calculates the proper setting
// for the adjust parameter
func (t *GpioThermometer) Calibrate(ohms float64) error {
calculated := ohms * t.microfarads / 1000.0
Info("Expecting %0.3f ms", calculated)
// Take a sample of values
h := NewHistory(20)
for i := 0; i < 20; i++ {
dt := t.getDischargeTime()
if dt != 0 {
h.Push(float64(dt))
}
}
dt := time.Duration(int64(h.Median()))
value := calculated / ms(dt)
Info("Calculated Value (full discharge) %0.3f ms, found %0.3f ms, ratio %0.3f", calculated, ms(dt), value)
if h.Stddev() > h.Median()*0.05 || h.Len() < 10 {
return fmt.Errorf("returned inconsistent data value(%0.4f) variance(%0.2f%%) entries(%d)",
value, 100.0*h.Stddev()/h.Median(), h.Len())
}
Debug("Setting adjustment to %0.3f", value)
t.adjust = value
return nil
}
func (t *GpioThermometer) inRange(dischargeTime time.Duration) bool {
// Completely bogus, ignore
if dischargeTime < minTime || dischargeTime > maxTime {
return false
}
return true
}
// Temperature returns the current temperature of the GpioThermometer
func (t *GpioThermometer) Temperature() float64 {
if time.Now().After(t.updated.Add(time.Minute)) {
t.Update()
}
return t.accessory.TempSensor.CurrentTemperature.GetValue()
}
// Update updates the current temperature of the GpioThermometer
func (t *GpioThermometer) Update() error {
var dischargeTime time.Duration
h := NewHistory(5)
for i := 0; h.Len() < 5 && i < 20; i++ {
dischargeTime = t.getDischargeTime()
if t.inRange(dischargeTime) {
t.history.PushDuration(dischargeTime)
h.PushDuration(dischargeTime)
}
}
stdd := t.history.Stddev()
avg := t.history.Average()
med := t.history.Median()
dev := stdd * 3
// Throw away bad results
if math.Abs(avg-h.Median()) > dev {
Info("%s Thermometer update failed: Cur(%0.3f) Med(%0.3f) Avg(%0.3f) Stdd(%0.3f) Dev(%0.3f)",
t.Name(),
h.Median()/MillisecondFloat,
med/MillisecondFloat,
avg/MillisecondFloat,
stdd/MillisecondFloat,
dev/MillisecondFloat)
return fmt.Errorf("could not update temperature successfully")
}
ohms := t.getOhms(time.Duration(int64(h.Median())))
temp := t.getTemp(ohms)
Debug("Calculating temperature (%f) for %s: %f ohms, median %s", temp, t.name, ohms, time.Duration(int64(h.Median())))
t.accessory.TempSensor.CurrentTemperature.SetValue(temp)
t.updated = time.Now()
return nil
}
// Converts a temperature in Celsius to Farenheit
func toFarenheit(celsius float64) float64 {
return (celsius * 9.0 / 5.0) + 32.0
}