Compare commits

..

25 Commits

Author SHA1 Message Date
8949041812 Added effect 'rainbow'. 2021-01-19 19:52:40 +00:00
d9708d9159 Better reporting of the analyzed layout at startup. 2021-01-18 05:53:50 +01:00
5676b5d63c Fixed publish_current_state() 2021-01-18 05:53:11 +01:00
e9143b6ca8 Removed Edge class. Wasn't needed. Nodes and Corners are anough. 2021-01-18 05:51:56 +01:00
db76255a2c Changed the bootup order: Connecting to WiFi first allows us to send the logs of the layout analyzer via syslog. 2021-01-16 18:27:54 +01:00
f4864dec05 Added a delay at bootup to allow pushing an OTA update in case of broken, looping code. 2021-01-16 18:15:17 +01:00
11dbea0302 LOGln now logs to a central syslog server, if available. 2021-01-16 13:41:46 +01:00
47cd48d572 We now accept and report state changes via JSON. Also added homeassistant MQTT autodiscovery. 2021-01-16 11:15:58 +00:00
a55e5e1ec2 Cleanup of stuff. 2021-01-10 16:34:06 +01:00
cc3bcb0370 Added a README with useful infos. 2021-01-10 16:33:48 +01:00
63bb2b43cf You can now define a maximum distance between colors to blend to during random effects in order to prevent extremely colorful displays. 2021-01-10 16:33:04 +01:00
4b3797f4fc Moved individual calls to node->draw() or corner->draw() to a single central call to show_all. 2021-01-10 16:30:53 +01:00
808112ebb0 Status is show during bootup and OTA by lighting some of the LEDs. 2021-01-10 16:29:30 +01:00
14f8e0fd3d Fixed short_corner calculation. 2021-01-10 16:28:08 +01:00
7651e46ee0 Speed can now be changed on-the-fly by setting speedup. 2021-01-10 16:27:49 +01:00
8fe03313ac Added "Effect" AM_STATIC ("static") and some more colors. 2021-01-08 22:22:06 +01:00
40efeee436 Corner.short_neighbours are now searched for based on the coordinates of the nodes. 2021-01-08 22:21:44 +01:00
2715d5aa6a Nodes now calculate their coordinates. But the code now only wirks with triangles. 2021-01-08 20:33:58 +01:00
d966d2ef8e Fixed MQTT stuff. 2021-01-08 17:10:46 +01:00
0d88dc3e0f Added ArduinoOTA to allow updating over-the-air. 2021-01-08 17:10:36 +01:00
31157453cb Handling MQTT commands formatted like HTTP requests. 2021-01-08 16:20:05 +01:00
25b5891f98 Added include/config.h to gitignore. 2021-01-08 05:56:22 +01:00
d7e8a8cbed Removed config.h. 2021-01-08 05:55:30 +01:00
bfc5f1dffe Added MQTT and WiFi support. 2021-01-08 05:54:55 +01:00
fa888bcfab color_blend_state extended from 0-255 to 0-1023 to allow slower / smoother effects. 2021-01-08 11:30:10 +01:00
22 changed files with 727 additions and 164 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
include/config.h

43
README.md Normal file
View File

@ -0,0 +1,43 @@
# ESPleaf
## Layout description
Layout is defined in `LAYOUT` in `config.h`.
LEDs within a node are supposed to be installed counter-clockwise. The edge where the cables enter the node is node 0. To its right (counter-clockwise, remember) is corner 0. Then edge 1, corner 1, edge 2, corner 2 before coming back to edge 0.
Thereby, the next panel can either be installed along edge 1 or edge 2. (But the cable has to go corner 0, corner 1, corner 2 first.)
First panel is ignored in `LAYOUT`. First entry in `LAYOUT` is the edge through which the cable leaves Node 0 to Node 1 - which can be either Edge 1 or Edge 2.
On the next panel, the edge the cable is coming through is called Edge 0 again. And so on.
So, `LAYOUT` countains a list of edges the cable takes to leave to the next node.
## Commands
Command can be sent via MQTT to `MQTT_TOPIC_COMMANDS`. Syntax is `key=value` or `key=value&key2=value2...`.
Valid keys are:
* `mode` sets a new mode. Valid modes are:
* `corners`
* `nodes`
* `first_corner`
* `first_node`
* `flash`
* `static`
* `off`
* `brightness` sets the overall brightness of the lamp. Values are from 0 to 255 inclusive.
* `duration` if sets, `mode` and `brightness` are set for this amount of seconds only.
* `color` sets the color for `static` and `flash` modes. A predefined color name is expected.
* `speedup` sets a speedup for faster animations. Default value 1, possible values are 1 to 255. 0 will lead to an exception.
## Startup sequence
During startup:
* 1 green corner: FastLED is initialized.
* 2 green corners: WiFi is connecting...
* 3 green corners: Layout is analyzed...
* 4 green corners: Connecting to MQTT server...
* 5 green corners (only if OTA_DELAY is set): Waiting for an OTA connection...
* Everything green (quarter of a second): Initialization done.

View File

@ -1,23 +0,0 @@
#pragma once
#define CORNERS_PER_PART 3
#define LEDS_PER_CORNER 2
// Layout definition
// Every node has EDGES_PER_PART corners and edges.
// The edge the signal comes in is edge number 0.
// All other edges are numbered counter-clockwise.
// LAYOUT contains a list of edges the signal takes.
// First node is implied.
// Examples, assuming EDGES_PER_PART == 3:
// Example: Nodes arranged in a circle: {1, 2, 2, 2, 2}
// Example: Nodes arranged in a line: {1, 2, 1, 2, 1, 2}
#define NODE_COUNT 5
#define LAYOUT {2, 1, 1, 2}
#define LED_COUNT NODE_COUNT * CORNERS_PER_PART * LEDS_PER_CORNER
#define SPEEDUP 1
//#define TEST_MODE

49
include/config.sample.h Normal file
View File

@ -0,0 +1,49 @@
#pragma once
#define CORNERS_PER_PART 3
#define LEDS_PER_CORNER 2
// Layout definition
// Every node has EDGES_PER_PART corners and edges.
// The edge the signal comes in is edge number 0.
// All other edges are numbered counter-clockwise.
// LAYOUT contains a list of edges the signal takes.
// First node is implied.
// Examples, assuming EDGES_PER_PART == 3:
// Example: Nodes arranged in a circle: {1, 2, 2, 2, 2}
// Example: Nodes arranged in a line: {1, 2, 1, 2, 1, 2}
#define NODE_COUNT 5
#define LAYOUT {2, 1, 1, 2}
#define LED_COUNT NODE_COUNT * CORNERS_PER_PART * LEDS_PER_CORNER
#define SPEEDUP 1
#define MAX_MILLIAMPS 1000
// Maximum color difference for the random effects.
// This changes the hue value +/- this value. Use a maximum value of 127, otherwise strange things might happen.
#define COLOR_DIFFERENCE 25
// If this is enabled, the node layout will be visualized at startup.
#define SHOW_LAYOUT_AT_BOOT
// Wait this many seconds for OTA requests during startup.
#define WAIT_FOR_OTA 5
#define WIFI_SSID "..."
#define WIFI_PASS "..."
#define OTA_HOSTNAME "..."
#define MQTT_CLIENT_ID "espleaf"
#define MQTT_USER "..."
#define MQTT_PASS "..."
#define MQTT_SERVER "..."
#define MQTT_SERVER_PORT 1883
#define MQTT_TOPIC_STATE "espleaf/state"
#define MQTT_TOPIC_STATE_LONG "espleaf/state_long"
#define MQTT_TOPIC_COMMANDS "esplead/cmnd"
#define SYSLOG_HOST "..."
#define SYSLOG_PORT 514
//#define TEST_MODE

View File

@ -1,14 +1,17 @@
#pragma once
class Corner;
#include "my_fastled.h"
#include <vector>
#include <list>
#include "edge.h"
#include "node.h"
class Corner {
public:
Edge* e1;
Edge* e2;
Corner(Edge* e1, Edge* e2);
Node* node;
uint8_t number;
Corner(Node* node, uint8_t number);
std::list<uint16_t> _leds;
std::vector<Corner*> _long_neighbours {};
std::vector<Corner*> _short_neighbours {};
@ -16,19 +19,19 @@ class Corner {
CRGB source_color;
CRGB target_color;
bool effect_running = false;
uint8_t color_blend_state = 255;
uint16_t color_blend_state = 1023;
uint16_t effect_id;
uint8_t effect_speed;
uint16_t effect_speed;
//bool loop();
void draw();
void blend_to(CRGB color, uint16_t effect_id=0, uint8_t effect_speed=0);
void add_led(uint16_t led_id);
void merge_leds(Corner* c);
void step();
void infect(uint8_t short_level, uint8_t long_level);
void infect(uint16_t short_level, uint16_t long_level);
bool is_finished();
void set_color(CRGB color);
bool reached_level(uint8_t level);
bool reached_level(uint16_t level);
private:
void _infect(std::vector<Corner*>* neighbours);

View File

@ -1,6 +0,0 @@
#pragma once
class Edge {
public:
Edge* neighbour = nullptr;
};

11
include/mqtt.h Normal file
View File

@ -0,0 +1,11 @@
#pragma once
#include "wifi.h"
#include "config.h"
#include <PubSubClient.h>
static PubSubClient mqtt(wifi);
void mqtt_setup();
void mqtt_loop();
void mqtt_publish_current_state(String state);

View File

@ -1,22 +1,36 @@
#pragma once
class Node;
#include <Arduino.h>
#include "config.h"
#include "edge.h"
#include "corner.h"
#include "prototypes.h"
// Delta-X data. Per direction of a triangle is a triple with Delta-X values for each direction.
static const int8_t dx[][3] = {{0, 1, -1}, {1, 0, -1}, {1, -1, 0}, {0, -1, 1}, {-1, 0, 1}, {-1, 1, 0}};
static const int8_t dy[][3] = {{-1, 0, 0}, {0, 1, 0}, {0, 0, -1}, {1, 0, 0}, {0, -1, 0}, {0, 0, 1}};
typedef struct {
int8_t x;
int8_t y;
} Coords;
class Node {
private:
uint16_t _number;
public:
uint16_t _number;
Coords coords;
uint8_t direction;
Node* neighbours[CORNERS_PER_PART];
Edge* edges[CORNERS_PER_PART];
Corner* _corners[CORNERS_PER_PART];
Node(uint16_t number);
Node(uint16_t number, Coords c, uint8_t direction);
Node* create_neighbour(uint8_t edge);
Coords coords_at_direction(uint8_t edge);
uint16_t distance_from_start = 0;
void blend_to(CRGB color, uint16_t effect_id=0, uint8_t effect_speed=0);
void set_color(CRGB color);
void infect(uint8_t level);
void infect(uint16_t level);
void step();
void draw();
};

View File

@ -2,19 +2,36 @@
#include "my_fastled.h"
#include <list>
#include <vector>
#include <map>
#include "config.h"
#include "node.h"
#include "edge.h"
#include "corner.h"
class Node;
extern std::vector<Node*> nodes;
extern std::list<Edge*> edges;
extern std::vector<Corner*> corners;
extern CRGB leds[LED_COUNT];
extern CRGB color;
enum AnimationMode {
AM_CORNERS,
AM_NODES
AM_FIRST_CORNER,
AM_NODES,
AM_FIRST_NODE,
AM_FLASH,
AM_OFF,
AM_ERROR,
AM_NONE,
AM_STATIC,
AM_RAINBOW
};
extern std::map<AnimationMode, const char*> animation_mode_names;
extern AnimationMode mode;
extern AnimationMode temp_mode;
extern unsigned long temp_mode_until;
extern int return_to_brightness;
extern uint8_t speedup;

27
include/state.h Normal file
View File

@ -0,0 +1,27 @@
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
#include "prototypes.h"
class State {
AnimationMode _mode = AM_NONE;
uint16_t _duration = 0;
int16_t _brightness = -1;
uint8_t _speedup = 0;
CRGB _color = CRGB::Black;
public:
void parse_json(char* str);
void set(String key, String value);
void commit();
static void publish_current_state();
static AnimationMode get_active_mode();
void parse_state(String state);
void parse_mode(String mode);
void set_mode(AnimationMode mode);
void set_duration(uint16_t duration);
void set_brightness(uint8_t brightness);
void set_color(JsonObject rgb);
void set_speedup(uint8_t speedup);
};

8
include/syslog.h Normal file
View File

@ -0,0 +1,8 @@
#pragma once
#include <Arduino.h>
#include <WiFiUdp.h>
#ifdef SYSLOG_HOST
void syslog(String msg, uint8_t severity=7);
#endif

View File

@ -1,8 +1,15 @@
#pragma once
#include "my_fastled.h"
#include "syslog.h"
#define LOG(...) Serial.printf(__VA_ARGS__)
#define LOGln(...) Serial.printf(__VA_ARGS__); Serial.println()
//#define LOG(...) Serial.printf(__VA_ARGS__)
//#define LOGln(...) Serial.printf(__VA_ARGS__); Serial.println()
#ifdef SYSLOG_HOST
#define LOGln(...) { char buffer[512]; snprintf(buffer, 512, __VA_ARGS__); syslog(buffer); Serial.println(buffer);}
#else
#define LOGln(...) Serial.printf(__VA_ARGS__); Serial.println()
#endif
void clear_leds();

8
include/wifi.h Normal file
View File

@ -0,0 +1,8 @@
#pragma once
#include <ESP8266WiFi.h>
#include "config.h"
static WiFiClient wifi;
void wifi_setup();

View File

@ -12,9 +12,13 @@
platform = espressif8266
board = d1_mini
framework = arduino
upload_port = /dev/cu.wchusbserial*
;upload_port = /dev/cu.wchusbserial*
upload_protocol = espota
upload_port = espleaf-prod.local
upload_speed = 921600
monitor_port = /dev/cu.wchusbserial*
monitor_speed = 74880
monitor_filters = default, time, send_on_enter, esp8266_exception_decoder
lib_deps = FastLED
lib_deps = fastled/FastLED @ 3.4.0
PubSubClient @ 2.8
ArduinoJson

View File

@ -2,7 +2,7 @@
#include "prototypes.h"
#include "tools.h"
Corner::Corner(Edge* new_e1, Edge* new_e2): e1(new_e1), e2(new_e2) {
Corner::Corner(Node* no, uint8_t nu): node(no), number(nu) {
}
@ -20,16 +20,16 @@ void Corner::_infect(std::vector<Corner*>* neighbours) {
}
void Corner::step() {
if (this->color_blend_state < 255) {
this->color = blend(this->source_color, this->target_color, color_blend_state);
this->color_blend_state = (this->color_blend_state + effect_speed > 255) ? 255 : this->color_blend_state + effect_speed;
if (this->color_blend_state==255) {
if (this->color_blend_state < 1024) {
this->color = blend(this->source_color, this->target_color, color_blend_state>>2);
this->color_blend_state = (this->color_blend_state + effect_speed > 1024) ? 1024 : this->color_blend_state + effect_speed;
if (this->color_blend_state==1024) {
this->color = this->target_color;
}
}
}
void Corner::infect(uint8_t infect_short_level, uint8_t infect_long_level) {
void Corner::infect(uint16_t infect_short_level, uint16_t infect_long_level) {
if (reached_level(infect_short_level)) {
_infect(&_short_neighbours);
}
@ -38,53 +38,29 @@ void Corner::infect(uint8_t infect_short_level, uint8_t infect_long_level) {
}
}
bool Corner::reached_level(uint8_t level) {
uint8_t old_cbs = color_blend_state >= effect_speed ? color_blend_state - effect_speed : 0;
bool Corner::reached_level(uint16_t level) {
if (color_blend_state >= 1024) return false;
uint16_t old_cbs = color_blend_state >= effect_speed ? color_blend_state - effect_speed : 0;
return (old_cbs < level && color_blend_state >= level);
}
/*bool Corner::loop() {
if (this->color_blend_state < 255) {
this->color = blend(this->source_color, this->target_color, color_blend_state);
if (255 - color_blend_state >= effect_speed) {
color_blend_state += effect_speed;
} else {
color_blend_state = 255;
}
if (color_blend_state >= 200 && color_blend_state-effect_speed<200) {
infect(&_long_neighbours);
}
if (color_blend_state>=75 && color_blend_state-effect_speed<75) {
infect(&_short_neighbours);
}
if (color_blend_state==255) {
this->color = this->target_color;
}
}
this->draw();
return color_blend_state < 255;
}*/
void Corner::blend_to(CRGB target, uint16_t eid, uint8_t effect_speed) {
LOGln("blendTo called. Corner: %p, target: %d,%d,%d, eid: %d, 'old' effect_id: %d, speed: %d", this, target.r, target.g, target.b, eid, effect_id, effect_speed);
//LOGln("blendTo called. Corner: %p, target: %d,%d,%d, eid: %d, 'old' effect_id: %d, speed: %d", this, target.r, target.g, target.b, eid, effect_id, effect_speed);
if (eid==0) {
this->effect_id = random16();
LOGln("Set effect_id to %d", this->effect_id);
//LOGln("Set effect_id to %d", this->effect_id);
} else {
if (this->effect_id == eid) {
LOGln("'Old' effect. Doing nothing.");
//LOGln("'Old' effect. Doing nothing.");
return;
}
this->effect_id = eid;
}
if (effect_speed==0) {
effect_speed = random8(3) + 1;
// Effect speed 2 - 7.
// Speed 7 @ 50fps => 3 seconds
effect_speed = random8(6) + 2;
}
this->effect_speed = effect_speed;
@ -104,10 +80,10 @@ void Corner::merge_leds(Corner* c) {
}
bool Corner::is_finished() {
return color_blend_state < 255;
return color_blend_state < 1024;
}
void Corner::set_color(CRGB color) {
this->color = color;
this->color_blend_state = 255;
this->color_blend_state = 1024;
}

View File

@ -1,20 +1,29 @@
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ArduinoOTA.h>
#include "my_fastled.h"
#include "config.h"
#include "tools.h"
#include "node.h"
#include "edge.h"
#include "corner.h"
#include "prototypes.h"
#include "mqtt.h"
#include "state.h"
#include "syslog.h"
std::vector<Node*> nodes;
std::list<Edge*> edges;
std::vector<Corner*> corners;
CRGB leds[LED_COUNT];
CRGB color = CRGB::Pink;
AnimationMode mode = AM_CORNERS;
AnimationMode temp_mode;
unsigned long temp_mode_until;
int return_to_brightness = -1;
uint8_t speedup = SPEEDUP;
unsigned long last_loop = 0;
#ifdef TEST_MODE
uint8_t base_hue = 0;
@ -25,7 +34,8 @@ bool looping;
void setup_layout() {
LOGln("Setting up layout...");
uint8_t layout[] = LAYOUT;
Node* current_node = new Node(0);
Node* current_node = new Node(0, {0, 0}, 0);
current_node->distance_from_start = 1;
nodes.push_back(current_node);
for(uint16_t i=0; i<NODE_COUNT-1; i++) {
@ -33,32 +43,85 @@ void setup_layout() {
nodes.push_back(current_node);
}
for(Node* node: nodes) {
for(Edge* edge: node->edges) {
auto e = std::find(edges.begin(), edges.end(), edge);
if (e == edges.end()) {
edges.push_back(edge);
bool verbose = false;
for (Node* n1 : nodes) {
if (verbose) LOGln("Looking for neighbours of node #%d @ %d,%d", n1->_number, n1->coords.x, n1->coords.y);
for(int edge=0; edge<CORNERS_PER_PART; edge++) {
Coords c = n1->coords_at_direction(edge);
if (verbose) LOGln(" Checking edge %d @ %d,%d...", edge, c.x, c.y);
Node* found = nullptr;
for(Node* n2 : nodes) {
if (n2 == n1) {
continue;
}
if (n2->coords.x == c.x && n2->coords.y == c.y) {
found = n2;
break;
}
}
LOGln("Node %p:", node);
for(Node* n : node->neighbours) {
LOGln(" %p", n);
if (found != nullptr) {
if (verbose) LOGln(" Found node #%d", found->_number);
uint8_t inverse_dir = (n1->direction + 2*edge + 3) % 6;
int8_t e = (inverse_dir - found->direction) % 6;
if (e < 0) e+=6;
e = e / 2;
//LOGln(" inverse_dir: %d, edge: %d", inverse_dir, edge);
int8_t e1 = (edge - 1) % CORNERS_PER_PART;
if (e1<0) e1+=CORNERS_PER_PART;
int8_t e2 = (e - 1) % CORNERS_PER_PART;
if (e2<0) e2+=CORNERS_PER_PART;
if (verbose) LOGln(" Mapping Corner #%d,%d with #%d,%d", n1->_number, edge, found->_number, e2);
n1->_corners[edge]->_short_neighbours.push_back(found->_corners[e2]);
if (verbose) LOGln(" Mapping Corner #%d,%d with #%d,%d", n1->_number, e1, found->_number, e);
n1->_corners[e1]->_short_neighbours.push_back(found->_corners[e]);
} else {
if (verbose) LOGln(" No match.");
}
}
}
for(Corner* corner: corners) {
LOGln("Corner %p:", corner);
for(auto c: corner->_long_neighbours) {
LOGln(" Long: %p", c);
bool checked_all = false;
while (!checked_all) {
checked_all = true;
for(Node* n : nodes) {
if (n->distance_from_start == 0) {
checked_all = false;
} else {
for(int i=0; i<CORNERS_PER_PART; i++) {
if (n->neighbours[i] != nullptr && (n->neighbours[i]->distance_from_start==0 || n->neighbours[i]->distance_from_start > n->distance_from_start)) {
n->neighbours[i]->distance_from_start = n->distance_from_start+1;
}
}
}
}
}
for (Node* node : nodes) {
LOGln("Node #%d:", node->_number);
LOGln(" Distance from start: %d", node->distance_from_start);
for(Corner* corner : node->_corners) {
LOGln(" Corner #%d,%d:", node->_number, corner->number);
for (auto c: corner->_long_neighbours) {
LOGln(" Long neighbour: #%d,%d", c->node->_number, c->number);
}
for (auto c: corner->_short_neighbours) {
LOGln(" Short neighbour: #%d,%d", c->node->_number, c->number);
}
}
for (int i=0; i<CORNERS_PER_PART; i++) {
if (node->neighbours[i]==nullptr) {
LOGln(" Neighbour %d: -", i);
} else {
LOGln(" Neighbour %d: #%d", i, node->neighbours[i]->_number);
}
for(auto c: corner->_short_neighbours) {
LOGln(" Short: %p", c);
}
}
LOGln("Counts:");
LOGln("Nodes: %3d", nodes.size());
LOGln("Edges: %3d", edges.size());
LOGln("Corners: %3d", corners.size());
}
@ -69,36 +132,102 @@ void setup_fastled() {
FastLED.addLeds<WS2812B, 5, GRB>(leds, LEDS_PER_CORNER * CORNERS_PER_PART * NODE_COUNT).setCorrection(TypicalLEDStrip);
LOGln("LEDs: %3d", LED_COUNT);
FastLED.setBrightness(255);
FastLED.setDither(DISABLE_DITHER);
//FastLED.setDither(DISABLE_DITHER);
FastLED.setMaxPowerInVoltsAndMilliamps(5, MAX_MILLIAMPS);
set_all_leds(CRGB::Black);
}
void setup_wifi() {
LOGln("Starting WiFi scan for RNG initialization...");
WiFi.mode(WIFI_STA);
WiFi.disconnect();
uint16_t seed = 0;
int n = WiFi.scanNetworks();
LOGln("%d WiFi networks found", n);
for(int i=0; i<n; i++) {
LOGln(" %s, %d dB", WiFi.SSID(i).c_str(), WiFi.RSSI(i));
seed = (seed << 2) | (WiFi.RSSI(i) & 0x03);
void show_all() {
for(Node* node : nodes) {
node->draw();
}
FastLED.show();
}
void show_status(uint8_t status, CRGB color=CRGB::Green) {
for (int i=0; i<status*LEDS_PER_CORNER && i<LED_COUNT; i++) {
leds[i] = color;
}
for (int i=status*LEDS_PER_CORNER; i<LED_COUNT; i++) {
leds[i] = CRGB::Black;
}
FastLED.show();
}
void display_layout() {
for(Corner* corner : corners) {
corner->set_color(CRGB::Blue);
for(Corner* c : corner->_short_neighbours) {
c->set_color(CRGB::Red);
}
for(Corner* c : corner->_long_neighbours) {
c->set_color(CRGB::Green);
}
show_all();
delay(1500);
for(Corner* c : corners) {
c->set_color(CRGB::Black);
}
}
LOGln("WiFi scan done. Generated seed is 0x%04x", seed);
random16_set_seed(seed);
}
void setup() {
Serial.begin(74880);
LOGln("ESPleaf starting.");
setup_layout();
setup_fastled();
setup_wifi();
show_status(1);
#ifdef TEST_MODE
LOGln("TEST_MODE is active!");
#else
show_status(2);
wifi_setup();
show_status(3);
setup_layout();
show_status(4);
mqtt_setup();
ArduinoOTA.setHostname(OTA_HOSTNAME);
ArduinoOTA.onProgress([&](unsigned int progress, unsigned int total){
uint8_t count = progress * corners.size() / total;
show_status(count, CRGB::Blue);
});
ArduinoOTA.onEnd([](){ show_status(0); });
ArduinoOTA.begin();
#ifdef WAIT_FOR_OTA
show_status(5);
LOGln("Waiting %d seconds for OTA requests...", WAIT_FOR_OTA);
unsigned long ota_target_time = millis() + WAIT_FOR_OTA*1000;
while (millis() < ota_target_time) {
ArduinoOTA.handle();
yield();
}
LOGln("Done waiting for OTA requests.");
#endif
show_status(255);
delay(250);
show_status(0);
#endif
LOGln("Setup done.");
#ifdef SHOW_LAYOUT_AT_BOOT
LOGln("SHOW_LAYOUT_AT_BOOT is active - showing layout...");
display_layout();
LOGln("Showing layout is done.");
#endif
for(Corner* corner : corners) {
corner->set_color(CRGB::Black);
}
State::publish_current_state();
}
void loop() {
@ -116,33 +245,72 @@ void loop() {
}
#else
// Normal mode
EVERY_N_MILLISECONDS(40 / SPEEDUP) {
mqtt_loop();
ArduinoOTA.handle();
if (speedup > 0 && (millis() - last_loop > (20 / speedup) || last_loop > millis())) {
looping = false;
if (mode == AM_CORNERS) {
AnimationMode active_mode = State::get_active_mode();
if (active_mode == AM_CORNERS || active_mode == AM_FIRST_CORNER) {
for(Corner* corner: corners) {
corner->step();
corner->infect(75, 200);
if (active_mode == AM_FIRST_CORNER) {
corner->infect(512, 512);
} else {
corner->infect(300, 600);
}
looping |= !corner->is_finished();
corner->draw();
}
if (random8(128)==0) {
corners[random16(corners.size())]->blend_to(CHSV(random8(), 255, 255));
uint16_t corner = (active_mode == AM_FIRST_CORNER) ? 0 : random16(corners.size());
CHSV color = rgb2hsv_approximate(corners[corner]->color);
corners[corner]->blend_to(CHSV(color.h - COLOR_DIFFERENCE + random8(2*COLOR_DIFFERENCE), 255, 255));
}
} else if (mode == AM_NODES) {
} else if (active_mode == AM_NODES || active_mode == AM_FIRST_NODE) {
for(Node* node : nodes) {
node->step();
node->infect(128);
node->draw();
node->infect(512);
}
if (random8(128)==0) {
nodes[random8(nodes.size())]->blend_to(CHSV(random8(), 255, 255));
uint16_t corner = (active_mode == AM_FIRST_NODE) ? 0 : random8(nodes.size());
CHSV color = rgb2hsv_approximate(corners[corner]->color);
nodes[corner]->blend_to(CHSV(color.h - COLOR_DIFFERENCE + random8(2*COLOR_DIFFERENCE), 255, 255));
}
} else if (active_mode == AM_FLASH) {
for (Node* node : nodes) {
node->step();
node->infect(512);
}
if (millis() / 1000 > last_loop / 1000) {
nodes[0]->blend_to(((millis() / 1000) % 2 == 0) ? CRGB::Black : color, 0, 64);
}
} else if (active_mode == AM_OFF || active_mode == AM_STATIC) {
for(Node* node : nodes) {
node->set_color(active_mode == AM_OFF ? CRGB::Black : color);
}
} else if (active_mode == AM_RAINBOW) {
const uint8_t speed = 5; // seconds (approx.) for full color sweep
const uint8_t diff_per_node = 5;
uint8_t base_hue = (millis() * 256 / speed) / 1000;
for(Node* node : nodes) {
node->set_color(CHSV(base_hue + diff_per_node * node->distance_from_start, 255, 255));
}
} else { // This includes AM_ERROR
for(Node* node : nodes) {
node->set_color(CRGB::Black);
}
nodes[0]->set_color(CRGB::Red);
}
last_loop = millis();
}
#endif
FastLED.show();
show_all();
}

79
src/mqtt.cpp Normal file
View File

@ -0,0 +1,79 @@
#include "mqtt.h"
#include "tools.h"
#include "prototypes.h"
#include "state.h"
void connect() {
LOGln("Connecting to MQTT broker...");
if (mqtt.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASS, MQTT_TOPIC "available", 0, true, "offline")) {
LOGln("Connected.");
mqtt.publish(MQTT_TOPIC "available", "online", true);
char buffer[40];
snprintf(buffer, 40, "online %s", wifi.localIP().toString().c_str());
mqtt.publish(MQTT_TOPIC "available_long", buffer, true);
mqtt.subscribe(MQTT_TOPIC "cmnd");
String discovery_msg = "{"
"\"~\":\"" MQTT_TOPIC "\",\"avty_t\":\"~available\",\"cmd_t\":\"~cmnd\",\"stat_t\":\"~state\","
"\"name\":\"ESPleaf\",\"schema\":\"json\","
"\"brightness\":true,\"bri_scl\":255,"
"\"effect\":true,\"effect_list\":[\"off\",\"corners\",\"nodes\",\"flash\",\"static\"],"
"\"rgb\":true}";
mqtt.publish("homeassistant/light/" HOMEASSISTANT_OBJECT_ID "/config", discovery_msg.c_str(), true);
} else {
LOGln("Connection failed. Reason: %d", mqtt.state());
delay(1000);
}
}
void callback(char* topic, byte* pl, unsigned int length) {
pl[length] = 0;
State s;
if (pl[0]=='{') {
s.parse_json((char*)pl);
} else {
String payload((char*)pl);
// Syntax: key=value&key2=value2...
String current_part;
LOGln("Received command %s", payload.c_str());
while (payload.length() > 0) {
int offset = payload.indexOf("&");
if (offset != -1) {
current_part = payload.substring(0, offset);
payload = payload.substring(offset + 1);
} else {
current_part = payload;
payload = "";
}
offset = current_part.indexOf("=");
if (offset==-1) {
LOGln("Parameter without '=' detected: %s", current_part.c_str());
continue;
}
String key = current_part.substring(0, offset);
String value = current_part.substring(offset+1);
s.set(key, value);
}
}
s.commit();
}
void mqtt_setup() {
mqtt.setServer(MQTT_SERVER, MQTT_SERVER_PORT);
mqtt.setCallback(callback);
mqtt.setSocketTimeout(1);
mqtt.setBufferSize(400);
connect();
}
void mqtt_loop() {
if (!mqtt.connected()) {
LOGln("MQTT disconnected. Reason: %d", mqtt.state());
connect();
}
mqtt.loop();
}
void mqtt_publish_current_state(String state) {
mqtt.publish(MQTT_TOPIC "state", state.c_str(), true);
};

View File

@ -2,15 +2,19 @@
#include "prototypes.h"
#include "tools.h"
Node::Node(uint16_t number) {
Node::Node(uint16_t number, Coords c, uint8_t _dir) {
_number = number;
coords = c;
direction = _dir;
LOGln("Created Node #%d at coordinates %d,%d with direction %d.", _number, coords.x, coords.y, direction);
for(int i=0; i<CORNERS_PER_PART; i++) {
edges[i] = new Edge();
neighbours[i] = nullptr;
}
Corner* last_corner = nullptr;
for(int i=0; i<CORNERS_PER_PART; i++) {
Corner* c = new Corner(edges[i], edges[(i+1) % CORNERS_PER_PART]);
Corner* c = new Corner(this, i);
for(int j=0; j<LEDS_PER_CORNER; j++) {
c->add_led(number * CORNERS_PER_PART * LEDS_PER_CORNER + i * LEDS_PER_CORNER + j);
}
@ -26,38 +30,22 @@ Node::Node(uint16_t number) {
last_corner->_long_neighbours.push_back(_corners[0]);
}
Coords Node::coords_at_direction(uint8_t edge) {
return {(int8_t)(coords.x + dx[direction][edge]), (int8_t)(coords.y + dy[direction][edge])};
}
Node* Node::create_neighbour(uint8_t edge) {
Node* node = new Node(_number + 1);
Coords new_c = coords_at_direction(edge);
int8_t new_dir = (edge==1) ? ((direction - 1) % 6) : ((direction + 1) % 6);
if (new_dir < 0) new_dir+=6;
Node* node = new Node(_number + 1, new_c, new_dir);
node->neighbours[0] = this;
neighbours[edge] = node;
node->edges[0]->neighbour = this->edges[edge];
this->edges[edge]->neighbour = node->edges[0];
node->_corners[0]->_short_neighbours.push_back(_corners[(edge-1) % CORNERS_PER_PART]);
node->_corners[CORNERS_PER_PART - 1]->_short_neighbours.push_back(_corners[edge]);
_corners[(edge-1) % CORNERS_PER_PART]->_short_neighbours.push_back(node->_corners[0]);
_corners[edge]->_short_neighbours.push_back(node->_corners[CORNERS_PER_PART - 1]);
/*
delete node->edges[0];
node->edges[0] = this->edges[edge];
Corner* c = this->corners[(edge-1) % CORNERS_PER_PART];
c->merge_leds(node->corners[0]);
delete node->corners[0];
node->corners[0] = c;
c = this->corners[edge];
c->merge_leds(node->corners[CORNERS_PER_PART-1]);
delete node->corners[CORNERS_PER_PART-1];
node->corners[CORNERS_PER_PART-1] = c;
*/
return node;
}
void Node::blend_to(CRGB color, uint16_t effect_id, uint8_t effect_speed) {
LOGln("Node::blend_to called. this:%p", this);
if (effect_speed == 0) effect_speed = random8(2)+1;
if (effect_id == 0) effect_id = random16();
for(Corner* corner : this->_corners) {
@ -83,7 +71,7 @@ void Node::set_color(CRGB color) {
}
}
void Node::infect(uint8_t level) {
void Node::infect(uint16_t level) {
if (this->_corners[0]->reached_level(level)) {
for (Node* neighbour : neighbours) {
if (neighbour == nullptr) continue;

14
src/prototypes.cpp Normal file
View File

@ -0,0 +1,14 @@
#include "prototypes.h"
std::map<AnimationMode, const char*> animation_mode_names {
{AM_CORNERS, "corners"},
{AM_FLASH, "flash"},
{AM_FIRST_CORNER, "first_corner"},
{AM_NODES, "nodes"},
{AM_FIRST_NODE, "first_node"},
{AM_OFF, "off"},
{AM_ERROR, "error"},
{AM_NONE, "NONE"},
{AM_STATIC, "static"},
{AM_RAINBOW, "rainbow"}
};

139
src/state.cpp Normal file
View File

@ -0,0 +1,139 @@
#include "state.h"
#include "tools.h"
#include "mqtt.h"
#include <ArduinoJson.h>
void State::parse_json(char* str) {
StaticJsonDocument<512> json;
deserializeJson(json, str);
if(json.containsKey("state")) parse_state(json["state"]);
if(json.containsKey("effect")) parse_mode(json["effect"]);
if(json.containsKey("duration")) set_duration(json["duration"]);
if(json.containsKey("brightness")) set_brightness(json["brightness"]);
if(json.containsKey("rgb")) set_color(json["rgb"]);
if(json.containsKey("speedup")) set_speedup(json["speedup"]);
}
void State::parse_state(String state) {
if (state.equals("ON")) {
set_mode(AM_CORNERS);
} else if (state.equals("OFF")) {
set_mode(AM_OFF);
} else {
LOGln("parse_state: Unknown state %s", state.c_str());
}
}
void State::parse_mode(String mode) {
AnimationMode m = AM_NONE;
for (std::pair<AnimationMode, const char*> pair : animation_mode_names) {
if (mode.equals(pair.second)) {
m = pair.first;
break;
}
}
if (m == AM_NONE) {
LOGln("parse_mode: Unknown mode '%s'.", mode.c_str());
} else {
set_mode(m);
}
}
void State::set_mode(AnimationMode m) {
_mode = m;
}
void State::set_duration(uint16_t d) {
_duration = d;
}
void State::set_brightness(uint8_t b) {
_brightness = b;
}
void State::set_color(JsonObject rgb) {
if (!rgb.containsKey("r") || !rgb.containsKey("g") || !rgb.containsKey("b")) {
LOGln("set_color: Invalid rgb data.");
} else {
_color = CRGB(rgb["r"], rgb["g"], rgb["b"]);
}
}
void State::set_speedup(uint8_t s) {
_speedup = s;
}
void State::set(String key, String value) {
if (key.equals("state")) { parse_state(value); }
else if (key.equals("effect") || key.equals("mode")) { parse_mode(value); }
else if (key.equals("duration")) { set_duration(value.toInt()); }
else if (key.equals("brightness")) { set_brightness(value.toInt()); }
else if (key.equals("color")) {
if (value.equals("red")) { _color = CRGB::Red; }
else if (value.equals("green")) { _color = CRGB::Green; }
else if (value.equals("blue")) { _color = CRGB::Blue; }
else if (value.equals("pink")) { _color = CRGB::Pink; }
else if (value.equals("yellow")) { _color = CRGB::Yellow; }
else if (value.equals("orange")) { _color = CRGB::Orange; }
else { LOGln("Unknown color name %s.", value.c_str());}
} else if (key.equals("speedup")) { set_speedup(value.toInt()); }
else {
LOGln("Unknown key '%s'. (For reference: Value is '%s'.)", key.c_str(), value.c_str());
}
}
void State::commit() {
if (_brightness >= 0) {
if (temp_mode_until == 0) {
return_to_brightness = FastLED.getBrightness();
}
FastLED.setBrightness(_brightness);
}
if (_mode != AM_NONE) {
if (_duration > 0) {
temp_mode = _mode;
temp_mode_until = millis() + _duration*1000;
} else {
mode = _mode;
}
}
if (_color != CRGB(0, 0, 0)) {
color = _color;
}
publish_current_state();
}
void State::publish_current_state() {
StaticJsonDocument<512> json;
json["state"] = (mode==AM_OFF) ? "OFF" : "ON";
json["brightness"] = FastLED.getBrightness();
json["effect"] = animation_mode_names[get_active_mode()];
JsonObject rgb = json.createNestedObject("rgb");
rgb["r"] = color.r;
rgb["g"] = color.g;
rgb["b"] = color.b;
String result = "";
serializeJson(json, result);
LOGln("Reporting current state: %s", result.c_str());
mqtt_publish_current_state(result);
}
AnimationMode State::get_active_mode() {
AnimationMode active_mode = mode;
if (temp_mode_until > 0) {
if (temp_mode_until>millis()) {
active_mode = temp_mode;
} else {
temp_mode_until = 0;
if (return_to_brightness != -1) {
FastLED.setBrightness(return_to_brightness);
return_to_brightness = -1;
}
State::publish_current_state();
}
}
return active_mode;
}

21
src/syslog.cpp Normal file
View File

@ -0,0 +1,21 @@
#include "syslog.h"
#include "config.h"
#ifdef SYSLOG_HOST
static uint16_t syslog_msg_id = 1;
void syslog(String msg, uint8_t severity) {
uint8_t facility = 16; // local0
if (severity > 7) severity = 7;
WiFiUDP udp;
udp.beginPacket(SYSLOG_HOST, SYSLOG_PORT);
udp.write("<");
udp.write(String(facility * 8 + severity).c_str());
udp.write(">1 - " OTA_HOSTNAME " core 1 ");
udp.write(String(syslog_msg_id++).c_str());
udp.write(" - ");
udp.write(msg.c_str());
udp.endPacket();
}
#endif

15
src/wifi.cpp Normal file
View File

@ -0,0 +1,15 @@
#include "wifi.h"
#include "tools.h"
void wifi_setup() {
Serial.printf("Connecting to WiFi %s...", WIFI_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println();
LOGln("Connected as %s", WiFi.localIP().toString().c_str());
random16_add_entropy(micros());
}