-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPlantManager.cpp
563 lines (433 loc) · 17.6 KB
/
PlantManager.cpp
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
#include "PlantManager.h"
#include "Arduino.h"
#include <EEPROM.h>
#define LOGGING 0
const double k_leaf_sensor_dv = 0.125; //mV
// we want to calibrate sensor when not on a leaf and then
// set the value where we say sensor is not connected at something
// less than that
const double k_sensor_normal_range = 30; // maximum of 30 mv between typical high and low readings
const double k_disconnected_sensor_value = 2290; //mV
const double k_sensor_target_calibration_value = 2300; //mV
const unsigned long k_minute_to_milliseconds = 60000;
const unsigned long k_second_to_milliseconds = 1000;
const double k_no_value = 1000000;
const double k_max_temp = 30;
const double k_min_temp = 20;
const double k_max_interval = 30;
// return a time in seconds for a spray interval as a function of time
// linear function that drops off linearely between 20 ℃ and 30 ℃
TimeValue linearTemperatureToTimeFunction(double temp) {
// this function is used to produce a max spray interval in minutes that
// is a function of the ambient air temperature. As the temperature
// increases the max spray interval decreases linearely.
double t = temp;
if( t >= k_max_temp ) { return 0; }
if( t < k_min_temp ) { return k_max_interval * 60; }
// at t = 35 ℃ (95f) v = 0
// at t = 20 ℃ (68f) v = 30
double v = 0.5 - ((t - k_max_temp)/0.34);
// pin value between zero and thirty minutes
if( v < 0 ) { v = 0; }
else if( v > k_max_interval ) { v = k_max_interval; }
// convert value to seconds and return
return v * 60.0;
}
// sqrt function that drops off slowly and then fast between 20 ℃ and 30 ℃
TimeValue sqrtTemperatureToTimeFunction(double temp) {
// this function is used to produce a max spray interval in minutes that
// is a function of the ambient air temperature. As the temperature
// increases the max spray interval decreases linearely.
// pin temp between 20 ℃ and 37 ℃
double t = temp;
if( t >= k_max_temp ) { return 0; }
if( t < k_min_temp ) { return k_max_interval * 60; }
// gives a non linear output between ~30 at 20 ℃ and ~0 at 30 ℃
double v = 52 * sqrt(1 - (t/k_max_temp));
// pin output value between zero and thirty minutes
if( v < 0 ) { v = 0; }
else if( v > 30.0 ) { v = 30.0; }
// convert value to seconds and return
return v * 60.0;
}
// sigmoid function that drops off slow, quick and flattens out between 20 ℃ and 30 ℃
// got the function at https://mycurvefit.com
TimeValue sigmoidTemperatureToTimeFunction(double temp) {
// this function is used to produce a max spray interval in minutes that
// is a function of the ambient air temperature. As the temperature
// increases the max spray interval decreases sigmoidally.
// pin input temp between 20 ℃ and 35 ℃
double t = temp;
if( t >= k_max_temp ) { return 0; }
if( t < k_min_temp ) { return k_max_interval * 60; }
// gives a sigmoid non linear output between ~30 at 20 ℃ and ~0 at 35 ℃
// the sigmoid curve is flat at low temperatures, drops off quicker
// from 25 ℃ and 35 ℃ with a value around 4 min at 30 ℃. This flattens
// out again and aproaches 0 beyond 35 ℃.
double v = k_max_temp/(1 + pow((t/25), 20));
// pin output value between zero and thirty minutes
if( v < 0 ) { v = 0; }
else if( v > 30.0 ) { v = 30.0; }
// convert value to seconds and return
return v * 60.0;
}
// add this layer if indirection to make the code cleaner
// we need to find the right spray interval at 30 ℃ where the plants
// start showing water stress.
TimeValue temperatureToSprayInterval(double temp) {
// return sqrtTemperatureToTimeFunction(temp); // interval 17 min at 30 ℃
// return linearTemperatureToTimeFunction(temp); // interval 10 min at 30 ℃
return sigmoidTemperatureToTimeFunction(temp); // interval ~2 min at 30 ℃
}
double scaleFactor( double v ) {
// v is a fraction ranging from 0 to 1, where 0 is a fully hydrated leaf,
// and 1 is completely dehydrated.
double res = 1.0 - v;
//pin result between zero and one
if( res < 0 ) { return 0; }
else if( res > 1 ) { return 1; }
return res;
}
// return a time value in seconds
TimeValue defaultInterval( TimeValue i, double a ) {
TimeValue interval = i * a;
if( interval > 1800 ) { interval = 1800; } // make sure we don't go longer than thirty minutes (in seconds)
if( interval < 60 ) { interval = 60; } // less than one minute is overkill
return interval;
}
unsigned long defaultIntervalMillis( TimeValue i, double a ) {
TimeValue t = defaultInterval(i, a);
return ((unsigned long)(t * 1000)); //convert seconds to milliseconds
}
/************************************************************************************************************
************************************************************************************************************
*
* PLANT PUBLIC FUNCTIONS
*
************************************************************************************************************
************************************************************************************************************/
void Plant:: initialize() {
#if LOGGING
if( _adc_index == 0 ) { Serial.println("initialize"); }
#endif
pinMode(_valvePin, OUTPUT);
_closeValve();
_next_default_spray = 0;
_last_default_spray = 0;
_spray_interval = 0;
// get the calibration data from EEPROM
loadBoundaryValues();
_iterationCounter = 0;
_state = &Plant::normalHydrationState;
_default_state = &Plant::normalHydrationState;
}
void Plant:: initializeBoundaryValues() {
#if LOGGING
if( _adc_index == 0 ) { Serial.println(" initializeBoundaryValues"); }
#endif
bounds.sensorOffset = 0;
bounds.lowValue = k_no_value;
bounds.highValue = 0;
}
void Plant:: loadBoundaryValues() {
int addr = sizeof(bounds) * _adc_index;
EEPROM.get(addr, bounds);
}
void Plant:: storeBoundaryValues(bool imediate) {
_eepromNeedsWrite = true;
if( imediate ) {
_nextEEPROMWrite = 0; //force a write on next call to synchronizeEEPROM
}
}
void Plant:: synchronizeEEPROM() {
if( _eepromNeedsWrite && (millis() > _nextEEPROMWrite)) {
int addr = sizeof(bounds) * _adc_index;
EEPROM.put(addr, bounds);
_nextEEPROMWrite = millis() + 14400000; //regular writes no more than every four hours
_eepromNeedsWrite = false;
}
}
void Plant:: setAmbientTemperature(double t) {
defaultSprayInterval = temperatureToSprayInterval(t);
_spray_interval = defaultIntervalMillis(defaultSprayInterval, _defaultSprayIntervalAdjustment);
_next_default_spray = _last_default_spray + _spray_interval;
}
/************************************************************************************************************
************************************************************************************************************
*
* MAIN LOOP
*
************************************************************************************************************
************************************************************************************************************/
void Plant:: perform() {
//this takes a reading every 10ms no matter what
this->_testLeafThickness();
if( this->_state == NULL ) {
_state = &Plant::normalHydrationState;
_default_state = &Plant::normalHydrationState;
}
handleButtonPress(); // do this before executing state function
(this->*_state)();
//having this here guarantees that the default interval will be executed
_attemptDefaultSpray();
_tryCloseValve(); // we keep trying this until valve duration is exceeded
synchronizeEEPROM();
}
void Plant:: handleButtonPress(void) {
// button pressed is true after a button click (pressed and released)
if( calibrateButtonPressed ) {
calibrateButtonPressed = false; // reset this
_iterationCounter = 0;
// reset all the stored values and then go straight to calibrate leaf
if( _isSensorConnected() ) {
_leafSensorReading.clearReading();
initializeBoundaryValues();
delay(k_one_minute, &Plant::calibrateLeaf);
}
}
}
/************************************************************************************************************
************************************************************************************************************
*
* PLANT SENSOR FUNCTIONS
*
************************************************************************************************************
************************************************************************************************************/
void Plant:: _appendValue( double value ) {
_leafSensorReading.appendReading( value );
leafRawSensorValue = _leafSensorReading.value;
leafSensorValue = leafRawSensorValue + bounds.sensorOffset;
leafSensorDeviation = leafSensorValue - bounds.lowValue;
}
double Plant:: _readRawLeafSensor() {
int16_t raw = _ads->readADC_SingleEnded(_adc_index);
return k_leaf_sensor_dv * double(raw);
}
double Plant:: _readCalibratedLeafSensor() {
double raw = _readRawLeafSensor();
return raw + bounds.sensorOffset;
}
double Plant:: _currentDeviation() {
double maxDiff = fabs(bounds.highValue - bounds.lowValue);
double diff = leafSensorDeviation;
if( maxDiff > 0.0001 ) {
// make sure we never divide by zero
// and pin result between minus one and one
double d = (diff/maxDiff);
if( d > 1 ) { return 1; }
if( d < -1 ) { return -1; }
return d;
}
return 1.0;
}
void Plant:: _testLeafThickness(void) {
unsigned long now = millis();
if( now > _nextReadingTime ) {
_appendValue( _readRawLeafSensor() );
_nextReadingTime = now + 10; // read sensor every 10 milliseconds
}
}
bool Plant:: _isSensorConnected() {
// if the sensor isn't connected to the cable or the cable isn't plugged into
// the controller board the value on this adc channel will be around 500mv
return leafSensorValue > 1000;
}
/************************************************************************************************************
************************************************************************************************************
*
* VALVE TIMING FUNCTIONS
*
************************************************************************************************************
************************************************************************************************************/
bool Plant:: _attemptDefaultSpray() {
if( _next_default_spray == 0 || millis() > _next_default_spray ) {
// we've exceeded the default spray interval so trigger a spray
_last_default_spray = millis();
_spray_interval = defaultIntervalMillis(defaultSprayInterval, _defaultSprayIntervalAdjustment);
_next_default_spray = _last_default_spray + _spray_interval;
_openValve();
return true;
}
return false;
}
void Plant:: _openValve(unsigned long duration) {
#if LOGGING
if( _adc_index == 0 ) { Serial.print(" + "); }
#endif
// #if defined(__AVR_ATmega2560__)
// //there's a wierd bug in mega 2560 that reverses digital write
// digitalWrite(_valvePin, LOW);
// #else
digitalWrite(_valvePin, LOW);
// #endif
sprayTriggeredCount += 1;
_valveCloseTime = millis() + duration;
}
void Plant:: _tryCloseValve() {
if( _valveCloseTime > 0 && millis() >= _valveCloseTime ) {
_valveCloseTime = 0;
_closeValve();
}
}
void Plant:: _closeValve() {
#if LOGGING
if( _adc_index == 0 ) { Serial.print(" - "); }
#endif
//#if defined(__AVR_ATmega2560__)
// //there's a wierd bug in mega 2560 that reverses digital write
// digitalWrite(_valvePin, HIGH);
//#else
digitalWrite(_valvePin, HIGH);
//#endif
_last_default_spray = millis();
_spray_interval = defaultIntervalMillis(defaultSprayInterval, _defaultSprayIntervalAdjustment);
_next_default_spray = _last_default_spray + _spray_interval;
}
/************************************************************************************************************
************************************************************************************************************
*
* PLANT STATE FUNCTIONS
*
************************************************************************************************************
************************************************************************************************************/
void Plant:: updateIntervalAdjustment() {
#if LOGGING
if( _adc_index == 0 ) { Serial.println(" updateIntervalAdjustment"); }
#endif
// figure the spray interval adjustment
// the spray cycle works like a heart beat where the spray pulses are delivered
// independently of anything we do here. All we do here is up or down
// regulate the interval between pulses.
// current deviation is fraction of (v - low)/(high - low) giving a percentage
// of the deviation of max deviation
double p = scaleFactor(_currentDeviation());
_defaultSprayIntervalAdjustment = p;
// if the current leaf sensor reading is less than the current
// low value set a new low value.
double value = _leafSensorReading.value;
if( _isSensorConnected() && value < bounds.lowValue ) {
bounds.lowValue = value;
bounds.highValue = bounds.lowValue + k_sensor_normal_range; // high value starts at 30 mv higher than low value
storeBoundaryValues(false);
}
_leafSensorReading.resetReading();
}
void Plant:: calibrateLeaf(void) {
#if LOGGING
if( _adc_index == 0 ) { Serial.println(" calibrateLeaf"); }
#endif
double value = _leafSensorReading.value;
_leafSensorReading.resetReading();
if( value < bounds.lowValue ) {
bounds.lowValue = value;
bounds.highValue = bounds.lowValue + k_sensor_normal_range; // high value starts at 30 mv higher than low value
storeBoundaryValues(true); //this is intentional so force a store
}
delay(k_one_minute, &Plant::normalHydrationState);
}
void Plant:: normalHydrationState(void) {
#if LOGGING
if( _adc_index == 0 ) { Serial.println(" normalHydrationState"); }
#endif
updateIntervalAdjustment();
delay(k_one_minute, &Plant::normalHydrationState);
}
void Plant:: delay(unsigned long duration, PlantStateFN nextState) {
#if LOGGING
if( _adc_index == 0 ) { Serial.println(" delay"); }
#endif
_state = &Plant::waitDelay;
_default_state = nextState;
_dt = millis() + duration;
}
void Plant:: waitDelay(void) {
if( millis() >= _dt ) {
#if LOGGING
if( _adc_index == 0 ) { Serial.println(" wait delay done"); }
#endif
// just delaying
_state = _default_state;
}
}
/************************************************************************************************************
************************************************************************************************************
*
* PLANT MANAGER
*
************************************************************************************************************
************************************************************************************************************/
PlantManager:: PlantManager( const int callibratePin, const uint8_t valvePins[4] ) {
for( int i = 0; i < 4; i++ ) {
_plants[i]._valvePin = valvePins[i];
_callibrateButtonPin = callibratePin;
}
}
void PlantManager:: initialize(Adafruit_ADS1115 *ads) {
_ads = ads;
pinMode(_callibrateButtonPin, INPUT);
for( int i = 0; i < 4; i++ ) {
_plants[i]._ads = _ads;
_plants[i].initialize();
}
}
bool PlantManager:: _callibrateButtonClicked() {
int buttonState = digitalRead(_callibrateButtonPin);
bool buttonDown = (buttonState == HIGH);
bool rtn = false;
if( _callibrateButtonDown && !buttonDown ) {
// button was down but now it's not which means it was clicked
rtn = true;
}
_callibrateButtonDown = buttonDown;
return rtn;
}
void PlantManager:: perform() {
bool buttonClicked = _callibrateButtonClicked();
for( int i = 0; i < 4; i++ ) {
if( buttonClicked ) {
_plants[i].calibrateButtonPressed = true; //latch button state high
}
_plants[i].perform();
}
}
void PlantManager:: setAmbientTemperature(double t) {
for( int i = 0; i < 4; i++ ) {
_plants[i].setAmbientTemperature(t);
}
}
void PlantManager:: updateSensorValues( double values[4], int triggers[4] ) {
for( int i = 0; i < 4; i++ ) {
//if( i == 0 ) { Serial.print("v: "); Serial.print(_plants[i].leafSensorValue); Serial.print(" d: "); Serial.println(_plants[i].leafSensorDeviation); }
if( _plants[i].leafSensorValue > 1000 ) {
double v = _plants[i].leafSensorDeviation; // leafSensorValue;
values[i] = v;
triggers[i] = _plants[i].sprayTriggeredCount;
} else {
values[i] = 0;
triggers[i] = 0;
}
_plants[i].sprayTriggeredCount = 0;
}
}
/*
* The SensorReading class
*/
void SensorReading:: appendReading(double reading) {
_average = ((_average * _count) + reading)/(_count + 1);
unsigned long now = millis();
if( now > _dt ) {
value = _average;
_count = 1;
_dt = now + 1000; //update value every second
}
_count += 1.0;
}
void SensorReading:: resetReading(void) {
_count = 1;
}
void SensorReading:: clearReading(void) {
_average = 0;
value = 0;
_count = 0;
_dt = 0;
}