Skip to content

Instantly share code, notes, and snippets.

@mpj

mpj/coding.c Secret

Last active July 25, 2020 11:38
Show Gist options
  • Save mpj/52387d39bd9e12271d2141d367e2e7c5 to your computer and use it in GitHub Desktop.
Save mpj/52387d39bd9e12271d2141d367e2e7c5 to your computer and use it in GitHub Desktop.
photon snapshot
#include <InternetButton.h>
InternetButton b = InternetButton();
long secondsInADay = 86400;
long windowSize = 30;
long powerStreak = 5;
long lastCheckin = 0;
long streak = 0;
long lastRewardedCheckin = 0;
struct PersistedState {
long lastCheckin;
long streak;
long lastRewardedCheckin;
};
void persist() {
PersistedState persistState = { lastCheckin, streak, lastRewardedCheckin };
EEPROM.put(0, persistState);
}
void restore() {
PersistedState persistState;
EEPROM.get(0, persistState);
lastCheckin = persistState.lastCheckin;
streak = persistState.streak;
lastRewardedCheckin = persistState.lastRewardedCheckin;
}
SYSTEM_THREAD(ENABLED);
void setup() {
restore();
//char lastCheckinStr[30];
//sprintf(lastCheckinStr,"%d", lastCheckin);
//Particle.publish("lastCheckin restored", lastCheckinStr, PRIVATE);
RGB.control(true);
RGB.brightness(0);
b.begin();
}
void loop() {
long now = Time.now();
long window = windowsSinceEpoch(now, windowSize);
long lastCheckinWindow = windowsSinceEpoch(lastCheckin, windowSize);
if(window > (lastCheckinWindow + 4)) {
b.allLedsOff();
lastCheckin = 0;
streak = 0;
lastRewardedCheckin = 0;
persist();
} else if(window > (lastCheckinWindow + 3)) {
b.allLedsOn(125, 0, 0); // red
}
else if(window > (lastCheckinWindow + 2)) {
b.allLedsOn(90, 40, 0); // orange
} else if (window > (lastCheckinWindow + 1)) {
lightIdle2();
} else { // last checkin was this window
// run reward animation if not yet rewarded
if (lastRewardedCheckin == 0 || lastRewardedCheckin != lastCheckinWindow) {
lastRewardedCheckin = lastCheckinWindow;
streak++;
persist();
lightRewardAnimation();
}
}
if (b.buttonOn(3)) {
lastCheckin = now;
persist();
//char lastCheckinStr[30];
//sprintf(lastCheckinStr,"%d", lastCheckin);
//Particle.publish("lastCheckin put", lastCheckinStr, PRIVATE);
}
}
long windowsSinceEpoch(long epoch, long windowSize) {
return epoch / windowSize;
}
void lightIdle() {
if(streak >= powerStreak) {
b.allLedsOn(0, 0, 30);
} else {
b.allLedsOn(0, 30, 0);
}
}
void lightIdle2() { // slightly brighter variant for debugging
if(streak >= powerStreak) {
b.allLedsOn(0, 0, 40);
} else {
b.allLedsOn(0, 40, 0);
}
}
void lightRewardAnimation() {
for(int i = 0; i<12; i++) {
if(streak >= powerStreak) {
b.ledOn(i, 0, 0, 255);
} else {
b.ledOn(i, 0, 255, 0);
}
delay(75);
}
for(int c=255;c>20;c--) {
if(streak >= powerStreak) {
b.allLedsOn(0, 0, c);
} else {
b.allLedsOn(0, c, 0);
}
// Fade out slowly during the first n% of the window size.=
delay(((windowSize * 1000) * 0.25 ) / 255);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment