Replace MQTT light switch with syncronised light

This commit is contained in:
Robert Marshall 2018-09-20 17:30:29 +01:00
parent 65dcc100e2
commit 386f405f15

View file

@ -25,8 +25,7 @@
#define VOLTAGE_OFFSET 0.03
#define SOLAR_EVENT_URL "http://api.sunrise-sunset.org/json?lat=20.548103&lng=96.916835&formatted=0"
#define TIMEZONE_OFFSET 23400 // 6.5 hours in seconds
//#define TIME_SHIFT 5400 // 1.5 hours
#define TIMEZONE_OFFSET 27000 // 7.5 hours in seconds
#define NTP_POOL "uk.pool.ntp.org"
void mqttCallback(char *topic, byte *payload, unsigned int length);
@ -39,10 +38,7 @@ PubSubClient client = PubSubClient(MQTT_SERVER, 1883, mqttCallback, wifiClient);
CRGB leds[LED_COUNT];
bool lightsOn = true;
static const uint8_t sunriseLength = 30;
static const uint8_t heatIndexMax = 241; // After 241 the pallet seems to go dim
static const float lightChangeInterval = ((float)(sunriseLength * 60) / heatIndexMax) * 1000;
static uint8_t heatIndex = 0;
static const float heatIndexMax = 241.0; // After 241 the pallet seems to go dim
int _lightsOnStartTime, _lightsOnEndTime, _lightsOffStartTime, _lightsOffEndTime;
float pHStep = (PH_7_VOLTAGE - PH_4_VOLTAGE) / 3;
@ -123,7 +119,6 @@ void parseEvents(String json){
_lightsOnEndTime = adjustForTimezone(getEpoch(sunrise));
_lightsOffStartTime = adjustForTimezone(getEpoch(sunset));
_lightsOffEndTime = adjustForTimezone(getEpoch(astronomicalTwilightEnd));
Serial.println(_lightsOffEndTime);
}
void setup() {
@ -187,19 +182,28 @@ void publishTemperature() {
client.publish(TEMPERATURE_TOPIC, temperatureString.c_str(), true);
}
float getIndexMultiplier(int now, int startTime, int endTime, bool swap){
float indexMultiplier = 1;
int a = swap ? endTime - now : now - startTime;
int b = endTime - startTime;
indexMultiplier = a > 0 ? b / a : 0;
if (indexMultiplier < 1)
indexMultiplier = 1;
return indexMultiplier;
}
float getHeatIndex() {
time_t now = time(nullptr);
float indexMultiplier = now >= _lightsOffStartTime ? getIndexMultiplier(now, _lightsOffStartTime, _lightsOffEndTime, true) : getIndexMultiplier(now, _lightsOnStartTime, _lightsOnEndTime, false);
return heatIndexMax / indexMultiplier;
}
void doLighting() {
EVERY_N_MILLISECONDS(lightChangeInterval) {
CRGB colour = ColorFromPalette(HeatColors_p, heatIndex);
EVERY_N_SECONDS(1) {
CRGB colour = ColorFromPalette(HeatColors_p, getHeatIndex());
fill_solid(leds, LED_COUNT, colour);
if (lightsOn){
if(heatIndex < heatIndexMax)
heatIndex++;
} else {
if (heatIndex > 0)
heatIndex--;
}
FastLED.show();
}
}
@ -211,10 +215,18 @@ void publishReadings(){
}
}
void syncTime(){
EVERY_N_SECONDS(3600) {
configTime(0, 0, NTP_POOL);
}
}
void loop() {
reconnect();
client.loop();
syncTime();
doLighting();
//publishReadings();