renderbug-cpp/src/main.cpp

469 lines
12 KiB
C++
Raw Normal View History

2021-03-29 08:10:55 +00:00
#include "Arduino.h"
#include <FastLED.h>
#include <Figments.h>
#include <ArduinoLog.h>
#include "Platform.h"
2021-03-29 08:10:55 +00:00
#include "Static.h"
#include "Config.h"
#include "LogService.h"
2021-03-29 08:10:55 +00:00
#include <time.h>
#include "animations/Power.h"
#include "animations/Drain.h"
#include "animations/InputBlip.h"
2021-03-29 08:10:55 +00:00
#include "inputs/ColorCycle.h"
#include "inputs/Buttons.h"
#define MAX_BRIGHTNESS 255
//#define PSU_MILLIAMPS 4800
//#define PSU_MILLIAMPS 500
//#define PSU_MILLIAMPS 1000
#define PSU_MILLIAMPS 1000
// Enable system thread, so rendering happens while booting
//SYSTEM_THREAD(ENABLED);
2021-03-29 08:10:55 +00:00
// Setup FastLED and the display
CRGB leds[HardwareConfig::MAX_LED_NUM];
Display dpy(leds, HardwareConfig::MAX_LED_NUM, Static<ConfigService>::instance()->coordMap());
// Setup power management
Power<MAX_BRIGHTNESS, PSU_MILLIAMPS> power;
REGISTER_TASK(power);
/*FigmentFunc configDisplay([](Display* dpy) {
2021-03-29 08:10:55 +00:00
uint8_t brightness = brighten8_video(beatsin8(60));
auto coords = Static<ConfigService>::instance()->coordMap();
for(int i = 0; i < HardwareConfig::MAX_LED_NUM; i++) {
if (i < coords->startPixel || i > coords->startPixel + coords->pixelCount) {
dpy->pixelAt(i) += CRGB(brightness, 0, 0);
} else {
dpy->pixelAt(i) += CRGB(255 - brightness, 255 - brightness, 255 - brightness);
}
}
});*/
2021-03-29 08:10:55 +00:00
InputFunc randomPulse([]() {
static unsigned int pulse = 0;
EVERY_N_MILLISECONDS(25) {
if (pulse == 0) {
pulse = random(25) + 25;
}
}
if (pulse > 0) {
if (random(255) >= 25) {
pulse--;
return InputEvent{InputEvent::Acceleration, beatsin16(60 * 8, 0, 4972)};
}
}
return InputEvent{};
}, "Pulse", Task::Stopped);
REGISTER_TASK(randomPulse);
2021-03-29 08:10:55 +00:00
InputMapper keyMap([](const InputEvent& evt) {
if (evt.intent == InputEvent::UserInput) {
Buttons::Chord chord = (Buttons::Chord)evt.asInt();
switch(chord) {
case Buttons::Circle:
return InputEvent::PowerToggle;
break;
case Buttons::Triangle:
return InputEvent::NextPattern;
break;
case Buttons::Cross:
return InputEvent::UserInput;
break;
default:
break;
2021-03-29 08:10:55 +00:00
}
}
return InputEvent::None;
}, "Keymap");
REGISTER_TASK(keyMap);
class BPM : public InputSource {
public:
BPM() : InputSource("BPM") {}
void handleEvent(const InputEvent& evt) override {
if (evt.intent == InputEvent::BeatDetect) {
m_nextBpm = millis();
m_timings.insert(millis());
Log.notice("%d timings", m_timings.size());
if (m_timings.size() >= 5) {
updateBPM();
}
}
}
2021-03-29 08:10:55 +00:00
InputEvent read() override {
if (m_bpm > 0) {
uint16_t now = millis();
if (now >= m_nextBpm) {
m_nextBpm += m_bpm;
return InputEvent{InputEvent::Beat, m_bpm};
}
if (now >= m_nextLearn && m_nextLearn != 0) {
m_timings.clear();
m_nextLearn = 0;
}
}
return InputEvent{};
}
private:
uint16_t m_bpm = 0;
uint16_t m_nextBpm = 0;
uint16_t m_nextLearn = 0;
Ringbuf<uint16_t, 7> m_timings;
void updateBPM() {
uint16_t avgDelta = 0;
for(uint8_t i = 0; i < m_timings.size() - 1; i++) {
uint16_t delta = m_timings.peek(i+1) - m_timings.peek(i);
Log.notice("Timing %d Delta %d", m_timings.peek(i), delta);
avgDelta += delta;
}
m_bpm = avgDelta / 4;
m_nextLearn = m_bpm * 5 + millis();
Log.notice("BPM is now %d", m_bpm);
uint16_t trash;
m_timings.take(trash);
}
};
STATIC_ALLOC(BPM);
STATIC_TASK(BPM);
2021-03-29 08:10:55 +00:00
Renderer configRenderer{
{&dpy},
{Static<DrainAnimation>::instance(), /*&configDisplay,*/ Static<InputBlip>::instance(), &power}
2021-03-29 08:10:55 +00:00
};
// Cycle some random colors
2021-04-10 18:10:25 +00:00
ColorSequenceInput<9> idleCycle{{
2021-03-29 08:10:55 +00:00
CRGB(0, 123, 167), // Cerulean
CRGB(80, 200, 120), // Emerald
CRGB(207, 113, 175), // Sky Magenta
CRGB(128, 0, 128), // Purple
CRGB(255, 255, 255), // White
CRGB(0, 255, 255), // Cyan
}, "IdleColors", Task::Stopped};
REGISTER_TASK(idleCycle);
2021-04-10 18:10:25 +00:00
ColorSequenceInput<7> rainbowCycle{{
CRGB(255, 0, 0), // Red
CRGB(255, 127, 0), // Yellow
CRGB(0, 255, 0), // Green
CRGB(0, 0, 255), // Blue
CRGB(128, 0, 128), // Purple
}, "Rainbow", Task::Stopped};
2021-03-29 08:10:55 +00:00
REGISTER_TASK(rainbowCycle);
/*struct ConfigInputTask: public BufferedInputSource {
2021-03-29 08:10:55 +00:00
public:
ConfigInputTask() : BufferedInputSource("ConfigInput") {}
void handleEvent(const InputEvent& evt) override {
if (evt.intent == InputEvent::UserInput) {
Buttons::Chord chord = (Buttons::Chord) evt.asInt();
switch (chord) {
case Buttons::Circle:
m_currentIntent = nextIntent();
//Log.info("Next setting... (%d)", m_currentIntent);
break;
case Buttons::CircleTriangle:
//Log.info("Increment...");
increment();
break;
case Buttons::CircleCross:
//Log.info("Decrement...");
decrement();
break;
case Buttons::Triangle:
//Log.info("Save...");
setEvent(InputEvent::SaveConfigurationRequest);
break;
default:
break;
2021-03-29 08:10:55 +00:00
}
}
}
private:
InputEvent::Intent m_currentIntent = InputEvent::SetDisplayLength;
void decrement() {
int current = 0;
switch (m_currentIntent) {
case InputEvent::SetDisplayLength:
current = Static<ConfigService>::instance()->coordMap()->pixelCount;
break;
case InputEvent::SetDisplayOffset:
current = Static<ConfigService>::instance()->coordMap()->startPixel;
break;
default:
break;
2021-03-29 08:10:55 +00:00
}
setEvent(InputEvent{m_currentIntent, current - 1});
}
void increment() {
int current = 0;
switch (m_currentIntent) {
case InputEvent::SetDisplayLength:
current = Static<ConfigService>::instance()->coordMap()->pixelCount;
break;
case InputEvent::SetDisplayOffset:
current = Static<ConfigService>::instance()->coordMap()->startPixel;
break;
default:
break;
2021-03-29 08:10:55 +00:00
}
setEvent(InputEvent{m_currentIntent, current + 1});
}
InputEvent::Intent nextIntent() {
switch (m_currentIntent) {
case InputEvent::SetDisplayLength:
return InputEvent::SetDisplayOffset;
case InputEvent::SetDisplayOffset:
return InputEvent::SetDisplayLength;
default:
return InputEvent::None;
2021-03-29 08:10:55 +00:00
}
}
};*/
2021-03-29 08:10:55 +00:00
struct ScheduleEntry {
uint8_t hour;
uint8_t brightness;
};
std::array<ScheduleEntry, 10> schedule{{
{0, 0},
{5, 0},
{6, 0},
{7, 10},
{8, 80},
{11, 120},
{18, 200},
{19, 255},
{22, 120},
{23, 20}
}};
2021-04-10 18:10:25 +00:00
class CircadianRhythm : public InputSource {
private:
bool needsUpdate = true;
public:
CircadianRhythm() : InputSource("CircadianRhythm") {}
void onStart() {
needsUpdate = true;
2021-03-29 08:10:55 +00:00
}
2021-04-10 18:10:25 +00:00
uint8_t brightnessForTime(uint8_t hour, uint8_t minute) const {
ScheduleEntry start = schedule.back();
ScheduleEntry end = schedule.front();
for(ScheduleEntry cur : schedule) {
// Find the last hour that is prior to or equal to now
if (cur.hour <= hour) {
start = cur;
} else {
break;
}
}
for(ScheduleEntry cur : schedule) {
// Find the first hour that is after now
// If no such hour exists, we should automatically wrap back to hour 0
if (cur.hour > hour) {
end = cur;
break;
}
}
2021-03-29 08:10:55 +00:00
2021-04-10 18:10:25 +00:00
if (start.hour > end.hour) {
end.hour += 24;
}
2021-03-29 08:10:55 +00:00
2021-04-10 18:10:25 +00:00
uint16_t startTime = start.hour * 60;
uint16_t endTime = end.hour * 60;
uint16_t nowTime = hour * 60 + minute;
2021-03-29 08:10:55 +00:00
2021-04-10 18:10:25 +00:00
uint16_t duration = endTime - startTime;
uint16_t curDuration = nowTime - startTime;
2021-03-29 08:10:55 +00:00
2021-04-10 18:10:25 +00:00
uint8_t frac = map8(curDuration, 0, duration);
return lerp8by8(start.brightness, end.brightness, frac);
}
2021-03-29 08:10:55 +00:00
InputEvent read() {
2021-03-29 08:10:55 +00:00
EVERY_N_SECONDS(60) {
needsUpdate = true;
}
if (needsUpdate) {
uint8_t hour = 0;
uint8_t minute = 0;
needsUpdate = false;
struct tm timeinfo;
if (Platform::getLocalTime(&timeinfo)) {
hour = timeinfo.tm_hour;
minute = timeinfo.tm_min;
} else {
hour = 0;
minute = 0;
}
Log.notice("Current time: %d:%d", hour, minute);
return InputEvent{InputEvent::SetBrightness, brightnessForTime(hour, minute)};
}
return InputEvent{};
2021-03-29 08:10:55 +00:00
}
};
STATIC_ALLOC(CircadianRhythm);
STATIC_TASK(CircadianRhythm);
2021-03-29 08:10:55 +00:00
// A special mainloop app for configuring hardware settings that reboots the
// device when the user is finished.
/*MainLoop configApp{{
2021-04-10 18:10:25 +00:00
Static<Platform>::instance(),
2021-03-29 08:10:55 +00:00
// Manage read/write of configuration data
Static<ConfigService>::instance(),
// Read hardware inputs
Static<Buttons>::instance(),
2021-03-29 08:10:55 +00:00
// Map input buttons to configuration commands
new ConfigInputTask(),
// System logging
Static<LogService>::instance(),
2021-03-29 08:10:55 +00:00
// Fill the entire display with a color, to see size
&configDisplay,
// Render some basic input feedback
&inputBlip,
// Render it all
&configRenderer,
}};*/
MainLoop configApp{std::vector<Task*>()};
2021-03-29 08:10:55 +00:00
2021-04-10 18:10:25 +00:00
TaskFunc safeModeNag([]{
static uint8_t frame = 0;
EVERY_N_SECONDS(30) {
Log.fatal("I am running in safe mode!");
2021-04-10 18:10:25 +00:00
}
EVERY_N_MILLISECONDS(16) {
frame++;
for(int i = 0; i < HardwareConfig::MAX_LED_NUM; i++) {
leds[i] = CRGB(0, 0, 0);
}
for(int idx = 0; idx < 3; idx++) {
uint8_t length = beatsin8(5, 3, HardwareConfig::MAX_LED_NUM, 0, idx * 5);
for(int i = 0; i < length; i++) {
leds[i] += CRGB(scale8(5, beatsin8(5 + i * 7, 0, 255, 0, i*3)), 0, 0);
}
}
FastLED.show();
}
});
#ifdef CONFIG_WIFI
#include "platform/arduino/WiFiTask.h"
#endif // CONFIG_WIFI
#ifdef CONFIG_OTA
#include "platform/arduino/OTA.h"
#endif // CONFIG_OTA
#ifdef CONFIG_MQTT
#include "platform/arduino/MQTTTelemetry.h"
#endif // CONFIG_MQTT
MainLoop safeModeApp{{
2021-04-10 18:10:25 +00:00
Static<Platform>::instance(),
// System logging
Static<LogService>::instance(),
&safeModeNag,
#ifdef CONFIG_WIFI
2021-03-29 08:10:55 +00:00
// ESP Wifi
Static<WiFiTask>::instance(),
#endif // CONFIG_WIFI
#ifdef CONFIG_MQTT
2021-03-29 08:10:55 +00:00
// MQTT
Static<MQTTTelemetry>::instance(),
#endif // CONFIG_MQTT
#ifdef CONFIG_OTA
// OTA Updates
Static<ArduinoOTAUpdater>::instance(),
#endif // CONFIG_OTA
2021-03-29 08:10:55 +00:00
}};
MainLoop* runner = &safeModeApp;
2021-03-29 08:10:55 +00:00
void setup() {
// Turn on,
Platform::preSetup();
2021-03-29 08:10:55 +00:00
Log.notice(u8"🐛 Booting Renderbug!");
Log.notice(u8"🐞 I am built for %d LEDs running on %dmA", HardwareConfig::MAX_LED_NUM, PSU_MILLIAMPS);
Log.notice(u8"📡 Platform %s version %s", Platform::name(), Platform::version());
2023-02-18 15:30:00 +00:00
Log.notice(u8"Setting timezone to +2 (CEST)");
Platform::setTimezone(+2);
Log.notice(u8"Setting up platform...");
2021-03-29 08:10:55 +00:00
Platform::setup();
Platform::bootSplash();
2021-03-29 08:10:55 +00:00
Log.notice(u8"💡 Starting FastLED...");
Platform::addLEDs(leds, HardwareConfig::MAX_LED_NUM);
2021-03-29 08:10:55 +00:00
// Tune in,
2021-04-10 18:10:25 +00:00
if (Platform::bootopts.isSafeMode) {
Log.notice(u8"⚠️ Starting Figment in safe mode!!!");
runner = &safeModeApp;
2021-04-10 18:10:25 +00:00
FastLED.showColor(CRGB(5, 0, 0));
FastLED.show();
} else if (Platform::bootopts.isSetup) {
Log.notice(u8"🔧 Starting Figment in configuration mode...");
//runner = &configApp;
2021-03-29 08:10:55 +00:00
} else {
Log.notice(u8"🌌 Starting Figment...");
// Render all layers to the displays
Renderer* renderer = new Renderer({&dpy}, std::vector<Figment*>{Platform::beginFigments(), Platform::endFigments()});
std::vector<Task*> defaultTasks{Platform::beginTasks(), Platform::endTasks()};
defaultTasks.push_back(renderer);
runner = new MainLoop{std::vector<Task*>{defaultTasks.begin(), defaultTasks.end()}};
2021-03-29 08:10:55 +00:00
}
Serial.flush();
runner->start();
2021-03-29 08:10:55 +00:00
2023-02-18 15:16:35 +00:00
Log.notice(u8"💽 %lu bytes of free RAM", Platform::freeRam());
2021-03-29 08:10:55 +00:00
Log.notice(u8"🚀 Setup complete! Ready to rock and roll.");
Serial.flush();
}
// Drop out.
void loop() {
EVERY_N_SECONDS(5) {
2023-02-18 15:16:35 +00:00
Log.notice("FPS: %d\tRAM: %d", FastLED.getFPS(), Platform::freeRam());
}
runner->loop();
2021-03-29 08:10:55 +00:00
}