-
Notifications
You must be signed in to change notification settings - Fork 100
/
core.cpp
492 lines (442 loc) · 11.2 KB
/
core.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
// core.cpp
// This file constitutes the core functions that run the scheduling for the Sprinkler system.
// Author: Richard Zimmerman
// Copyright (c) 2013 Richard Zimmerman
//
#include "core.h"
#include "settings.h"
#if defined(WEATHER_WUNDERGROUND)
#include "Wunderground.h"
#elif defined(WEATHER_AERIS)
#include "Aeris.h"
#elif defined(WEATHER_DARKSKY)
#include "DarkSky.h"
#elif defined(WEATHER_OPENWEATHER)
#include "OpenWeather.h"
#else
#include "Weather.h"
#endif
#include "web.h"
#include "Event.h"
#include "port.h"
#include <stdlib.h>
#ifdef ARDUINO
#include "tftp.h"
static tftp tftpServer;
#else
#include <wiringPi.h>
#include <unistd.h>
#include <sys/stat.h>
#endif
#ifdef LOGGING
Logging logger;
#endif
static web webServer;
nntp nntpTimeServer;
runStateClass runState;
// A bitfield that defines which zones are currently on.
int ZoneState = 0;
runStateClass::runStateClass() : m_bSchedule(false), m_bManual(false), m_iSchedule(-1), m_zone(-1), m_endTime(0), m_eventTime(0)
{
}
void runStateClass::LogSchedule()
{
#ifdef LOGGING
if ((m_eventTime > 0) && (m_zone >= 0))
logger.LogZoneEvent(m_eventTime, m_zone, nntpTimeServer.LocalNow() - m_eventTime, m_bSchedule ? m_iSchedule+1:-1, m_adj.seasonal, m_adj.wunderground);
#endif
}
void runStateClass::SetSchedule(bool val, int8_t iSched, const runStateClass::DurationAdjustments * adj)
{
LogSchedule();
m_bSchedule = val;
m_bManual = false;
m_zone = -1;
m_endTime = 0;
m_iSchedule = val?iSched:-1;
m_eventTime = nntpTimeServer.LocalNow();
m_adj = adj?*adj:DurationAdjustments();
}
void runStateClass::ContinueSchedule(int8_t zone, short endTime)
{
LogSchedule();
m_bSchedule = true;
m_bManual = false;
m_zone = zone;
m_endTime = endTime;
m_eventTime = nntpTimeServer.LocalNow();
}
void runStateClass::SetManual(bool val, int8_t zone)
{
LogSchedule();
m_bSchedule = false;
m_bManual = val;
m_zone = zone;
m_endTime = 0;
m_iSchedule = -1;
m_eventTime = nntpTimeServer.LocalNow();
m_adj=DurationAdjustments();
}
#ifdef ARDUINO
uint8_t ZoneToIOMap[] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37};
#endif
#if defined(GREENIQ)
uint8_t ZoneToIOMap[] = {5, 7, 0, 1, 2, 3, 4};
#else
uint8_t ZoneToIOMap[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
#define SR_CLK_PIN 7
#define SR_NOE_PIN 0
#define SR_DAT_PIN 2
#define SR_LAT_PIN 3
#endif
static uint16_t outState;
static uint16_t prevOutState;
static void io_latch()
{
// check if things have changed
if (outState == prevOutState)
return;
const EOT eot = GetOT();
switch (eot)
{
case OT_NONE:
#ifndef ARDUINO
#ifdef EXTERNAL_SCRIPT
struct stat buffer;
char cmd[50];
if (stat(EXTERNAL_SCRIPT, &buffer) == 0) {
for (int i = 0; i <= NUM_ZONES; i++)
{
sprintf(cmd, "%s %i %i", EXTERNAL_SCRIPT, i, (outState&(0x01<<i))?1:0);
system(cmd);
}
}
#endif
#endif
break;
case OT_DIRECT_POS:
case OT_DIRECT_NEG:
for (int i = 0; i <= NUM_ZONES; i++)
{
if (eot == OT_DIRECT_POS)
digitalWrite(ZoneToIOMap[i], (outState&(0x01<<i))?1:0);
else
digitalWrite(ZoneToIOMap[i], (outState&(0x01<<i))?0:1);
}
break;
case OT_OPEN_SPRINKLER:
#ifndef ARDUINO
#ifndef GREENIQ
// turn off the latch pin
digitalWrite(SR_LAT_PIN, 0);
digitalWrite(SR_CLK_PIN, 0);
for (uint8_t i = 0; i < 16; i++)
{
digitalWrite(SR_CLK_PIN, 0);
digitalWrite(SR_DAT_PIN, outState&(0x01<<(15-i)));
digitalWrite(SR_CLK_PIN, 1);
}
// latch the outputs
digitalWrite(SR_LAT_PIN, 1);
// Turn off the NOT enable pin (turns on outputs)
digitalWrite(SR_NOE_PIN, 0);
#endif
#endif
break;
}
// Now store the new output state so we know if things have changed
prevOutState = outState;
}
void io_setup()
{
const EOT eot = GetOT();
if ((eot != OT_NONE))
{
#ifndef ARDUINO
if (geteuid() != 0)
{
trace("You need to be root to run this. Setting output mode to NONE\n");
SetOT(OT_NONE);
return;
}
else if (wiringPiSetup() == -1)
{
trace("Failed to Setup Outputs\n");
}
#endif
if (eot == OT_OPEN_SPRINKLER)
{
#ifndef GREENIQ
pinMode(SR_CLK_PIN, OUTPUT);
digitalWrite(SR_CLK_PIN, 0);
pinMode(SR_NOE_PIN, OUTPUT);
digitalWrite(SR_NOE_PIN, 0);
pinMode(SR_DAT_PIN, OUTPUT);
digitalWrite(SR_DAT_PIN, 0);
pinMode(SR_LAT_PIN, OUTPUT);
digitalWrite(SR_LAT_PIN, 0);
#endif
}
else
{
for (uint8_t i=0; i<sizeof(ZoneToIOMap); i++)
{
pinMode(ZoneToIOMap[i], OUTPUT);
digitalWrite(ZoneToIOMap[i], (eot==OT_DIRECT_NEG)?1:0);
}
}
}
outState = 0;
prevOutState = 1;
io_latch();
}
void io_latchNow()
{
io_latch();
}
void TurnOffZones()
{
trace(F("Turning Off All Zones\n"));
outState = 0;
}
bool isZoneOn(int iNum)
{
if ((iNum <= 0) || (iNum > NUM_ZONES))
return false;
return outState & (0x01 << iNum);
}
static void pumpControl(bool val)
{
if (val)
outState |= 0x01;
else
outState &= ~0x01;
}
void TurnOnZone(int iValve)
{
trace(F("Turning on Zone %d\n"), iValve);
if ((iValve <= 0) || (iValve > NUM_ZONES))
return;
ShortZone zone;
LoadShortZone(iValve - 1, &zone);
outState = 0x01 << iValve;
// Turn on the pump if necessary
pumpControl(zone.bPump);
}
// Adjust the durations based on atmospheric conditions
static runStateClass::DurationAdjustments AdjustDurations(Schedule * sched)
{
runStateClass::DurationAdjustments adj(100);
if (sched->IsWAdj()) {
#if defined(WEATHER_WUNDERGROUND)
Wunderground w;
#elif defined(WEATHER_AERIS)
Aeris w;
#elif defined(WEATHER_DARKSKY)
DarkSky w;
#elif defined(WEATHER_OPENWEATHER)
OpenWeather w;
#else
// this is a dummy provider which will just result in 100
Weather w;
#endif
// get factor to adjust times by. 100 = 100% (i.e. no adjustment)
adj.wunderground = w.GetScale();
}
adj.seasonal = GetSeasonalAdjust();
long scale = ((long)adj.seasonal * (long)adj.wunderground) / 100;
for (uint8_t k = 0; k < NUM_ZONES; k++)
sched->zone_duration[k] = (uint8_t)spi_min(((long)sched->zone_duration[k] * scale + 50) / 100, 255);
return adj;
}
// Load the on/off events for a specific schedule/time or the quick schedule
void LoadSchedTimeEvents(uint8_t sched_num, bool bQuickSchedule)
{
Schedule sched;
runStateClass::DurationAdjustments adj;
if (!bQuickSchedule)
{
const uint8_t iNumSchedules = GetNumSchedules();
if ((sched_num < 0) || (sched_num >= iNumSchedules))
return;
LoadSchedule(sched_num, &sched);
adj=AdjustDurations(&sched);
}
else
sched = quickSchedule;
const time_t local_now = nntpTimeServer.LocalNow();
short start_time = (local_now - previousMidnight(local_now)) / 60;
for (uint8_t k = 0; k < NUM_ZONES; k++)
{
ShortZone zone;
LoadShortZone(k, &zone);
if (zone.bEnabled && (sched.zone_duration[k] > 0))
{
if (iNumEvents >= MAX_EVENTS - 1)
{ // make sure we have room for the on && the off events.. hence the -1
trace(F("ERROR: Too Many Events!\n"));
}
else
{
events[iNumEvents].time = start_time;
events[iNumEvents].command = 0x01; // Turn on a zone
events[iNumEvents].data[0] = k + 1; // Zone to turn on
events[iNumEvents].data[1] = (start_time + sched.zone_duration[k]) >> 8;
events[iNumEvents].data[2] = (start_time + sched.zone_duration[k]) & 0x00FF;
iNumEvents++;
start_time += sched.zone_duration[k];
}
}
}
// Load up the last turn off event.
events[iNumEvents].time = start_time;
events[iNumEvents].command = 0x02; // Turn off all zones
events[iNumEvents].data[0] = 0;
events[iNumEvents].data[1] = 0;
events[iNumEvents].data[2] = 0;
iNumEvents++;
runState.SetSchedule(true, bQuickSchedule?99:sched_num, &adj);
}
void ClearEvents()
{
iNumEvents = 0;
runState.SetSchedule(false);
}
// TODO: Schedules that go past midnight!
// Pretty simple. When we one-shot at midnight, check to see if any outstanding events are at time >1400. If so, move them
// to the top of the event stack and subtract 1440 (24*60) from their times.
// Loads the events for the current day
void ReloadEvents(bool bAllEvents)
{
ClearEvents();
TurnOffZones();
// Make sure we're running now
if (!GetRunSchedules())
return;
const time_t time_now = nntpTimeServer.LocalNow();
const uint8_t iNumSchedules = GetNumSchedules();
for (uint8_t i = 0; i < iNumSchedules; i++)
{
Schedule sched;
LoadSchedule(i, &sched);
if (sched.IsRunToday(time_now))
{
// now load up events for each of the start times.
for (uint8_t j = 0; j <= 3; j++)
{
const short start_time = sched.time[j];
if (start_time != -1)
{
if (!bAllEvents && (start_time <= (long)(time_now - previousMidnight(time_now))/60 ))
continue;
if (iNumEvents >= MAX_EVENTS)
{
trace(F("ERROR: Too Many Events!\n"));
}
else
{
events[iNumEvents].time = start_time;
events[iNumEvents].command = 0x03; // load events for schedule i, time j
events[iNumEvents].data[0] = i;
events[iNumEvents].data[1] = j;
events[iNumEvents].data[2] = 0;
iNumEvents++;
}
}
}
}
}
}
// Check to see if there are any events that need to be processed.
static void ProcessEvents()
{
const time_t local_now = nntpTimeServer.LocalNow();
const short time_check = (local_now - previousMidnight(local_now)) / 60;
for (uint8_t i = 0; i < iNumEvents; i++)
{
if (events[i].time == -1)
continue;
if (time_check >= events[i].time)
{
switch (events[i].command)
{
case 0x01: // turn on valves in data[0]
TurnOnZone(events[i].data[0]);
runState.ContinueSchedule(events[i].data[0], events[i].data[1] << 8 | events[i].data[2]);
events[i].time = -1;
break;
case 0x02: // turn off all valves
TurnOffZones();
runState.SetSchedule(false);
events[i].time = -1;
break;
case 0x03: // load events for schedule(data[0]) time(data[1])
if (runState.isSchedule()) // If we're already running a schedule, push this off 1 minute
events[i].time++;
else
{
// Load all the individual events for the individual zones on/off
LoadSchedTimeEvents(events[i].data[0]);
events[i].time = -1;
}
break;
};
}
}
}
void mainLoop()
{
static bool firstLoop = true;
static bool bDoneMidnightReset = false;
if (firstLoop)
{
firstLoop = false;
freeMemory();
if (IsFirstBoot())
ResetEEPROM();
io_setup();
#ifdef LOGGING
if (!logger.Init())
exit(EXIT_FAILURE);
#endif
TurnOffZones();
ClearEvents();
//Init the web server
if (!webServer.Init())
exit(EXIT_FAILURE);
#ifdef ARDUINO
//Init the TFTP server
tftpServer.Init();
#endif
// Set the clock.
nntpTimeServer.checkTime();
ReloadEvents();
//ShowSockStatus();
}
// Check to see if we need to set the clock and do so if necessary.
nntpTimeServer.checkTime();
const time_t timeNow = nntpTimeServer.LocalNow();
// One shot at midnight
if ((hour(timeNow) == 0) && !bDoneMidnightReset)
{
trace(F("Reloading Midnight\n"));
bDoneMidnightReset = true;
// TODO: outstanding midnight events. See other TODO for how.
ReloadEvents(true);
}
else if (hour(timeNow) != 0)
bDoneMidnightReset = false;
// See if any web clients have connected
webServer.ProcessWebClients();
// Process any pending events.
ProcessEvents();
#ifdef ARDUINO
// Process the TFTP Server
tftpServer.Poll();
#else
// if we've changed the settings, store them to disk
EEPROM.Store();
#endif
// latch any output modifications
io_latch();
}