move pixel plugin to separate repo

This commit is contained in:
2018-11-15 18:00:07 +01:00
parent 73495201eb
commit 3a45f8626e
10 changed files with 3 additions and 1011 deletions

View File

@@ -1,471 +0,0 @@
/**
* Original NeoPattern code by Bill Earl
* https://learn.adafruit.com/multi-tasking-the-arduino-part-3/overview
*
* TODO
* - cleanup the mess
* - fnc table for patterns to replace switch case
*
* Custom modifications by 0x1d:
* - default OnComplete callback that sets pattern to reverse
* - separate animation update from timer; Update now updates directly, UpdateScheduled uses timer
*/
#ifndef __NeoPattern_INCLUDED__
#define __NeoPattern_INCLUDED__
#include <Adafruit_NeoPixel.h>
using namespace std;
using namespace std::placeholders;
// Pattern types supported:
enum pattern
{
NONE = 0,
RAINBOW_CYCLE = 1,
THEATER_CHASE = 2,
COLOR_WIPE = 3,
SCANNER = 4,
FADE = 5,
FIRE = 6
};
// Patern directions supported:
enum direction
{
FORWARD,
REVERSE
};
// NeoPattern Class - derived from the Adafruit_NeoPixel class
class NeoPattern : public Adafruit_NeoPixel
{
public:
// Member Variables:
pattern ActivePattern = RAINBOW_CYCLE; // which pattern is running
direction Direction = FORWARD; // direction to run the pattern
unsigned long Interval = 150; // milliseconds between updates
unsigned long lastUpdate = 0; // last update of position
uint32_t Color1 = 0;
uint32_t Color2 = 0; // What colors are in use
uint16_t TotalSteps = 32; // total number of steps in the pattern
uint16_t Index; // current step within the pattern
uint16_t completed = 0;
// FIXME return current NeoPatternState
void (*OnComplete)(int); // Callback on completion of pattern
uint8_t *frameBuffer;
int bufferSize = 0;
// Constructor - calls base-class constructor to initialize strip
NeoPattern(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)(int))
: Adafruit_NeoPixel(pixels, pin, type)
{
frameBuffer = (uint8_t *)malloc(768);
OnComplete = callback;
TotalSteps = numPixels();
begin();
}
NeoPattern(uint16_t pixels, uint8_t pin, uint8_t type)
: Adafruit_NeoPixel(pixels, pin, type)
{
frameBuffer = (uint8_t *)malloc(768);
TotalSteps = numPixels();
begin();
}
void handleStream(uint8_t *data, size_t len)
{
//const uint16_t *data16 = (uint16_t *)data;
bufferSize = len;
memcpy(frameBuffer, data, len);
}
void drawFrameBuffer(int w, uint8_t *frame, int length)
{
for (int i = 0; i < length; i++)
{
uint8_t r = frame[i];
uint8_t g = frame[i + 1];
uint8_t b = frame[i + 2];
setPixelColor(i, r, g, b);
}
}
void onCompleteDefault(int pixels)
{
//Serial.println("onCompleteDefault");
// FIXME no specific code
if (ActivePattern == THEATER_CHASE)
{
return;
}
Reverse();
//Serial.println("pattern completed");
}
// Update the pattern
void Update()
{
switch (ActivePattern)
{
case RAINBOW_CYCLE:
RainbowCycleUpdate();
break;
case THEATER_CHASE:
TheaterChaseUpdate();
break;
case COLOR_WIPE:
ColorWipeUpdate();
break;
case SCANNER:
ScannerUpdate();
break;
case FADE:
FadeUpdate();
break;
case FIRE:
Fire(50, 120);
break;
default:
if (bufferSize > 0)
{
drawFrameBuffer(TotalSteps, frameBuffer, bufferSize);
}
break;
}
}
void UpdateScheduled()
{
if ((millis() - lastUpdate) > Interval) // time to update
{
lastUpdate = millis();
Update();
}
}
// Increment the Index and reset at the end
void Increment()
{
completed = 0;
if (Direction == FORWARD)
{
Index++;
if (Index >= TotalSteps)
{
Index = 0;
completed = 1;
if (OnComplete != NULL)
{
OnComplete(numPixels()); // call the comlpetion callback
}
else
{
onCompleteDefault(numPixels());
}
}
}
else // Direction == REVERSE
{
--Index;
if (Index <= 0)
{
Index = TotalSteps - 1;
completed = 1;
if (OnComplete != NULL)
{
OnComplete(numPixels()); // call the comlpetion callback
}
else
{
onCompleteDefault(numPixels());
}
}
}
}
// Reverse pattern direction
void Reverse()
{
if (Direction == FORWARD)
{
Direction = REVERSE;
Index = TotalSteps - 1;
}
else
{
Direction = FORWARD;
Index = 0;
}
}
// Initialize for a RainbowCycle
void RainbowCycle(uint8_t interval, direction dir = FORWARD)
{
ActivePattern = RAINBOW_CYCLE;
Interval = interval;
TotalSteps = 255;
Index = 0;
Direction = dir;
}
// Update the Rainbow Cycle Pattern
void RainbowCycleUpdate()
{
for (int i = 0; i < numPixels(); i++)
{
setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
}
show();
Increment();
}
// Initialize for a Theater Chase
void TheaterChase(uint32_t color1, uint32_t color2, uint16_t interval, direction dir = FORWARD)
{
ActivePattern = THEATER_CHASE;
Interval = interval;
TotalSteps = numPixels();
Color1 = color1;
Color2 = color2;
Index = 0;
Direction = dir;
}
// Update the Theater Chase Pattern
void TheaterChaseUpdate()
{
for (int i = 0; i < numPixels(); i++)
{
if ((i + Index) % 3 == 0)
{
setPixelColor(i, Color1);
}
else
{
setPixelColor(i, Color2);
}
}
show();
Increment();
}
// Initialize for a ColorWipe
void ColorWipe(uint32_t color, uint8_t interval, direction dir = FORWARD)
{
ActivePattern = COLOR_WIPE;
Interval = interval;
TotalSteps = numPixels();
Color1 = color;
Index = 0;
Direction = dir;
}
// Update the Color Wipe Pattern
void ColorWipeUpdate()
{
setPixelColor(Index, Color1);
show();
Increment();
}
// Initialize for a SCANNNER
void Scanner(uint32_t color1, uint8_t interval)
{
ActivePattern = SCANNER;
Interval = interval;
TotalSteps = (numPixels() - 1) * 2;
Color1 = color1;
Index = 0;
}
// Update the Scanner Pattern
void ScannerUpdate()
{
for (int i = 0; i < numPixels(); i++)
{
if (i == Index) // Scan Pixel to the right
{
setPixelColor(i, Color1);
}
else if (i == TotalSteps - Index) // Scan Pixel to the left
{
setPixelColor(i, Color1);
}
else // Fading tail
{
setPixelColor(i, DimColor(getPixelColor(i)));
}
}
show();
Increment();
}
// Initialize for a Fade
void Fade(uint32_t color1, uint32_t color2, uint16_t steps, uint8_t interval, direction dir = FORWARD)
{
ActivePattern = FADE;
Interval = interval;
TotalSteps = steps;
Color1 = color1;
Color2 = color2;
Index = 0;
Direction = dir;
}
// Update the Fade Pattern
void FadeUpdate()
{
// Calculate linear interpolation between Color1 and Color2
// Optimise order of operations to minimize truncation error
uint8_t red = ((Red(Color1) * (TotalSteps - Index)) + (Red(Color2) * Index)) / TotalSteps;
uint8_t green = ((Green(Color1) * (TotalSteps - Index)) + (Green(Color2) * Index)) / TotalSteps;
uint8_t blue = ((Blue(Color1) * (TotalSteps - Index)) + (Blue(Color2) * Index)) / TotalSteps;
ColorSet(Color(red, green, blue));
show();
Increment();
}
// Calculate 50% dimmed version of a color (used by ScannerUpdate)
uint32_t DimColor(uint32_t color)
{
// Shift R, G and B components one bit to the right
uint32_t dimColor = Color(Red(color) >> 1, Green(color) >> 1, Blue(color) >> 1);
return dimColor;
}
// Set all pixels to a color (synchronously)
void ColorSet(uint32_t color)
{
for (int i = 0; i < numPixels(); i++)
{
setPixelColor(i, color);
}
show();
}
// Returns the Red component of a 32-bit color
uint8_t Red(uint32_t color)
{
return (color >> 16) & 0xFF;
}
// Returns the Green component of a 32-bit color
uint8_t Green(uint32_t color)
{
return (color >> 8) & 0xFF;
}
// Returns the Blue component of a 32-bit color
uint8_t Blue(uint32_t color)
{
return color & 0xFF;
}
// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos)
{
//if(WheelPos == 0) return Color(0,0,0);
WheelPos = 255 - WheelPos;
if (WheelPos < 85)
{
return Color(255 - WheelPos * 3, 0, WheelPos * 3);
}
else if (WheelPos < 170)
{
WheelPos -= 85;
return Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
else
{
WheelPos -= 170;
return Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}
}
/**
* Effects from https://www.tweaking4all.com/hardware/arduino/adruino-led-strip-effects/
*/
void Fire(int Cooling, int Sparking)
{
byte heat[numPixels()];
int cooldown;
// Step 1. Cool down every cell a little
for (int i = 0; i < numPixels(); i++)
{
cooldown = random(0, ((Cooling * 10) / numPixels()) + 2);
if (cooldown > heat[i])
{
heat[i] = 0;
}
else
{
heat[i] = heat[i] - cooldown;
}
}
// Step 2. Heat from each cell drifts 'up' and diffuses a little
for (int k = numPixels() - 1; k >= 2; k--)
{
heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2]) / 3;
}
// Step 3. Randomly ignite new 'sparks' near the bottom
if (random(255) < Sparking)
{
int y = random(7);
heat[y] = heat[y] + random(160, 255);
//heat[y] = random(160,255);
}
// Step 4. Convert heat to LED colors
for (int j = 0; j < numPixels(); j++)
{
setPixelHeatColor(j, heat[j]);
}
showStrip();
}
void setPixelHeatColor(int Pixel, byte temperature)
{
// Scale 'heat' down from 0-255 to 0-191
byte t192 = round((temperature / 255.0) * 191);
// calculate ramp up from
byte heatramp = t192 & 0x3F; // 0..63
heatramp <<= 2; // scale up to 0..252
// figure out which third of the spectrum we're in:
if (t192 > 0x80)
{ // hottest
setPixel(Pixel, 255, 255, heatramp);
}
else if (t192 > 0x40)
{ // middle
setPixel(Pixel, 255, heatramp, 0);
}
else
{ // coolest
setPixel(Pixel, heatramp, 0, 0);
}
}
void setPixel(int Pixel, byte red, byte green, byte blue)
{
setPixelColor(Pixel, Color(red, green, blue));
}
void showStrip()
{
show();
}
};
#endif

View File

@@ -1,97 +0,0 @@
#ifndef __NEOPATTERN_STATE__
#define __NEOPATTERN_STATE__
#include <ArduinoJson.h>
#include "NeoPattern_api_json.h"
#include "NeoPattern_api_modes.cpp"
#include "utils_print.h"
#include "JsonStruct.h"
// TODO move ARRAY_LENGTH to core lib
#define ARRAY_LENGTH(array) sizeof(array)/sizeof(array[0])
struct NeoPixelConfig : public JsonStruct {
// FIXME constants!
int pin = 4;
int length = 8;
int brightness = 100;
int updateInterval = 100;
int defaultColor = 100; // FIXME remove unused
void mapJsonObject(JsonObject& root) {
root["pin"] = pin;
root["length"] = length;
root["brightness"] = brightness;
root["updateInterval"] = updateInterval;
root["defaultColor"] = defaultColor;
}
void fromJsonObject(JsonObject& json) {
pin = getIntAttrFromJson(json, "pin", pin);
length = getIntAttrFromJson(json, "length", length);
brightness = getIntAttrFromJson(json, "brightness", brightness);
updateInterval = getIntAttrFromJson(json, "updateInterval", updateInterval);
defaultColor = getIntAttrFromJson(json, "defaultColor", defaultColor);
}
};
struct NeoPatternState : public JsonStruct {
uint pattern = 0;
uint color= 0;
uint color2= 0;
uint totalSteps = 16;
uint brightness = 64;
void mapJsonObject(JsonObject& root) {
root["pattern"] = pattern;
root["color"] = color;
root["color2"] = color2;
root["totalSteps"] = totalSteps;
root["brightness"] = brightness;
}
// Map a json object to this struct.
void fromJsonObject(JsonObject& json){
if(!verifyJsonObject(json)){
PRINT_MSG(Serial, "fromJsonObject", "cannot parse JSON");
valid = 0;
return;
}
color = getIntAttrFromJson(json, "color", color);
color2 = getIntAttrFromJson(json, "color2", color2);
pattern = getIntAttrFromJson(json, "pattern", pattern);
brightness = getIntAttrFromJson(json, "brightness", brightness);
totalSteps = getIntAttrFromJson(json, "totalSteps", totalSteps);
valid = 1;
};
};
struct NeoPatternDto : public JsonStruct {
uint mode;
uint value;
const char* valueStr;
// ------------------------------------------------------------------------------------------
//Check if given object is valid and contains fields: JSON_MODE_NODE, JSON_VALUE
int verifyJsonObject(JsonObject& json){
return json.success()
&& json.containsKey(JSON_MODE_NODE)
&& json.containsKey(JSON_VALUE);
};
void mapJsonObject(JsonObject& root) {
root[JSON_MODE_NODE] = mode;
root[JSON_VALUE] = value;
}
// Map a json object to this struct.
void fromJsonObject(JsonObject& json){
if(!verifyJsonObject(json)){
PRINT_MSG(Serial, "fromJsonObject", "cannot parse JSON");
valid = 0;
return;
}
mode = atoi(json[JSON_MODE_NODE]);
mode = mode < ARRAY_LENGTH(PIXEL_FNCS) ? mode : 0;
value = json[JSON_VALUE];
valueStr = json[JSON_VALUE];
valid = 1;
};
};
#endif

View File

@@ -1,16 +0,0 @@
#ifndef __PIXEL_JSON_API__
#define __PIXEL_JSON_API__
/*
modes: PIXELS_OFF = 0, COLOR_WHEEL_MODE = 1, COLOR_MODE = 2, PATTERN_MODE = 3
patterns: NONE = 0, RAINBOW_CYCLE = 1, THEATER_CHASE = 2, COLOR_WIPE = 3, SCANNER = 4, FADE = 5
{
"mode": int,
"value": int || String
}
*/
#define JSON_MODE_NODE "mode"
#define JSON_VALUE "value"
#define JSON_ACTION_NODE "action"
#endif

View File

@@ -1,64 +0,0 @@
#ifndef __NEOPATTERN_API_MODES__
#define __NEOPATTERN_API_MODES__
#include "NeoPattern.cpp"
enum PIXEL_MODE { PIXELS_OFF = 0, COLOR_WHEEL_MODE = 1, COLOR_MODE = 2, PATTERN_MODE = 3};
typedef void (*PIXEL_FP)(NeoPattern*, const char *);
/*
Array of function pointers to be used as lookup table using the int values of PIXEL_MODE.
TODO header file + separate functions instead of lambdas
*/
const PIXEL_FP PIXEL_FNCS[] = {
/*
PIXESL_OFF
Sets all pixels to black.
*/
[](NeoPattern* pixels, const char *color){
pixels->clear();
pixels->ColorSet(0);
},
/*
COLOR_WHEEL_MODE
Input: integer color from 0 to 155
Uses the color wheel to set a color.
If given integer is <= 1, set the color to black.
By using this function, Color1 and Color2 is set on the pixels;
Color1 = new color, Color2 = last color.
*/
[](NeoPattern* pixels, const char *color){
int c1 = atoi(color);
int c2 = pixels->Color1;
pixels->Color1 = c1;
pixels->Color2 = c2;
pixels->ActivePattern = NONE;
if(c1 <= 1) {
pixels->ColorSet(0);
return;
}
pixels->ColorSet(pixels->Wheel(c1));
},
/*
COLOR_MODE
sets the color from an rgb int
*/
[](NeoPattern* pixels, const char *color){
pixels->ActivePattern = NONE;
pixels->ColorSet(atoi(color));
},
/*
PATTERN_MODE
Input: id of the pattern
Sets the active pattern on the strip.
As every pattern has another API, all fields need to be set before, for example by using COLOR_WHEEL_MODE.
*/
[](NeoPattern* pixels, const char *id){
pattern p = (pattern)atoi(id);
//pixels->Interval = 50;
//pixels->TotalSteps = pixels->numPixels();
pixels->ActivePattern = p;
}
};
#endif

View File

@@ -1,25 +0,0 @@
#include "utils_print.h"
int FORMAT_BUFFER_SIZE(const char* format, ...) {
va_list args;
va_start(args, format);
int result = vsnprintf(NULL, 0, format, args);
va_end(args);
return result + 1; // safe byte for \0
}
void PRINT_MSG(Print &out, const char* prefix, const char* format, ...) {
if(SPROCKET_PRINT){
out.print(String(prefix) + String(": "));
char formatString[128], *ptr;
strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
// null terminate - leave last char since we might need it in worst case for result's \0
formatString[ sizeof(formatString)-2 ]='\0';
ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
va_list args;
va_start (args,format);
vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
va_end (args);
formatString[ sizeof(formatString)-1 ]='\0';
out.println(ptr);
}
}

View File

@@ -1,15 +0,0 @@
#ifndef __SPROCKET_UTILS__
#define __SPROCKET_UTILS__
#include <Arduino.h>
#ifndef SPROCKET_PRINT
#define SPROCKET_PRINT 1
#endif
// TODO move to sprocket
int FORMAT_BUFFER_SIZE(const char* format, ...);
void PRINT_MSG(Print &out, const char* prefix, const char* format, ...);
#endif

View File

@@ -1,132 +0,0 @@
#ifndef __WebUtils_H___
#define __WebUtils_H___
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include <AsyncWebSocket.h>
#include <ESPAsyncTCP.h>
class WebUtils {
public:
static String getRequestParameterOrDefault(AsyncWebServerRequest *request, String param, String defaultValue, bool isPost = true){
if(request->hasParam(param, isPost)) {
return request->getParam(param, isPost)->value();
}
return defaultValue;
}
static String parseFrame(AwsEventType type, void * arg, uint8_t *data, size_t len) {
String msg = "";
if(type == WS_EVT_DATA){
AwsFrameInfo * info = (AwsFrameInfo*)arg;
if(info->opcode == WS_TEXT){
for(size_t i=0; i < info->len; i++) {
msg += (char) data[i];
}
} else {
char buff[3];
for(size_t i=0; i < info->len; i++) {
sprintf(buff, "%02x ", (uint8_t) data[i]);
msg += buff ;
}
}
}
return msg;
}
static String parseFrameAsString(AwsEventType type, void * arg, uint8_t *data, size_t len, int start = 0) {
String msg = "";
if(type == WS_EVT_DATA){
AwsFrameInfo * info = (AwsFrameInfo*)arg;
//if(info->final && info->index == 0 && info->len == len){
if(info->opcode == WS_TEXT){
for(size_t i=start; i < info->len; i++) {
msg += (char) data[i];
}
} else {
char buff[3];
for(size_t i=start; i < info->len; i++) {
sprintf(buff, "%02x ", (uint8_t) data[i]);
msg += buff ;
}
}
//}
}
return msg;
}
/* static void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len) {
if(type == WS_EVT_CONNECT){
Serial.printf("ws[%s][%u] connect\n", server->url(), client->id());
client->printf("Hello Client %u :)", client->id());
client->ping();
} else if(type == WS_EVT_DISCONNECT){
Serial.printf("ws[%s][%u] disconnect: %u\n", server->url(), client->id());
} else if(type == WS_EVT_ERROR){
Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t*)arg), (char*)data);
} else if(type == WS_EVT_PONG){
Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len)?(char*)data:"");
} else if(type == WS_EVT_DATA){
AwsFrameInfo * info = (AwsFrameInfo*)arg;
String msg = "";
//the whole message is in a single frame and we got all of it's data
if(info->final && info->index == 0 && info->len == len){
Serial.printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT)?"text":"binary", info->len);
if(info->opcode == WS_TEXT){
for(size_t i=0; i < info->len; i++) {
msg += (char) data[i];
}
} else {
char buff[3];
for(size_t i=0; i < info->len; i++) {
sprintf(buff, "%02x ", (uint8_t) data[i]);
msg += buff ;
}
}
Serial.printf("%s\n",msg.c_str());
if(info->opcode == WS_TEXT)
client->text("I got your text message");
else
client->binary("I got your binary message");
}
//message is comprised of multiple frames or the frame is split into multiple packets
else {
if(info->index == 0){
if(info->num == 0)
Serial.printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary");
Serial.printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len);
}
Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT)?"text":"binary", info->index, info->index + len);
if(info->opcode == WS_TEXT){
for(size_t i=0; i < info->len; i++) {
msg += (char) data[i];
}
} else {
char buff[3];
for(size_t i=0; i < info->len; i++) {
sprintf(buff, "%02x ", (uint8_t) data[i]);
msg += buff ;
}
}
Serial.printf("%s\n",msg.c_str());
if((info->index + len) == info->len){
Serial.printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len);
if(info->final){
Serial.printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary");
if(info->message_opcode == WS_TEXT)
client->text("I got your text message");
else
client->binary("I got your binary message");
}
}
}
}
} */
};
#endif

View File

@@ -24,6 +24,9 @@ lib_deps =
ArduinoJson
Adafruit NeoPixel
ESPAsyncTCP
https://gitlab.com/wirelos/sprocket-lib.git#develop
https://gitlab.com/wirelos/sprocket-plugin-neopixel.git
https://gitlab.com/wirelos/sprocket-plugin-web.git
[env:build]
src_filter = +<*> -<wifiMesh/> +<wifi/>
@@ -39,7 +42,6 @@ lib_deps = ${common.lib_deps}
ESP8266mDNS
ESP Async WebServer
painlessMesh
https://gitlab.com/wirelos/sprocket-lib.git#develop
https://gitlab.com/wirelos/sprocket-plugin-web.git
@@ -54,7 +56,6 @@ build_flags = -Wl,-Teagle.flash.4m1m.ld
-DSPROCKET_PRINT=1
lib_deps = ${common.lib_deps}
painlessMesh
https://gitlab.com/wirelos/sprocket-lib.git#develop
[env:release]
src_filter = +<*> -<wifiMesh/> +<wifi/>
@@ -66,7 +67,6 @@ framework = ${common.framework}
build_flags = -Wl,-Teagle.flash.4m1m.ld
-DSPROCKET_PRINT=0
lib_deps = ${common.lib_deps}
https://gitlab.com/wirelos/sprocket-lib.git#develop
https://gitlab.com/wirelos/sprocket-plugin-web.git

View File

@@ -1,130 +0,0 @@
#include "PixelPlugin.h"
PixelPlugin::PixelPlugin(NeoPattern *neoPattern)
{
pixels = neoPattern;
loadConfigFromFile();
applyConfig(pixelConfig);
defaultAnimation();
}
PixelPlugin::PixelPlugin(PixelConfig cfg)
{
pixelConfig.brightness = cfg.brightness;
pixelConfig.pin = cfg.pin;
pixelConfig.length = cfg.length;
pixelConfig.updateInterval = cfg.updateInterval;
loadConfigFromFile();
pixels = new NeoPattern(pixelConfig.length, pixelConfig.pin, NEO_GRB + NEO_KHZ800);
applyConfig(pixelConfig);
defaultAnimation();
}
PixelPlugin::PixelPlugin()
{
loadConfigFromFile();
pixels = new NeoPattern(pixelConfig.length, pixelConfig.pin, NEO_GRB + NEO_KHZ800);
applyConfig(pixelConfig);
defaultAnimation();
}
void PixelPlugin::loadConfigFromFile(){
if (SPIFFS.begin()){
pixelConfig.fromFile(PIXEL_CONFIG_FILE);
}
}
void PixelPlugin::applyConfig(NeoPixelConfig cfg)
{
pixels->setBrightness(pixelConfig.brightness);
}
void PixelPlugin::defaultAnimation() {
pixels->RainbowCycle(pixelConfig.updateInterval);
animate();
}
void PixelPlugin::activate(Scheduler *userScheduler)
{
animation.set(TASK_MILLISECOND * pixelConfig.updateInterval, TASK_FOREVER, bind(&PixelPlugin::animate, this));
userScheduler->addTask(animation);
animation.enable();
subscribe("pixels/colorWheel", bind(&PixelPlugin::colorWheel, this, _1));
subscribe("pixels/color", bind(&PixelPlugin::setColor, this, _1));
subscribe("pixels/color2", bind(&PixelPlugin::setColor2, this, _1));
subscribe("pixels/pattern", bind(&PixelPlugin::setPattern, this, _1));
subscribe("pixels/totalSteps", bind(&PixelPlugin::setTotalSteps, this, _1));
subscribe("pixels/brightness", bind(&PixelPlugin::setBrightness, this, _1));
subscribe("pixels/state", bind(&PixelPlugin::setState, this, _1));
PRINT_MSG(Serial, SPROCKET_TYPE, "NeoPixels activated");
}
void PixelPlugin::setState(String msg)
{
PRINT_MSG(Serial, SPROCKET_TYPE, msg.c_str());
state.fromJsonString(msg);
//pixels->setBrightness(state.brightness);
//pixels->ColorSet(state.color);
pixels->Index = 0;
pixels->Color1 = state.color;
pixels->Color2 = state.color2;
pixels->TotalSteps = state.totalSteps;
pixels->ActivePattern = (pattern)state.pattern;
pixels->Direction = FORWARD;
}
void PixelPlugin::colorWheel(String msg)
{
int color = atoi(msg.c_str());
pixels->ActivePattern = NONE;
pixels->ColorSet(pixels->Wheel(color));
}
void PixelPlugin::setTotalSteps(String msg)
{
pixels->TotalSteps = atoi(msg.c_str());
}
void PixelPlugin::setBrightness(String msg)
{
int inVal = atoi(msg.c_str());
pixels->setBrightness(inVal);
pixels->show();
}
void PixelPlugin::setColor(String msg)
{
pixels->ActivePattern = NONE;
pixels->Color1 = atoi(msg.c_str());
//if(pixels->ActivePattern == NONE){
pixels->ColorSet(pixels->Color1);
//}
}
void PixelPlugin::setColor2(String msg)
{
pixels->Color2 = atoi(msg.c_str());
}
void PixelPlugin::setPattern(String msg)
{
pixels->Index = 0;
pixels->Direction = FORWARD;
pixels->ActivePattern = (pattern)atoi(msg.c_str());
}
void PixelPlugin::animate()
{
pixels->Update();
yield();
}
void PixelPlugin::enable()
{
animation.enable();
}
void PixelPlugin::disable()
{
animation.disable();
}

View File

@@ -1,58 +0,0 @@
#ifndef __PIXEL_PLUGIN__
#define __PIXEL_PLUGIN__
#define _TASK_SLEEP_ON_IDLE_RUN
#define _TASK_STD_FUNCTION
#include "TaskSchedulerDeclarations.h"
#include "MeshNet.h"
#include "Plugin.h"
#include "NeoPatternDto.h"
#include "NeoPattern.cpp"
#include "config.h"
using namespace std;
using namespace std::placeholders;
#ifndef PIXEL_CONFIG_FILE
#define PIXEL_CONFIG_FILE "/pixelConfig.json"
#endif
struct PixelConfig
{
int pin;
int length;
int brightness;
int updateInterval;
};
class PixelPlugin : public Plugin
{
private:
NeoPixelConfig pixelConfig;
NeoPattern *pixels;
NeoPatternState state;
public:
Task animation;
PixelPlugin(PixelConfig cfg);
PixelPlugin(NeoPattern *neoPattern);
PixelPlugin();
void loadConfigFromFile();
void applyConfig(NeoPixelConfig cfg);
void applyConfigFromFile();
void activate(Scheduler *userScheduler);
void defaultAnimation();
void setState(String msg);
void colorWheel(String msg);
void setTotalSteps(String msg);
void setBrightness(String msg);
void setColor(String msg);
void setColor2(String msg);
void setPattern(String msg);
void animate();
void enable();
void disable();
};
#endif