forked from emoncms/demandshaper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demandshaper_run.php
527 lines (444 loc) · 24.1 KB
/
demandshaper_run.php
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
<?php
/*
All Emoncms code is released under the GNU Affero General Public License.
See COPYRIGHT.txt and LICENSE.txt.
---------------------------------------------------------------------
Emoncms - open source energy visualisation
Part of the OpenEnergyMonitor project:
http://openenergymonitor.org
*/
$userid = 1;
define('EMONCMS_EXEC', 1);
$fp = fopen("/var/lock/demandshaper.lock", "w");
if (! flock($fp, LOCK_EX | LOCK_NB)) { echo "Already running\n"; die; }
$pid = getmypid();
//$fh = fopen("/home/pi/data/demandshaper.pid","w");
//fwrite($fh,$pid);
//fclose($fh);
chdir("/var/www/emoncms");
require "process_settings.php";
require "Lib/EmonLogger.php";
require "core.php";
set_error_handler('exceptions_error_handler');
$log = new EmonLogger(__FILE__);
$log->info("Starting demandshaper service");
// -------------------------------------------------------------------------
// MQTT Connect
// -------------------------------------------------------------------------
$mqtt_client = new Mosquitto\Client();
$connected = false;
$mqtt_client->onConnect('connect');
$mqtt_client->onDisconnect('disconnect');
$mqtt_client->onMessage('message');
$mysqli = @new mysqli(
$settings["sql"]["server"],
$settings["sql"]["username"],
$settings["sql"]["password"],
$settings["sql"]["database"],
$settings["sql"]["port"]
);
if ( $mysqli->connect_error ) {
$log->error("Can't connect to database, please verify credentials/configuration in settings.php");
if ( $display_errors ) {
$log->error("Error message: ".$mysqli->connect_error);
}
die();
}
// -------------------------------------------------------------------------
// Redis Connect
// -------------------------------------------------------------------------
$redis = new Redis();
if (!$redis->connect($settings['redis']['host'], $settings['redis']['port'])) { $log->error("Can't connect to redis"); die; }
if (!empty($settings['redis']['prefix'])) $redis->setOption(Redis::OPT_PREFIX, $settings['redis']['prefix']);
if (!empty($settings['redis']['auth']) && !$redis->auth($settings['redis']['auth'])) {
$log->error("Can't connect to redis, autentication failed"); die;
}
// Load user module used to fetch user timezone
require("Modules/user/user_model.php");
$user = new User($mysqli,$redis);
$timezone = $user->get_timezone($userid);
if (file_exists("$linked_modules_dir/demandshaper/scheduler.php")) {
require "$linked_modules_dir/demandshaper/scheduler.php";
}
require "Modules/demandshaper/demandshaper_model.php";
$demandshaper = new DemandShaper($mysqli,$redis);
$forecast_list = $demandshaper->get_forecast_list();
// -------------------------------------------------------------------------
// Control Loop
// -------------------------------------------------------------------------
$last_30min = 0;
$last_retry = 0;
$timer = array();
$last_timer = array();
$last_ctrlmode = array();
$last_flowtemp = array();
$update_interval = 60;
$last_state_check = 0;
$schedules = array();
$firstrun = true;
$lasttime = time();
while(true)
{
$now = time();
// demandshaper trigger
if ($trigger = $redis->get("demandshaper:trigger")) {
$log->info("trigger");
}
// ---------------------------------------------------------------------
// Control Loop
// ---------------------------------------------------------------------
if ($now%$update_interval==0 || $trigger || $firstrun) {
$firstrun = false;
$redis->set("demandshaper:trigger",0);
// Get time of start of day
$date = new DateTime();
$date->setTimezone(new DateTimeZone($timezone));
$date->setTimestamp($now);
$date->modify("midnight");
$daystart = $date->getTimestamp();
$second_in_day = $now - $daystart;
// Schedule definition
$schedules = $demandshaper->get($userid);
if ($schedules!=null)
{
// ---------------------------------------------------------------------
// Load demand shaper and cache locally every hour
// - load only relevant forecasts
// ---------------------------------------------------------------------
if (($now-$last_30min)>=3600) {
$last_30min = $now;
$request_forecasts = array();
foreach ($schedules as $sid=>$schedule) {
if (!in_array($schedule->settings->signal,$request_forecasts)) $request_forecasts[] = $schedule->settings->signal;
}
// Clear old forecasts - ensures forecasts are reloaded properly if selected after an extended period in the UI
foreach ($forecast_list as $forecast_key=>$forecast) $redis->del("demandshaper:$forecast_key");
// Load in only relevant forecasts
foreach ($request_forecasts as $forecast) {
if (strpos($forecast,"energylocal_")!==false) {
// Energy Local Bethesda demand shaper
if ($result = http_request("GET","https://dashboard.energylocal.org.uk/cydynni/demandshaper",array())) {
$redis->set("demandshaper:energylocal_bethesda",$result);
$log->info("load: demandshaper:energylocal_bethesda (".strlen($result).")");
}
// Octopus agile
} else if (strpos($forecast,"octopusagile_")!==false && strlen($forecast)==14) {
// Agile region code options
$gsp_id = "A"; if (in_array($forecast[13],array("A","B","C","D","E","F","G","H","J","K","L","M","N","P"))) $gsp_id = $forecast[13];
if ($result = http_request("GET","https://emoncms.org/demandshaper/octopus?gsp=$gsp_id&time=".time(),array())) {
$redis->set("demandshaper:octopusagile_$gsp_id",$result);
$log->info("load: demandshaper:octopusagile_$gsp_id (".strlen($result).")");
}
} else if ($forecast=="carbonintensity") {
// Uk Grid carbon intensity
if ($result = http_request("GET","https://emoncms.org/demandshaper/carbonintensity",array())) {
$redis->set("demandshaper:carbonintensity",$result);
$log->info("load: demandshaper:carbonintensity (".strlen($result).")");
}
}
}
}
foreach ($schedules as $sid=>$schedule)
{
$device = false;
if (isset($schedule->settings->device)) $device = $schedule->settings->device;
$device_type = false;
if (isset($schedule->settings->device_type)) $device_type = $schedule->settings->device_type;
$ctrlmode = false;
if (isset($schedule->settings->ctrlmode)) $ctrlmode = $schedule->settings->ctrlmode;
if ($device_type && $ctrlmode)
{
$log->info(date("Y-m-d H:i:s")." Schedule:$device ".$schedule->settings->ctrlmode);
$log->info(" end timestamp: ".$schedule->settings->end_timestamp);
// -----------------------------------------------------------------------
// Work out if schedule is running
// -----------------------------------------------------------------------
$status = 0;
$active_period = 0;
if ($schedule->runtime->timeleft>0 || $ctrlmode=="timer") {
foreach ($schedule->runtime->periods as $pid=>$period) {
$start = $period->start[0];
$end = $period->end[0];
if ($now>=$start && $now<$end) {
$status = 1;
$active_period = $pid;
}
}
}
// If runonce is true, check if within 24h period
if ($schedule->settings->runonce!==false) {
if (($now-$schedule->settings->runonce)>(24*3600)) $status = 0;
} else {
// Check if schedule should be ran on this day
if (!$schedule->settings->repeat[$date->format("N")-1]) $status = 0;
}
if ($schedule->settings->ctrlmode=="on") $status = 1;
if ($schedule->settings->ctrlmode=="off") $status = 0;
if ($status) {
$log->info(" status: ON");
$schedule->runtime->started = true;
$time_elapsed = $now - $lasttime;
$log->info(" time elapsed: $time_elapsed");
$schedule->runtime->timeleft -= $time_elapsed; // $update_interval;
$log->info(" timeleft: ".$schedule->runtime->timeleft."s");
if ($schedule->runtime->timeleft<0) $schedule->runtime->timeleft = 0;
} else {
$log->info(" status: OFF");
}
// $connected = true; $device = "openevse";
// Publish to MQTT
if ($connected) {
// SmartPlug and WIFI Relay
if ($device_type=="openevse" || $device_type=="smartplug" || $device_type=="hpmon" || $device_type=="wifirelay") {
// Timezone correction to UTC for smartplug and hpmon
$timeOffset = 0;
if ($device_type=="smartplug" || $device_type=="hpmon" || $device_type=="wifirelay") {
$dateTimeZone = new DateTimeZone($timezone);
$date = new DateTime("now", $dateTimeZone);
$timeOffset = $dateTimeZone->getOffset($date) / 3600;
}
// ----------------------------------------------------------------------------
// Set Timer
// ----------------------------------------------------------------------------
$s1 = 0.0; $e1 = 0.0; $s2 = 0.0; $e2 = 0.0;
// Smart timer
if ($schedule->settings->ctrlmode=="smart") {
if (count($schedule->runtime->periods)) {
$s1 = time_offset($schedule->runtime->periods[$active_period]->start[1],-$timeOffset);
$e1 = time_offset($schedule->runtime->periods[$active_period]->end[1],-$timeOffset);
}
// Standard timer
} else if ($schedule->settings->ctrlmode=="timer") {
$s1 = time_offset($schedule->settings->timer_start1,-$timeOffset);
$e1 = time_offset($schedule->settings->timer_stop1,-$timeOffset);
$s2 = time_offset($schedule->settings->timer_start2,-$timeOffset);
$e2 = time_offset($schedule->settings->timer_stop2,-$timeOffset);
}
if (!isset($timer[$device])) $timer[$device] = "";
$last_timer[$device] = $timer[$device];
// Slight difference in API format
if ($device_type=="smartplug" || $device_type=="hpmon" || $device_type=="wifirelay") {
$api = "in/timer";
$timer[$device] = time_conv_dec_str($s1)." ".time_conv_dec_str($e1)." ".time_conv_dec_str($s2)." ".time_conv_dec_str($e2);
}
if ($device_type=="openevse") {
$api = "rapi/in/\$ST";
$timer[$device] = time_conv_dec_str($s1," ")." ".time_conv_dec_str($e1," ");
}
if ($timer[$device]!=$last_timer[$device]) { // && (time_conv_dec_str($s1)!=time_conv_dec_str($e1))
$log->info(" emon/$device/$api"." $timer[$device]");
$mqtt_client->publish("emon/$device/$api",$timer[$device],0);
schedule_log($device." set timer ".$timer[$device]);
}
} else {
$mqtt_client->publish("emon/$device/status",$status,0);
}
if (!isset($last_ctrlmode[$device])) $last_ctrlmode[$device] = false;
if ($ctrlmode!=$last_ctrlmode[$device]) {
$ctrlmode_status = "Off";
if ($ctrlmode=="on") $ctrlmode_status = "On";
if ($ctrlmode=="smart") $ctrlmode_status = "Timer";
if ($ctrlmode=="timer") $ctrlmode_status = "Timer";
if ($device_type=="smartplug" || $device_type=="hpmon" || $device_type=="wifirelay") {
$mqtt_client->publish("emon/$device/in/ctrlmode",$ctrlmode_status,0);
schedule_log("$device set ctrlmode $ctrlmode_status");
}
if ($device_type=="openevse") {
if ($ctrlmode=="on" || $ctrlmode=="off") {
$mqtt_client->publish("emon/$device/rapi/in/\$ST","00 00 00 00",0);
}
if ($ctrlmode=="on") {
$mqtt_client->publish("emon/$device/rapi/in/\$FE","",0);
schedule_log("$device turning ON");
}
if ($ctrlmode=="off") {
$mqtt_client->publish("emon/$device/rapi/in/\$FS","",0);
schedule_log("$device turning OFF");
}
}
}
$last_ctrlmode[$device] = $ctrlmode;
// Flow temperature target used with heatpump
if (isset($schedule->settings->flowT)) {
if (!isset($last_flowT[$device])) $last_flowT[$device] = false;
if ($schedule->settings->flowT!=$last_flowT[$device]) {
if ($device_type=="smartplug" || $device_type=="hpmon" || $device_type=="wifirelay") {
$vout = round(($schedule->settings->flowT-7.14)/0.0371);
$log->info("emon/$device/vout ".$vout);
$mqtt_client->publish("emon/$device/in/vout",$vout,0);
schedule_log("$device set vout $vout");
}
}
$last_flowT[$device] = $schedule->settings->flowT;
}
}
// -----------------------------------------------------------------------
// Recalculate schedule
// -----------------------------------------------------------------------
if ($now>$schedule->settings->end_timestamp) {
$date->setTimestamp($schedule->settings->end_timestamp);
$date->modify("+1 day");
$schedule->settings->end_timestamp = $date->getTimestamp();
$schedule->runtime->timeleft = $schedule->settings->period * 3600;
unset($schedule->runtime->started);
schedule_log("$device schedule complete");
}
if (!isset($schedule->runtime->started) || $schedule->settings->interruptible) {
if ($schedule->settings->ctrlmode=="smart") {
$forecast = get_forecast($redis,$schedule->settings->signal,$timezone);
$schedule->runtime->periods = schedule_smart($forecast,$schedule->runtime->timeleft,$schedule->settings->end,$schedule->settings->interruptible,900,$timezone);
} else if ($schedule->settings->ctrlmode=="timer") {
$forecast = get_forecast($redis,$schedule->settings->signal,$timezone);
$schedule->runtime->periods = schedule_timer(
$forecast,
$schedule->settings->timer_start1,$schedule->settings->timer_stop1,$schedule->settings->timer_start2,$schedule->settings->timer_stop2,
900,$timezone
);
}
$schedule = json_decode(json_encode($schedule));
$log->info(" reschedule ".json_encode($schedule->runtime->periods));
}
} // if active
$schedules->$sid = $schedule;
if ($device_type===false)
{
$log->info("DELETE: ".$sid);
unset($schedules->$sid);
}
} // foreach schedules
$demandshaper->set($userid,$schedules);
} // valid schedules
sleep(1.0);
$lasttime = $now;
} // 10s update
if ($connected && (time()-$last_state_check)>300) {
$last_state_check = time();
foreach ($schedules as $schedule) {
$device = false;
if (isset($schedule->settings->device)) $device = $schedule->settings->device;
$log->info("emon/$device/in/state");
if ($device) $mqtt_client->publish("emon/$device/in/state","",0);
}
}
// MQTT Connect or Reconnect
if (!$connected && (time()-$last_retry)>5.0) {
$last_retry = time();
try {
$mqtt_client->setCredentials($settings['mqtt']['user'],$settings['mqtt']['password']);
$mqtt_client->connect($settings['mqtt']['host'], $settings['mqtt']['port'], 5);
} catch (Exception $e) { }
}
try { $mqtt_client->loop(); } catch (Exception $e) { }
// Dont loop to fast
sleep(0.1);
}
function connect($r, $message) {
global $connected, $mqtt_client;
$connected = true;
$mqtt_client->subscribe("emon/#",2);
}
function disconnect() {
global $connected; $connected = false;
}
// -------------------------------------------------------------------------
// Update demand shaper state with state from device
// -------------------------------------------------------------------------
function message($message)
{
global $demandshaper, $userid, $schedules, $log, $timezone;
$topic_parts = explode("/",$message->topic);
if (isset($topic_parts[1])) {
$device = $topic_parts[1];
if (isset($schedules->$device)) {
// timezone offset for smartplug and hpmon which use UTC time
$device_type = $schedules->$device->settings->device_type;
$timeOffset = 0;
if ($device_type=="smartplug" || $device_type=="hpmon" || $device_type=="wifirelay") {
$dateTimeZone = new DateTimeZone($timezone);
$date = new DateTime("now", $dateTimeZone);
$timeOffset = $dateTimeZone->getOffset($date) / 3600;
}
$p = $message->payload;
if ($message->topic=="emon/$device/out/state") {
$p = json_decode($p);
if (isset($p->ip)) {
$schedules->$device->settings->ip = $p->ip;
}
if (isset($p->ctrlmode)) {
if ($p->ctrlmode=="On") $schedules->$device->settings->ctrlmode = "on";
if ($p->ctrlmode=="Off") $schedules->$device->settings->ctrlmode = "off";
if ($p->ctrlmode=="Timer" && $schedules->$device->settings->ctrlmode!="smart") $schedules->$device->settings->ctrlmode = "timer";
}
if (isset($p->vout)) {
$schedules->$device->settings->flowT = ($p->vout*0.0371)+7.14;
}
if (isset($p->timer)) {
$timer = explode(" ",$p->timer);
$schedules->$device->settings->timer_start1 = time_conv($timer[0],$timeOffset);
$schedules->$device->settings->timer_stop1 = time_conv($timer[1],$timeOffset);
$schedules->$device->settings->timer_start2 = time_conv($timer[2],$timeOffset);
$schedules->$device->settings->timer_stop2 = time_conv($timer[3],$timeOffset);
}
$schedules->$device->runtime->last_update_from_device = time();
$demandshaper->set($userid,$schedules);
}
else if ($message->topic=="emon/$device/out/ctrlmode") {
if ($p=="On") $schedules->$device->settings->ctrlmode = "on";
if ($p=="Off") $schedules->$device->settings->ctrlmode = "off";
if ($p=="Timer" && $schedules->$device->settings->ctrlmode!="smart") $schedules->$device->settings->ctrlmode = "timer";
$demandshaper->set($userid,$schedules);
}
else if ($message->topic=="emon/$device/out/vout") {
$schedules->$device->flowT = ($p*0.0371)+7.14;
$demandshaper->set($userid,$schedules);
}
else if ($message->topic=="emon/$device/out/timer") {
$timer = explode(" ",$p);
$schedules->$device->settings->timer_start1 = time_conv($timer[0],$timeOffset);
$schedules->$device->settings->timer_stop1 = time_conv($timer[1],$timeOffset);
$schedules->$device->settings->timer_start2 = time_conv($timer[2],$timeOffset);
$schedules->$device->settings->timer_stop2 = time_conv($timer[3],$timeOffset);
$schedules->$device->settings->flowT = ($timer[4]*0.0371)+7.14;
$demandshaper->set($userid,$schedules);
}
}
}
}
function time_offset($t,$timeOffset) {
$t += $timeOffset;
if ($t<0.0) $t += 24.0;
if ($t>=24.0) $t -= 24.0;
return $t;
}
function time_conv($t,$timeOffset){
$t = floor($t*0.01) + ($t*0.01 - floor($t*0.01))/0.6;
$t += $timeOffset;
if ($t<0.0) $t += 24.0;
if ($t>=24.0) $t -= 24.0;
return $t;
}
function time_conv_dec_str($t,$div="") {
$h = floor($t);
$m = round(($t-$h)*60);
if ($h<10) $h = "0".$h;
if ($m<10) $m = "0".$m;
return $h.$div.$m;
}
function exceptions_error_handler($severity, $message, $filename, $lineno) {
if (error_reporting() == 0) {
return;
}
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
}
function schedule_log($message){
if ($fh = @fopen("/var/log/emoncms/demandshaper.log","a")) {
$now = microtime(true);
$micro = sprintf("%03d",($now - ($now >> 0)) * 1000);
$now = DateTime::createFromFormat('U', (int)$now); // Only use UTC for logs
$now = $now->format("Y-m-d H:i:s").".$micro";
@fwrite($fh,$now." | ".$message."\n");
@fclose($fh);
}
}