/
anyleaf_ph.py
371 lines (326 loc) · 11.8 KB
/
anyleaf_ph.py
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# coding=utf-8
import copy
from mycodo.inputs.base_input import AbstractInput
def constraints_pass_positive_value(mod_input, value):
"""
Check if the user input is acceptable
:param mod_input: SQL object with user-saved Input options
:param value: float or int
:return: tuple: (bool, list of strings)
"""
errors = []
all_passed = True
# Ensure value is positive
if value <= 0:
all_passed = False
errors.append("Must be a positive value")
return all_passed, errors, mod_input
# Measurements
measurements_dict = {
0: {
'measurement': 'ion_concentration',
'unit': 'pH'
},
}
# Input information
INPUT_INFORMATION = {
'input_name_unique': 'ANYLEAF_PH',
'input_manufacturer': 'AnyLeaf',
'input_name': 'AnyLeaf pH',
'input_library': 'anyleaf',
'measurements_name': 'Ion concentration',
'measurements_dict': measurements_dict,
'url_manufacturer': 'https://anyleaf.org/ph-module',
'url_datasheet': 'https://anyleaf.org/static/ph-module-datasheet.pdf',
'options_enabled': [
'i2c_location',
'period',
],
'options_disabled': [],
'dependencies_module': [
('apt', 'python3-numpy', 'python3-numpy'),
('apt', 'python3-scipy', 'python3-scipy'),
('pip-pypi', 'usb.core', 'pyusb==1.1.1'),
('pip-pypi', 'adafruit_extended_bus', 'Adafruit-extended-bus==1.0.1'),
('pip-pypi', 'anyleaf', 'anyleaf==0.1.8.1')
],
'interfaces': ['I2C'],
'i2c_location': ['0x48', '0x49'],
'i2c_address_editable': False,
'custom_options': [
# {
# 'id': 'temp_source',
# 'type': 'select_measurement',
# 'default_value': '',
# 'options_select': [
# 'Input',
# 'Function',
# 'Math'
# ],
# 'name': lazy_gettext('Temperature compensation source. Leave at `Select one` to use the onboard sensor.'),
# 'phrase': lazy_gettext('Select a measurement for temperature compensation. If not selected, uses the onboard sensor.'),
# },
{
'id': 'cal1_v',
'type': 'float',
'default_value': 0.,
'name': 'Cal data: V1 (internal)',
'phrase': 'Calibration data: Voltage'
},
{
'id': 'cal1_ph',
'type': 'float',
'default_value': 7.,
'name': 'Cal data: pH1 (internal)',
'phrase': 'Calibration data: pH'
},
{
'id': 'cal1_t',
'type': 'float',
'default_value': 23.,
'name': 'Cal data: T1 (internal)',
'phrase': 'Calibration data: Temperature'
},
{
'id': 'cal2_v',
'type': 'float',
'default_value': 0.17,
'name': 'Cal data: V2 (internal)',
'phrase': 'Calibration data: Voltage'
},
{
'id': 'cal2_ph',
'type': 'float',
'default_value': 4.,
'name': 'Cal data: pH2 (internal)',
'phrase': 'Calibration data: pH'
},
{
'id': 'cal2_t',
'type': 'float',
'default_value': 23.,
'name': 'Cal data: T2 (internal)',
'phrase': 'Calibration data: Temperature'
},
{
'id': 'cal3_v',
'type': 'float',
'default_value': None,
'name': 'Cal data: V3 (internal)',
'phrase': 'Calibration data: Voltage'
},
{
'id': 'cal3_ph',
'type': 'float',
'default_value': None,
'name': 'Cal data: pH3 (internal)',
'phrase': 'Calibration data: pH'
},
{
'id': 'cal3_t',
'type': 'float',
'default_value': None,
'name': 'Cal data: T3 (internal)',
'phrase': 'Calibration data: Temperature'
},
],
'custom_actions_message': """Calibrate: Place your probe in a solution of known pH. Set
the known pH value in the `Calibration buffer pH` field, and press `Calibrate, slot 1`. Repeat with a second buffer,
and press `Calibrate, slot 2`. Optionally, repeat a third time with `Calibrate, slot 3`. You don't need to change
the values under `Custom Options`.""",
'custom_actions': [
{
'id': 'calibration_ph',
'type': 'float',
'default_value': 7.,
'name': 'Calibration buffer pH',
'phrase': 'This is the nominal pH of the calibration buffer, usually labelled on the bottle.'
},
{
'id': 'calibrate_slot_1',
'type': 'button',
'name': 'Calibrate, slot 1'
},
{
'id': 'calibrate_slot_2',
'type': 'button',
'name': 'Calibrate, slot 2'
},
{
'id': 'calibrate_slot_3',
'type': 'button',
'name': 'Calibrate, slot 3'
},
# todo: Including this input will raise an error about `cannot convert string to float`
# todo when attempting calibration.
# {
# 'id': 'temperature_comp_meas',
# 'type': 'select_measurement',
# 'default_value': '',
# 'options_select': [
# 'Input',
# 'Function',
# 'Math'
# ],
# 'name': lazy_gettext('Temperature Compensation Measurement'),
# 'phrase': lazy_gettext('Select a measurement for temperature compensation')
# },
# {
# 'id': 'max_age',
# 'type': 'integer',
# 'default_value': 120,
# 'required': True,
# 'constraints_pass': constraints_pass_positive_value,
# 'name': lazy_gettext('Temperature Compensation Max Age'),
# 'phrase': lazy_gettext('The maximum age (seconds) of the measurement to use for temperature compensation')
# },
]
}
class InputModule(AbstractInput):
"""A sensor support class that monitors AnyLeaf sensor pH or ORP"""
def __init__(self, input_dev, testing=False):
super(InputModule, self).__init__(input_dev, testing=testing, name=__name__)
self.sensor = None
# todo: We've temporarily disabled offboard measurements.
# self.temperature_comp_meas_device_id = None
# self.temperature_comp_meas_measurement_id = None
# self.max_age = None
if not testing:
self.setup_custom_options(
INPUT_INFORMATION['custom_options'], input_dev)
self.initialize_input()
def initialize_input(self):
from adafruit_extended_bus import ExtendedI2C
from anyleaf import PhSensor, CalPt
self.sensor = PhSensor(
ExtendedI2C(self.input_dev.i2c_bus),
self.input_dev.period,
address=int(str(self.input_dev.i2c_location), 16)
)
# `default_value` above doesn't set the default in the database: custom options will initialize to None.
if self.get_custom_option("cal1_v"):
cal1_v = self.get_custom_option("cal1_v")
else:
cal1_v = 0.
if self.get_custom_option("cal1_ph"):
cal1_ph = self.get_custom_option("cal1_ph")
else:
cal1_ph = 7.
if self.get_custom_option("cal1_t"):
cal1_t = self.get_custom_option("cal1_t")
else:
cal1_t = 23.
if self.get_custom_option("cal2_v"):
cal2_v = self.get_custom_option("cal2_v")
else:
cal2_v = 0.17
if self.get_custom_option("cal2_ph"):
cal2_ph = self.get_custom_option("cal2_ph")
else:
cal2_ph = 4.
if self.get_custom_option("cal2_t"):
cal2_t = self.get_custom_option("cal2_t")
else:
cal2_t = 23.
if self.get_custom_option("cal3_v"):
cal3_v = self.get_custom_option("cal3_v")
else:
cal3_v = None
if self.get_custom_option("cal3_ph"):
cal3_ph = self.get_custom_option("cal3_ph")
else:
cal3_ph = None
if self.get_custom_option("cal3_t"):
cal3_t = self.get_custom_option("cal3_t")
else:
cal3_t = None
# cal pt 3 may be None to indicate 2-pt calibration.
if cal3_v and cal3_ph and cal3_t:
cal_pt_3 = CalPt(
cal3_v,
cal3_ph,
cal3_t,
)
else:
cal_pt_3 = None
cal_pt_3 = None
# Load cal data from the database.
self.sensor.calibrate_all(
CalPt(
cal1_v,
cal1_ph,
cal1_t,
),
CalPt(
cal2_v,
cal2_ph,
cal2_t,
),
cal_pt_3
)
def calibrate(self, cal_slot, args_dict):
"""Calibration helper method"""
from anyleaf import CalSlot
if 'calibration_ph' not in args_dict:
self.logger.error("Cannot conduct calibration without a buffer pH value")
return
if not isinstance(args_dict['calibration_ph'], float) and not isinstance(args_dict['calibration_ph'], int):
self.logger.error("buffer value does not represent a number: '{}', type: {}".format(
args_dict['calibration_ph'], type(args_dict['calibration_ph'])))
return
temp_data = self.get_temp_data()
# For this session
v, t = self.sensor.calibrate(cal_slot, args_dict['calibration_ph'], temp_data)
# For future sessions
if cal_slot == CalSlot.ONE:
self.set_custom_option("cal1_v", v)
self.set_custom_option("cal1_ph", args_dict['calibration_ph'])
self.set_custom_option("cal1_t", t)
elif cal_slot == CalSlot.TWO:
self.set_custom_option("cal2_v", v)
self.set_custom_option("cal2_ph", args_dict['calibration_ph'])
self.set_custom_option("cal2_t", t)
else:
self.set_custom_option("cal3_v", v)
self.set_custom_option("cal3_ph", args_dict['calibration_ph'])
self.set_custom_option("cal3_t", t)
def calibrate_slot_1(self, args_dict):
# """ Auto-calibrate """
# # todo: You probably need to store in this class, not self.sensor, to avoid it
# # todo resetting. experiment.
from anyleaf import CalSlot
self.calibrate(CalSlot.ONE, args_dict)
def calibrate_slot_2(self, args_dict):
""" Auto-calibrate """
from anyleaf import CalSlot
self.calibrate(CalSlot.TWO, args_dict)
def calibrate_slot_3(self, args_dict):
""" Auto-calibrate """
from anyleaf import CalSlot
self.calibrate(CalSlot.THREE, args_dict)
@staticmethod
def get_temp_data():
"""Get the temperature, from onboard or off."""
from anyleaf import OnBoard
# if self.temperature_comp_meas_measurement_id:
# last_temp_measurement = self.get_last_measurement(
# self.temperature_comp_meas_device_id,
# self.temperature_comp_meas_measurement_id,
# max_age=self.max_age
# )
# if last_temp_measurement:
# temp_data = OffBoard(last_temp_measurement[1])
# else:
# temp_data = OnBoard()
# else:
temp_data = OnBoard()
return temp_data
def get_measurement(self):
""" Gets the measurement """
self.return_dict = copy.deepcopy(measurements_dict)
if not self.sensor:
self.logger.error("Input not set up")
return
temp_data = self.get_temp_data()
self.value_set(0, self.sensor.read(temp_data))
return self.return_dict