added native alexa support, new patterns, sound reactive mode, code cleanup, new documentation

This commit is contained in:
Lorenz Nimmervoll 2020-02-01 09:39:15 +01:00
parent 619d2fc747
commit cbf71bfd21
7 changed files with 899 additions and 496 deletions

44
.gitignore vendored Normal file
View File

@ -0,0 +1,44 @@
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
# Visual studio crap
*.sln
*.vcxproj
*.filters
*.user
__vm/
Release/
.vs/
Secrets.h
CppProperties.json

View File

@ -1,47 +0,0 @@
{
"configurations": [
{
"name": "Visual Micro",
"intelliSenseMode": "msvc-x64",
"includePath": [
"${projectRoot}..\\esp8266-fastled-webserver",
"D:\\Music\\Documents\\Arduino\\libraries\\FastLED",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\libraries\\ESP8266WiFi\\src",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\libraries\\ESP8266WebServer\\src",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\libraries\\ESP8266HTTPUpdateServer\\src",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\libraries\\EEPROM",
"S:\\Software\\Arduino\\libraries",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\libraries",
"D:\\Music\\Documents\\Arduino\\libraries",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\cores\\esp8266",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\cores\\esp8266\\libb64",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\cores\\esp8266\\spiffs",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\cores\\esp8266\\umm_malloc",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\variants\\d1_mini",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\tools\\sdk\\include",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\tools\\sdk\\lwip2\\include",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\tools\\sdk\\libc\\xtensa-lx106-elf\\include",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\tools\\xtensa-lx106-elf-gcc\\1.20.0-26-gb404fb9-2\\xtensa-lx106-elf\\include\\c++\\4.8.2",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\tools\\xtensa-lx106-elf-gcc\\1.20.0-26-gb404fb9-2\\xtensa-lx106-elf\\include\\c++\\4.8.2\\xtensa-lx106-elf",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\tools\\xtensa-lx106-elf-gcc\\1.20.0-26-gb404fb9-2\\xtensa-lx106-elf\\include",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\tools\\xtensa-lx106-elf-gcc\\1.20.0-26-gb404fb9-2\\lib\\gcc\\xtensa-lx106-elf\\4.8.2\\include",
"${projectRoot}..\\..\\..\\..\\AppData\\Local\\arduino15\\packages\\esp8266\\hardware\\esp8266\\2.4.1\\tools\\sdk\\include"
],
"defines": [
"__ESP8266_ESp8266__",
"__ESP8266_ESP8266__",
"__ets__",
"ICACHE_FLASH",
"F_CPU=80000000L",
"LWIP_OPEN_SRC",
"TCP_MSS=536",
"ARDUINO=10807",
"ARDUINO_ESP8266_WEMOS_D1MINI",
"ARDUINO_ARCH_ESP8266",
"ESP8266",
"__cplusplus=201103L",
"_VMICRO_INTELLISENSE"
]
}
]
}

View File

@ -0,0 +1,251 @@
# Node-RED & Alexa integration Setup
## Features
### **Amazon Alexa Integration** (optional)
It works with any language that is supported by Alexa and can be easily expanded to support more activities or patterns. How you want to call them (Nanoleaf, Nanoleafs, Nano, Triangles) must be set in the setup of the devices.
#### **Commands**:
- Turn on/off
- Control Brightness
- Control Pattern Speed
- Set Color
- Set into Rainbow mode
- Enable Autoplay and set Duration
- Activate custom activities
> *Alexa, turn Nanoleafs **on/off***
> *Alexa, set Nanoleafs 70%*
> Alexa, dim Nanoleafs
> *Alexa, Nanoleaf speed 20%*
> *Alexa, set Nanoleafs pink*
> *Alexa, turn Nanoleaf rainbow on*
> *Alexa, turn Nanoleaf Autoplay on*
> *Alexa, set Nanoleaf Autoplay 40*
>
> Alexa, Nanoleaf Default
> Alexa, Nanoleaf Mode 1
> Alexa, Nanoleaf Mode 2
> Alexa, Nanoleaf Mode 3
### Node-RED GUI
The Node-RED GUI is an addition to the regular UI that is running on the Wemos D1 mini. It allows to create and save custom patterns and also control all regular parameters same as the ESP8266 webserver. It can be accessed by any device.
![full](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/full.png?raw=true)
#### Nanoleaf Designer
In the Node-RED GUI you can easily create your nanoleaf setup by using the *Nanoleaf Designer*. It's easy to use and allows almost any design that is possible. But it might have still some minor bugs.
![nanoleaf_designer](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/nanoleaf_designer.png?raw=true)
![nanoleaf_designer_2](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/nanoleaf_designer_2.png?raw=true)
#### Nanoleaf Custom Pattern Designer
With the *Nanoleaf Custom Pattern Designer* you can create custom patterns with effects. Currently the individual leafs can be set to *Static* mode and *Breathe* mode that allows to set a phase shift and lets the leafs breathe. Flow-mode follows in the next update.
![pattern_designer](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/pattern_designer.png?raw=true)
![pattern_designer_2](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/pattern_designer_2.png?raw=true)
![patternlist](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/patternlist.png?raw=true)
## What you will need
- Any device that runs Node-RED, examples would be:
- (recommended) [Raspberry Pi](https://www.amazon.de/gp/product/B01CD5VC92?ie=UTF8&tag=surrbradl08-21&camp=1638&linkCode=xm2&creativeASIN=B01CD5VC92)
- Any Linux machine
- (instructions are provided for linux) Any Windows machine
- Any Amazon Alexa device for Alexa integration, works on Android and IOS too (**OPTIONAL**)
## Setup
#### 1. Install Node-RED
```bash
bash <(curl -sL https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/update-nodejs-and-nodered)
```
#### 2. Install npm - this might be already installed
```bash
sudo apt-get install nodejs npm -y
```
#### 3. Install dashboard, alexa-home-skill, color-convert, config
```bash
cd $HOME/.node-red
npm install node-red-dashboard
```
- if you get an error try: `npm install --unsafe-perm node-red-dashboard`
```bash
npm install node-red-contrib-alexa-home-skill
npm install node-red-contrib-color-convert
npm install node-red-contrib-config
```
#### 4. Setup a static IP-Address for your Raspberry Pi (optional)
- (recommended) Setup a static ip on your router
- [or on your Raspberry Pi](http://www.circuitbasics.com/how-to-set-up-a-static-ip-on-the-raspberry-pi/)
#### 5. Run Node-RED
To start Node-RED type into the shell:
```bash
sudo node-red-start
```
Connect to the GUI by typing the following line into your browser:
- http://IP-ADDRESS:1880
#### 6. Import the flow
- Click on the 3 dashes in the top right corner → import → clipboard
- Copy the contents of NodeRED_flows.txt into the window and hit import
![import](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/import.png?raw=true)
#### 7. Configure the IP-Address of the Wemos D1 mini
Edit the Nanoleaf-Config node to set the IP-Address.
![config_1](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/config_1.png?raw=true)
![config_2](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/config_2.png?raw=true)
#### 8. Connect to the Dashboard
Connect to the dashboard(website) of Node-RED by typing the following line into your browser:
- http://IP-ADDRESS:1880/ui
## Amazon Alexa setup
The Alexa integration uses the *Node-RED Alexa Home Skill Bridge* to redirect the commands from alexa to Node-RED.
### 1. Create a new Bridge account
Head to https://alexa-node-red.bm.hardill.me.uk/newuser and create a new account.
Afterwards login into your account.
### 2. Create the Devices
You have to create devices that are called by Alexa.
#### 2.1 Main Nanoleaf Device
First create the devices that control a few devices that are used to turn on/off the nanoleafs and controls the brightness. I've called them "Nanoleafs", "Nanoleaf", "Nano" and "Triangles", but a single one would be enough too.
Click the **Add Device** button and choose. Repeat this step for all your names.
![device_1](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_1.png?raw=true)
![device_2](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_2.png?raw=true)
#### 2.2 Autoplay control Device (optional)
To control the autoplay functionality, create a device with **On, Off, %, +%, -%, LIGHT**.
#### 2.3 Speed control Device (optional)
To control the speed of the animations, create a device with **%, +%, -%**.
#### 2.4 Activities (optional)
Now create activities by clicking *Add Device* and selecting **On, Off, ACTIVITY**.
I've created one to set the *Rainbow* pattern, one for my default settings and Nanoleaf Mode 1-3 for some custom settings.
![device_3](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_3.png?raw=true)
![device_4](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_4.png?raw=true)
### 3. Activating the Alexa skill
Open the app on your phone or head to https://alexa.amazon.de and click on **Skills**.
Search for **Node-RED** and activate the skill. Afterwards you are prompted to login into your account that you have created the devices beforehand.
![1551006980428](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/alexa_skill.png?raw=true)
### 4. Add a new Alexa-Home-Skill configuration
Click on any Alexa node in the flow, and click *Add new alexa-home-configuration*. Afterwards hit the refresh button next to the devices list.
![conf_1](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/conf_1.png?raw=true)
### 5. Select the devices
Click the alexa skill nodes in the flow and select the corresponding devices. **Delete all unused alexa nodes**.
For me, it looked like this:
![device_config](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_config.png?raw=true)
### 6. Discover the Smart-Home Devices
Speak to Alexa and say to her: **Alexa, discover devices**. (Just say it in english, it works on every device)
If everything worked correctly she should tell you after around 30 seconds that she has found new devices.

430
README.md
View File

@ -1,405 +1,92 @@
Nanoleaf Web Server
# Nanoleaf Web Server
<a href="https://github.com/NimmLor/esp8266-nanoleaf-webserver/graphs/contributors" alt="Contributors">
<img src="https://img.shields.io/github/contributors/NimmLor/esp8266-nanoleaf-webserver" /></a>
=========
This is a fork of [jasoncoon's esp8266 fastled webserver](https://github.com/jasoncoon/esp8266-fastled-webserver) that was adapted to control the colors of my [DIY-Nanoleaf Replica](https://www.thingiverse.com/thing:3354082).
[![Nanoleafs](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/rgb_preview2.gif?raw=true)](https://www.thingiverse.com/thing:3354082)
## Changelog
### 01.02.2020, Native Alexa Update
- **NodeRED** part is now **DEPRECATED**
- The Nanoleaf Replica allows now for **NATIVE** Alexa support without the need of an extra Raspberry Pi. When added to the Smart Home devices in the Alexa app, the nanoleafs will appear as Phillips Hue devices.
- Added Strobe Pattern
- Added Sound Reactive support
- Some code cleanup and new parameters to configure
- New step by step installation instructions ([Software_Installation.md](Software_Installation.md))
### 24.02.2019, NodeRED Update (Depricated)
- Node-RED integration was added
- Alexa support via NodeRED
### Bill of Materials
- 1x [Wemos D1 mini](http://s.click.aliexpress.com/e/_srb2XX) is recommended, but any other ESP8266 variant should work too, but it might require an additional step-down converter.
- [WS2812B LED Strip **IP30**](http://s.click.aliexpress.com/e/_sUwhA1), only IP30 will fit inside the nanoleafs, I'll recommend at least 60LEDs/m
- 1x [Microphone Sensor](http://s.click.aliexpress.com/e/_sYiUrz) (Optional), MAX4466 Sensor is recommended
- 1x [3.3V to 5V Logic Level Shifter](http://s.click.aliexpress.com/e/_s49Saz) (optional, required if LEDs "glitch")
- 1x [Female Power Jack](http://s.click.aliexpress.com/e/_sPe0RR)
- 1x [5V Power Supply](http://s.click.aliexpress.com/e/_sIzXbC), Note: 100 LEDs draw around 4A
Hardware
--------
##### ESP8266
**Check out the project on [Thingiverse](https://www.thingiverse.com/thing:3354082) for more details.**
![Wemos D1 Mini Pro & Headers](https://ae01.alicdn.com/kf/HTB1QYHzJKuSBuNjy1Xcq6AYjFXau/ESP8266-ESP-12-ESP12-WeMos-D1-Mini-Modul-Wemos-D1-Mini-WiFi-Entwicklung-Bord-Micro-USB.jpg)
[Wemos D1 mini](http://s.click.aliexpress.com/e/cBDdafPw) is recommended, but any other ESP8266 variant should work too, but it might require an additional step-down converter.
[![https://www.thingiverse.com/Surrbradl08/things](https://cdn.thingiverse.com/site/img/thingiverse-logo-2015.png)](https://www.thingiverse.com/thing:3354082)
**Addressable Led Strip**
![](https://cdn.pixabay.com/photo/2017/02/27/11/36/digital-led-strip-lights-2103020_960_720.jpg)
I have used 12 led pixels per leaf → 1m of 60 leds/m = 5 leafs
I would recommend buying a strip with 60 leds/m or more.
[WS2812b led strip](http://s.click.aliexpress.com/e/SkQFQqc), make sure you choose IP30 any other IP rating wouldn't make any sense and might not even fit.
Installation
--------
**FOR INSTALLATION REFER TO THE [Software_Installation.md](Software_Installation.md)**
Other (optional) hardware:
* [3.3V to 5V Logic Level Shifter](http://s.click.aliexpress.com/e/buDr0PT2) (required if LEDs "glitch")
Features
--------
* Control the colors of individual leafs
* Adjust the brightness
* Change the display pattern
* Adjust the color
* Adapted patterns to look great on the [DIY-Nanoleaf Replica](https://www.thingiverse.com/thing:3354082)
* OTA-Update support
* **Node-RED** integration :white_check_mark:
* Simple Amazon **Alexa** integration :white_check_mark:
* Custom pattern designer :white_check_mark:
* **Node-RED** webinterface to store special patterns persistant :white_check_mark:
* Turn the LEDs on and off
* Appear as an **ALEXA SMART HOME DEVICE**
* **Sound Reactive Mode**
* Adjust the brightness, color and patterns
* Play over 30+ patterns in Autoplay
### Upcoming Features
- **Node-RED** integration :white_check_mark:
- Simple Amazon **Alexa** integration :white_check_mark:
- Nanoleaf voice control :white_check_mark:
- Custom pattern designer :white_check_mark:
- **Node-RED** webinterface to store special patterns persistant :white_check_mark:
- Controlling multiple nanoleafs at once
- Advanced Amazon **Alexa** integration with custom skill (AWS account required, free)
> these features will be optional and require additional hardware (any linux/windows device that is in the same network)
Webinterface
Web App
--------
![Webinterface](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/interface.jpg?raw=true)
The web app is stored in SPIFFS (on-board flash memory).
Installing
-----------
The app is installed via the Arduino IDE which can be [downloaded here](https://www.arduino.cc/en/main/software) (Arduino IDE 1.8.9 and above might cause Sketch-Data-Uploading Issues). The ESP8266 boards will need to be added to the Arduino IDE which is achieved as follows. Click File > Preferences and copy and paste the URL "http://arduino.esp8266.com/stable/package_esp8266com_index.json" into the Additional Boards Manager URLs field. Click OK. Click Tools > Boards: ... > Boards Manager. Find and click on ESP8266 (using the Search function may expedite this). Click on Install. After installation, click on Close and then select your ESP8266 board from the Tools > Board: ... menu (esp8266 2.5.0 and above causes compilation errors).
The app depends on the following libraries. They must either be downloaded from GitHub and placed in the Arduino 'libraries' folder, or installed as [described here](https://www.arduino.cc/en/Guide/Libraries) by using the Arduino library manager.
* [FastLED](https://github.com/FastLED/FastLED) (FastLED 3.2.7 & 3.2.8 DOES NOT WORK)
* [Arduino WebSockets](https://github.com/Links2004/arduinoWebSockets)
Download the app code from GitHub using the [**Releases** section on GitHub](https://github.com/NimmLor/esp8266-nanoleaf-webserver/releases) and download the ZIP file. Decompress the ZIP file in your Arduino sketch folder.
The web app needs to be uploaded to the ESP8266's SPIFFS. You can do this within the Arduino IDE after installing the [Arduino ESP8266FS tool](http://esp8266.github.io/Arduino/versions/2.3.0/doc/filesystem.html#uploading-files-to-file-system). An alternative would be to install the [Visual Micro](https://www.visualmicro.com/) plugin for Visual Studio.
With ESP8266FS installed upload the web app using `ESP8266 Sketch Data Upload` command in the Arduino Tools menu.
## Configuration
The most important thing to do is to set the amount of 'leafs' and the amount of led pixels that one 'leaf' contains.
For instance I use 12 leafs (triangles) with a total of 12 pixels in one leaf (=4 leds in each corner of the triangle).
```c++
#define LEAFCOUNT 12
#define PIXELS_PER_LEAF 12
```
Next enter the pin where the *Data* line is connected to, in my case it's pin D4 (you can either write D4 or 2).
`#define DATA_PIN D4`
If you are using another controller such as a clone or a NodeMCU board, you may need to configure the pin assignment for FastLED (See also [this entry in the FastLED Wiki](https://github.com/FastLED/FastLED/wiki/ESP8266-notes)). Example:
`#define FASTLED_ESP8266_RAW_PIN_ORDER`
Another **important** step is to create the **Secrets.h** file. Create a new tab (**ctrl**+**shift**+**n**) and name it *Secrets.h*, this file contains your WIFI credentials and it's structure must look like this:
``````c++
// AP mode password
const char WiFiAPPSK[] = "WIFI_NAME_IF_IN_AP_MODE";
// Wi-Fi network to connect to (if not in AP mode)
char* ssid = "YOUR_WIFI_NAME";
char* password = "YOUR_WIFI_PASSWORD";
``````
If colors appear to be swapped you should change the color order. For me, red and green was swapped so i had to change the color order from *RGB* to *GRB*.
You should also set the milli-amps of your power supply to prevent power overloading. I am using a 3A 5V psu so i defined 3000mA.
`#define MILLI_AMPS 3000`
## Circuit
### Without Logic-Level Converter
![circuit without Logic level converter](wiring.jpg)
![circuit without Logic level converter](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/circuit.jpg?raw=true)
### With Logic-Level-Converter (required if leds 'glitch')
![circuit with logic level converter](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/circuit_logic_level_Steckplatine.jpg?raw=true)
# Node-RED & Alexa integration Setup
## Features
### **Amazon Alexa Integration** (optional)
It works with any language that is supported by Alexa and can be easily expanded to support more activities or patterns. How you want to call them (Nanoleaf, Nanoleafs, Nano, Triangles) must be set in the setup of the devices.
#### **Commands**:
- Turn on/off
- Control Brightness
- Control Pattern Speed
- Set Color
- Set into Rainbow mode
- Enable Autoplay and set Duration
- Activate custom activities
> *Alexa, turn Nanoleafs **on/off***
> *Alexa, set Nanoleafs 70%*
> Alexa, dim Nanoleafs
> *Alexa, Nanoleaf speed 20%*
> *Alexa, set Nanoleafs pink*
> *Alexa, turn Nanoleaf rainbow on*
> *Alexa, turn Nanoleaf Autoplay on*
> *Alexa, set Nanoleaf Autoplay 40*
>
> Alexa, Nanoleaf Default
> Alexa, Nanoleaf Mode 1
> Alexa, Nanoleaf Mode 2
> Alexa, Nanoleaf Mode 3
### Node-RED GUI
The Node-RED GUI is an addition to the regular UI that is running on the Wemos D1 mini. It allows to create and save custom patterns and also control all regular parameters same as the ESP8266 webserver. It can be accessed by any device.
![full](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/full.png?raw=true)
#### Nanoleaf Designer
In the Node-RED GUI you can easily create your nanoleaf setup by using the *Nanoleaf Designer*. It's easy to use and allows almost any design that is possible. But it might have still some minor bugs.
![nanoleaf_designer](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/nanoleaf_designer.png?raw=true)
![nanoleaf_designer_2](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/nanoleaf_designer_2.png?raw=true)
#### Nanoleaf Custom Pattern Designer
With the *Nanoleaf Custom Pattern Designer* you can create custom patterns with effects. Currently the individual leafs can be set to *Static* mode and *Breathe* mode that allows to set a phase shift and lets the leafs breathe. Flow-mode follows in the next update.
![pattern_designer](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/pattern_designer.png?raw=true)
![pattern_designer_2](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/pattern_designer_2.png?raw=true)
![patternlist](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/patternlist.png?raw=true)
## What you will need
- Any device that runs Node-RED, examples would be:
- (recommended) [Raspberry Pi](https://www.amazon.de/gp/product/B01CD5VC92?ie=UTF8&tag=surrbradl08-21&camp=1638&linkCode=xm2&creativeASIN=B01CD5VC92)
- Any Linux machine
- (instructions are provided for linux) Any Windows machine
- Any Amazon Alexa device for Alexa integration, works on Android and IOS too (**OPTIONAL**)
## Setup
#### 1. Install Node-RED
```bash
bash <(curl -sL https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/update-nodejs-and-nodered)
```
#### 2. Install npm - this might be already installed
```bash
sudo apt-get install nodejs npm -y
```
#### 3. Install dashboard, alexa-home-skill, color-convert, config
```bash
cd $HOME/.node-red
npm install node-red-dashboard
```
- if you get an error try: `npm install --unsafe-perm node-red-dashboard`
```bash
npm install node-red-contrib-alexa-home-skill
npm install node-red-contrib-color-convert
npm install node-red-contrib-config
```
#### 4. Setup a static IP-Address for your Raspberry Pi (optional)
- (recommended) Setup a static ip on your router
- [or on your Raspberry Pi](http://www.circuitbasics.com/how-to-set-up-a-static-ip-on-the-raspberry-pi/)
#### 5. Run Node-RED
To start Node-RED type into the shell:
```bash
sudo node-red-start
```
Connect to the GUI by typing the following line into your browser:
- http://IP-ADDRESS:1880
#### 6. Import the flow
- Click on the 3 dashes in the top right corner → import → clipboard
- Copy the contents of NodeRED_flows.txt into the window and hit import
![import](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/import.png?raw=true)
#### 7. Configure the IP-Address of the Wemos D1 mini
Edit the Nanoleaf-Config node to set the IP-Address.
![config_1](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/config_1.png?raw=true)
![config_2](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/config_2.png?raw=true)
#### 8. Connect to the Dashboard
Connect to the dashboard(website) of Node-RED by typing the following line into your browser:
- http://IP-ADDRESS:1880/ui
## Amazon Alexa setup
The Alexa integration uses the *Node-RED Alexa Home Skill Bridge* to redirect the commands from alexa to Node-RED.
### 1. Create a new Bridge account
Head to https://alexa-node-red.bm.hardill.me.uk/newuser and create a new account.
Afterwards login into your account.
### 2. Create the Devices
You have to create devices that are called by Alexa.
#### 2.1 Main Nanoleaf Device
First create the devices that control a few devices that are used to turn on/off the nanoleafs and controls the brightness. I've called them "Nanoleafs", "Nanoleaf", "Nano" and "Triangles", but a single one would be enough too.
Click the **Add Device** button and choose. Repeat this step for all your names.
![device_1](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_1.png?raw=true)
![device_2](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_2.png?raw=true)
#### 2.2 Autoplay control Device (optional)
To control the autoplay functionality, create a device with **On, Off, %, +%, -%, LIGHT**.
#### 2.3 Speed control Device (optional)
To control the speed of the animations, create a device with **%, +%, -%**.
#### 2.4 Activities (optional)
Now create activities by clicking *Add Device* and selecting **On, Off, ACTIVITY**.
I've created one to set the *Rainbow* pattern, one for my default settings and Nanoleaf Mode 1-3 for some custom settings.
![device_3](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_3.png?raw=true)
![device_4](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_4.png?raw=true)
### 3. Activating the Alexa skill
Open the app on your phone or head to https://alexa.amazon.de and click on **Skills**.
Search for **Node-RED** and activate the skill. Afterwards you are prompted to login into your account that you have created the devices beforehand.
![1551006980428](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/alexa_skill.png?raw=true)
### 4. Add a new Alexa-Home-Skill configuration
Click on any Alexa node in the flow, and click *Add new alexa-home-configuration*. Afterwards hit the refresh button next to the devices list.
![conf_1](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/conf_1.png?raw=true)
### 5. Select the devices
Click the alexa skill nodes in the flow and select the corresponding devices. **Delete all unused alexa nodes**.
For me, it looked like this:
![device_config](https://github.com/NimmLor/esp8266-nanoleaf-webserver/blob/master/gallery/NodeRED_UI/device_config.png?raw=true)
### 6. Discover the Smart-Home Devices
Speak to Alexa and say to her: **Alexa, discover devices**. (Just say it in english, it works on every device)
If everything worked correctly she should tell you after around 30 seconds that she has found new devices.
Technical information
-----------------
## Technical
Patterns are requested by the app from the ESP8266, so as new patterns are added, they're automatically listed in the app.
@ -411,4 +98,23 @@ The only drawback to SPIFFS that I've found so far is uploading the files can be
### Alexa
The code has an optional feature to be able to control the lamp via Alexa on any Amazon Echo device. For setup instructions refer to [Software_Installation.md](https://github.com/NimmLor/esp8266-fastled-desk-light/blob/master/Software_Installation.md) document.
### Compression
The web app files can be gzip compressed before uploading to SPIFFS by running the following command:
`gzip -r data/`
The ESP8266WebServer will automatically serve any .gz file. The file index.htm.gz will get served as index.htm, with the content-encoding header set to gzip, so the browser knows to decompress it. The ESP8266WebServer doesn't seem to like the Glyphicon fonts gzipped, though, so I decompress them with this command:
`gunzip -r data/fonts/`
### REST Web services
The firmware implements basic [RESTful web services](https://en.wikipedia.org/wiki/Representational_state_transfer) using the ESP8266WebServer library. Current values are requested with HTTP GETs, and values are set with POSTs using query string parameters. It can run in connected or standalone access point modes.

145
Software_Installation.md Normal file
View File

@ -0,0 +1,145 @@
The software runs on the ESP8266. The web app is stored in SPIFFS (on-board flash memory). I've forked [jasoncoon's esp8266 fastled webserver](https://github.com/jasoncoon/esp8266-fastled-webserver) and added some extra functionality, made a proper config area and created custom patterns for the lamp.
Amazon Alexa support and Node-RED integration will follow soon.
**The software can be found on [GitHub](https://github.com/NimmLor/esp8266-fastled-desk-light).**
For beginners I would recommend watching this setup tutorial below.
## 1. Programming Environment
1. The code requires an installed version of **Arduino IDE 1.8.8** which can be downloaded [here]( https://www.arduino.cc/en/Main/OldSoftwareReleases#previous ).
2. The ESP8266 boards need to be added to the Arduino IDE:
Click on *File >> Preferences* and paste the URL "http://arduino.esp8266.com/stable/package_esp8266com_index.json" into the **Additional Boards Manager URLs** field.
![](software_screenshots/board_manager_urls.png?raw=true)
3. Install the CH340/341 USB Driver
- Download and install the driver from e.g. [Arduined]( https://www.arduined.eu/ch340-windows-8-driver-download/ )
4. The Boards need be installed in the Arduino IDE
Click on *Tools >> Board >> Boards Manager* and install **esp8266, version 2.6.3**
![](software_screenshots/board_manager.png?raw=true)
5. The LED Library **FastLED** is also required
Click on *Sketch >> Include Library >> Manage Libraries* and install **FastLED, version 3.3.2**
![](software_screenshots/FastLED.png?raw=true)
6. Install the *ESP8266FS* **Sketch Data Upload Tool**:
> - Download the tool: https://github.com/esp8266/arduino-esp8266fs-plugin/releases/download/0.2.0/ESP8266FS-0.2.0.zip.
>
> - In your Arduino sketchbook directory, create `tools` directory if it doesn't exist yet
>
> - Unpack the tool into `tools` directory (the path will look like `/Arduino/tools/ESP8266FS/tool/esp8266fs.jar`)
>
> - Restart Arduino IDE
>
> // [source]( http://arduino.esp8266.com/Arduino/versions/2.3.0/doc/filesystem.html#uploading-files-to-file-system )
7. (Optional) Install *Espalexa* for Amazon Alexa Support
Click on *Sketch >> Include Library >> Manage Libraries* and install **Espalexa, version 2.4.4**
![](software_screenshots/espalexa.png?raw=true)
## 2. Software Configuration
1. Download the Project from the [Releases at Github]( https://github.com/NimmLor/esp8266-fastled-desk-light/releases ) and extract the archive
2. Open the **.ino** file inside the folder in the Arduino IDE
3. Create the **Secrets.h** file
*Top Right Corner >> New Tab >> "Secrets.h"*
![](software_screenshots/newtab.png?raw=true)
4. Paste the following code and fill in your WiFi credentials
```c++
// AP mode password
const char WiFiAPPSK[] = "your-password";
// Wi-Fi network to connect to (if not in AP mode)
char* ssid = "your-ssid";
char* password = "your-password";
```
![](software_screenshots/secret.png?raw=true)
5. Configure the parameters
In the .ino file there are many parameters to change and tweak the essential settings are:
- `DATA_PIN`: The pin where the LED-Strip is connected
- `LED_TYPE`: The type of LED strip that is used (WS2812B, WS2811, ...)
- `COLOR_ORDER`: Ordering of the colors sent, **depends on the LED-Strip**, if colors are swapped, then swap the Letters (RGB, RBG, GRB, GBR, BRG, BGR)
- `LEDS_PER_LINE`: Amount of LEDs inside **1x** slot of the core
- `SOUND_REACTIVE`: Uncomment to enable a sound reactive pattern when using a sound sensor
- `SENSOR_TYPE`: Model of the [Sensor](http://s.click.aliexpress.com/e/_sYiUrz) used
- `ENABLE_ALEXA_SUPPORT`: Uncomment to disable the Amazon Alexa Support
![](software_screenshots/config.png?raw=true)
6. (Optional) Configure Alexa
- Installation of the **Espalexa** library required
- Requires `ENABLE_ALEXA_SUPPORT`
- The name of the device is set in the variable `ALEXA_DEVICE_NAME`
- Configuration of addition Devices
- In order to control more parameters, the code allows to create additional devices that control, i.e. a specific pattern or the autoplay functionality
- To make use of these features remove the `//` in front of the `#define ...`
![](software_screenshots/alexa_config.png?raw=true)
## 3. Upload
1. Configure the upload settings in **Tools** menu, there are **3 essential settings**
- **Board: LOLIN(WEMOS) D1 R2 & mini**: when using the recommended Wemos D1 Mini
- **Flash Size: "4MB (FS:1MB OTA:~1019KB)"**
- **Port:** COMxx, if there are multiple ports, then replug your esp8266 to find the correct port. (**Hint:** COM1 is usually your PCs internal parallel port and not the esp8266)
![](software_screenshots/upload_settings.png?raw=true)
2. Hit the **Upload** button to upload the code
3. **Upload the Sketch Data**
Click on *Tools >> ESP8266 Sketch Data Upload*
![](software_screenshots/data_upload.png?raw=true)
4. (Optional) Open the **Serial Monitor** to find the IP address of esp8266
- Click on *Tools >> Serial Monitor*
- When pressing the *Reset-Button* on the esp8266, the console should print the IP-Address
5. Connect to the UI by opening http://ip_address/ in your browser of choice, this works on mobile devices too
## 4. Alexa Configuration
The connect your esp8266, the "Pairing-Mode" mode must be activated to add it to your Smart-Home devices in the alexa app.
Open http://ip_of_the_esp8266/alexa in your browser, the window should tell you that it is ready to be discovered by your alexa device.
**Important**: The esp8266 and you Amazon Echo device **must** be in the same network.
Just say to your echo, "Alexa, discover devices". This phrase can be spoken out in English on any echo device independent of the device's language.
After around 30 seconds, Alexa should respond with the devices that were found. These should show up in the Alexa app.
![](software_screenshots/app.png?raw=true)

View File

@ -15,84 +15,90 @@
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//-----------------------------------------CONFIG-----------------------------------------//
#define LEAFCOUNT 12
#define PIXELS_PER_LEAF 12
#define DATA_PIN D4 // The pin where the data line is connected to
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB // Color order, if e.g. your Colors are swapped then change the order, (RGB, RBG, GBR, GRB, BRG, BGR)
#define MILLI_AMPS 3000 // IMPORTANT: set the max milli-Amps of your power supply (4A = 4000mA)
#define FRAMES_PER_SECOND 120 // here you can control the speed. With the Access Point / Web Server the animations run a bit slower.
const bool apMode = false; // Set to true if the esp8266 should open an Access-Point
// Animation Config:
// ten seconds per color palette makes a good demo
// 20-120 is better for deployment
uint8_t secondsPerPalette = 60;
// COOLING: How much does the air cool as it rises?
// Less cooling = taller flames. More cooling = shorter flames.
// Default 50, suggested range 20-100
uint8_t cooling = 49;
// SPARKING: What chance (out of 255) is there that a new spark will be lit?
// Higher chance = more roaring fire. Lower chance = more flickery fire.
// Default 120, suggested range 50-200.
uint8_t sparking = 160;
uint8_t speed = 20;
//---------------------------------------CONFIG END---------------------------------------//
//#define FASTLED_ALLOW_INTERRUPTS 1
//#define INTERRUPT_THRESHOLD 1
#define FASTLED_INTERRUPT_RETRY_COUNT 0
#include <FastLED.h>
FASTLED_USING_NAMESPACE
extern "C" {
#include "user_interface.h"
}
#include <ESP8266WiFi.h>
//#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPUpdateServer.h>
//#include <WebSocketsServer.h>
#include <FS.h>
#include <EEPROM.h>
//#include <IRremoteESP8266.h>
#include "GradientPalettes.h"
#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
#include "Field.h"
//#define RECV_PIN D4
//IRrecv irReceiver(RECV_PIN);
//#include "Commands.h"
/*######################## MAIN CONFIG ########################*/
#define DATA_PIN D4 // Should be GPIO02 on other boards like the NodeMCU
#define LED_TYPE WS2812B // You might also use a WS2811 or any other strip that is fastled compatible
#define COLOR_ORDER GRB // Change this if colors are swapped (in my case, red was swapped with green)
#define MILLI_AMPS 5000 // IMPORTANT: set the max milli-Amps of your power supply (4A = 4000mA)
#define VOLTS 5 // Voltage of the Power Supply
#define LEAFCOUNT 12 // Amount of triangles
#define PIXELS_PER_LEAF 12 // Amount of LEDs inside 1x Tringle
const bool apMode = false; // set to true if the esp8266 should open an access point
//#define SOUND_REACTIVE // Uncomment to enable the Sound reactive mode
#define SOUND_SENSOR_PIN A0 // An Analog sensor should be connected to an analog pin
#define SENSOR_TYPE 1 // 0: Dumb Sensors, 1: MAX4466 Sound Sensor, 2: MAX9814 Sound Sensor
#define HOSTNAME "Nanoleafs" // Name that appears in your network
#define CORRECTION UncorrectedColor // If colors are weird use TypicalLEDStrip
#define RANDOM_AUTOPLAY_PATTERN // if enabled the next pattern for autoplay is choosen at random,
// if commented out patterns will play in order
#define ENABLE_ALEXA_SUPPORT // Espalexa library required
/*######################## MAIN CONFIG END ####################*/
/*############ Alexa Configuration ############*/
/* This part configures the devices that can be detected,
* by your Amazon Alexa device. In order to Connect the device,
* open http://ip_of_the_esp8266/alexa in your browser.
* Afterwards tell say "Alexa, discover devices" to your device,
* after around 30 seconds it should respond with the new devices
* it has detected.
*
* In order to be able to control mutliple parameters of the nanoleafs,
* the code creates multiple devices.
*
* To add those extra devices remove the two "//" in front of the,
* defines below.
*/
#ifdef ENABLE_ALEXA_SUPPORT
#define ALEXA_DEVICE_NAME "Nanoleafs"
#define AddAutoplayDevice "Nanoleafs Autoplay"
#define AddStrobeDevice "Nanoleafs Strobe"
#define AddSpecificPatternDevice "Nanoleafs Party"
#ifdef AddSpecificPatternDevice
#define SpecificPattern 1 // Parameter defines what pattern gets executed
#endif
#endif // ENABLE_ALEXA_SUPPORT
/*########## Alexa Configuration END ##########*/
ESP8266WebServer webServer(80);
//WebSocketsServer webSocketsServer = WebSocketsServer(81);
ESP8266HTTPUpdateServer httpUpdateServer;
#include "FSBrowser.h"
#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
#define NUM_LEDS (PIXELS_PER_LEAF * LEAFCOUNT)
#define FRAMES_PER_SECOND 120 // here you can control the speed. With the Access Point / Web Server the animations run a bit slower.
#define SOUND_REACTIVE_FPS 120
#include "Secrets.h" // this file is intentionally not included in the sketch, so nobody accidentally commits their secret information.
// create a Secrets.h file with the following:
// AP mode password
// const char WiFiAPPSK[] = "your-password";
@ -100,14 +106,44 @@ ESP8266HTTPUpdateServer httpUpdateServer;
// char* ssid = "your-ssid";
// char* password = "your-password";
#ifdef ENABLE_ALEXA_SUPPORT
#include <Espalexa.h>
void mainAlexaEvent(EspalexaDevice*);
Espalexa espalexa;
ESP8266WebServer webServer2(80);
EspalexaDevice* alexa_main;
#endif // ENABLE_ALEXA_SUPPORT
CRGB leds[NUM_LEDS];
const uint8_t brightnessCount = 5;
uint8_t brightnessMap[brightnessCount] = { 16, 32, 64, 128, 255 };
uint8_t brightnessMap[brightnessCount] = { 5, 32, 64, 128, 255 };
uint8_t brightnessIndex = 0;
char vals[4 + LEAFCOUNT * 5][4] = {""};
char vals[4 + LEAFCOUNT * 5][4] = { "" };
uint8_t breathe = 0; // value for starting custom pattern
uint8_t breathe_dir = 1; // 1== rising
char cpattern[500] = "";
uint8_t allLeafs = 1; // Sets if all leafs should get the same color
uint8_t selectedLeaf = 1; // Sets position of leaf to color
// ten seconds per color palette makes a good demo
// 20-120 is better for deployment
uint8_t secondsPerPalette = 10;
// COOLING: How much does the air cool as it rises?
// Less cooling = taller flames. More cooling = shorter flames.
// Default 50, suggested range 20-100
uint8_t cooling = 3;
// SPARKING: What chance (out of 255) is there that a new spark will be lit?
// Higher chance = more roaring fire. Lower chance = more flickery fire.
// Default 120, suggested range 50-200.
uint8_t sparking = 50;
uint8_t speed = 70;
///////////////////////////////////////////////////////////////////////
@ -126,9 +162,6 @@ CRGBPalette16 IceColors_p = CRGBPalette16(CRGB::Black, CRGB::Blue, CRGB::Aqua, C
uint8_t currentPatternIndex = 0; // Index number of which pattern is current
uint8_t autoplay = 0;
uint8_t allLeafs = 1; // Sets if all leafs should get the same color
uint8_t selectedLeaf = 1; // Sets position of leaf to color
uint8_t autoplayDuration = 10;
unsigned long autoPlayTimeout = 0;
@ -136,10 +169,6 @@ uint8_t currentPaletteIndex = 0;
uint8_t gHue = 0; // rotating "base color" used by many of the patterns
uint8_t breathe = 0; // value for starting custom pattern
uint8_t breathe_dir = 1; // 1== rising
char cpattern[500] = "";
CRGB solidColor = CRGB::Blue;
// scale the brightness of all pixels down
@ -166,6 +195,16 @@ typedef PatternAndName PatternAndNameList[];
PatternAndNameList patterns = {
{ pride, "Pride" },
{ colorWaves, "Color Waves" },
{ rainbow, "Horizontal Rainbow" },
{ rainbowSolid, "Solid Rainbow" },
{ confetti, "Confetti" },
{ sinelon, "Sinelon" },
{ bpm, "Beat" },
{ juggle, "Juggle" },
{ fire, "Fire" },
{ water, "Water" },
{ strobe, "Strobe"},
{ rainbow_strobe, "Rainbow Strobe"},
// twinkle patterns
{ rainbowTwinkles, "Rainbow Twinkles" },
@ -189,16 +228,6 @@ PatternAndNameList patterns = {
{ cloud2Twinkles, "Cloud 2 Twinkles" },
{ oceanTwinkles, "Ocean Twinkles" },
{ rainbow, "Rainbow" },
{ rainbowWithGlitter, "Rainbow With Glitter" },
{ rainbowSolid, "Solid Rainbow" },
{ confetti, "Confetti" },
{ sinelon, "Sinelon" },
{ bpm, "Beat" },
{ juggle, "Juggle" },
{ fire, "Fire" },
{ water, "Water" },
{ showSolidColor, "Solid Color" },
{ SetCustomPattern, "Custom Pattern"}
@ -240,16 +269,19 @@ const String paletteNames[paletteCount] = {
void setup() {
WiFi.setSleepMode(WIFI_NONE_SLEEP);
#ifdef SOUND_REACTIVE
patterns[patternCount - 2] = { soundReactive, "Sound Reactive" };
#endif // SOUND_REACTIVE
Serial.begin(115200);
delay(100);
Serial.setDebugOutput(true);
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); // for WS2812 (Neopixel)
//FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS); // for APA102 (Dotstar)
FastLED.setDither(false);
FastLED.setCorrection(TypicalLEDStrip);
FastLED.setCorrection(CORRECTION);
FastLED.setBrightness(brightness);
FastLED.setMaxPowerInVoltsAndMilliamps(5, MILLI_AMPS);
FastLED.setMaxPowerInVoltsAndMilliamps(VOLTS, MILLI_AMPS);
fill_solid(leds, NUM_LEDS, CRGB::Black);
FastLED.show();
@ -271,6 +303,13 @@ void setup() {
Serial.print(F("Vcc: ")); Serial.println(ESP.getVcc());
Serial.println();
#ifdef SOUND_REACTIVE
#if SENSOR_TYPE == 0
pinMode(SOUND_SENSOR_PIN, INPUT);
#endif
#endif // SOUND_REACTIVE
SPIFFS.begin();
{
Serial.println("SPIFFS contents:");
@ -284,8 +323,6 @@ void setup() {
Serial.printf("\n");
}
//disabled due to https://github.com/jasoncoon/esp8266-fastled-webserver/issues/62
//initializeWiFi();
if (apMode)
{
@ -296,7 +333,7 @@ void setup() {
uint8_t mac[WL_MAC_ADDR_LENGTH];
WiFi.softAPmacAddress(mac);
String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
macID.toUpperCase();
String AP_NameString = "ESP8266 Thing " + macID;
@ -316,11 +353,71 @@ void setup() {
WiFi.mode(WIFI_STA);
Serial.printf("Connecting to %s\n", ssid);
if (String(WiFi.SSID()) != String(ssid)) {
WiFi.hostname("Nanoleaf");
WiFi.begin(ssid, password);
WiFi.hostname(HOSTNAME);
}
}
#ifdef ENABLE_ALEXA_SUPPORT
#ifdef ALEXA_DEVICE_NAME
alexa_main = new EspalexaDevice(ALEXA_DEVICE_NAME, mainAlexaEvent, EspalexaDeviceType::color);
#else
alexa_main = new EspalexaDevice(HOSTNAME, mainAlexaEvent, EspalexaDeviceType::color);
#endif
espalexa.addDevice(alexa_main);
#ifdef AddAutoplayDevice
espalexa.addDevice(AddAutoplayDevice, AlexaAutoplayEvent, EspalexaDeviceType::onoff); //non-dimmable device
#endif
#ifdef AddStrobeDevice
espalexa.addDevice(AddStrobeDevice, AlexaStrobeEvent, EspalexaDeviceType::color); //non-dimmable device
#endif
#ifdef AddSpecificPatternDevice
espalexa.addDevice(AddSpecificPatternDevice, AlexaSpecificEvent, EspalexaDeviceType::onoff); //non-dimmable device
#endif
webServer.onNotFound([]() {
if (!espalexa.handleAlexaApiCall(webServer.uri(), webServer.arg(0))) //if you don't know the URI, ask espalexa whether it is an Alexa control request
{
//whatever you want to do with 404s
webServer.send(404, "text/plain", "Not found");
}
});
webServer.on("/alexa", HTTP_GET, []() {
String h = "<font face='arial'><h1> Alexa pairing mode</h1>";
h += "<h2>Procedure: </h3>";
h += "The webserver will reboot and the UI won't be available.<br>";
h += "<b>Now. Say to Alexa: 'Alexa, discover devices'.<b><br><br>";
h += "Alexa should tell you that it found a new device, if it did reset the esp8266 to return to the normal mode.</font>";
webServer.send(200, "text/html", h);
delay(100);
webServer.stop();
delay(500);
webServer.close();
delay(500);
webServer2.onNotFound([]() {
if (!espalexa.handleAlexaApiCall(webServer2.uri(), webServer2.arg(0))) //if you don't know the URI, ask espalexa whether it is an Alexa control request
{
//whatever you want to do with 404s
webServer2.send(404, "text/plain", "Not found");
}
});
espalexa.begin(&webServer2);
delay(100);
while (1)
{
espalexa.loop();
delay(1);
}
});
#endif
httpUpdateServer.setup(&webServer);
webServer.on("/all", HTTP_GET, []() {
@ -391,17 +488,14 @@ void setup() {
String g = webServer.arg("g");
String b = webServer.arg("b");
setSolidColor(r.toInt(), g.toInt(), b.toInt());
alexa_main->setColor(r.toInt(), g.toInt(), b.toInt());
sendString(String(solidColor.r) + "," + String(solidColor.g) + "," + String(solidColor.b));
Serial.println(String(solidColor.r) + "," + String(solidColor.g) + "," + String(solidColor.b));
});
webServer.on("/pattern", HTTP_POST, []() {
String value = webServer.arg("value");
if (value.toInt() <= 29)
{
setPattern(value.toInt());
sendInt(currentPatternIndex);
}
setPattern(value.toInt());
sendInt(currentPatternIndex);
});
webServer.on("/patternName", HTTP_POST, []() {
@ -425,6 +519,7 @@ void setup() {
webServer.on("/brightness", HTTP_POST, []() {
String value = webServer.arg("value");
setBrightness(value.toInt());
alexa_main->setValue(brightness);
sendInt(brightness);
});
@ -480,8 +575,13 @@ void setup() {
}, handleFileUpload);
webServer.serveStatic("/", SPIFFS, "/", "max-age=86400");
#ifdef ENABLE_ALEXA_SUPPORT
espalexa.begin(&webServer);
#endif
#ifndef ENABLE_ALEXA_SUPPORT
webServer.begin();
#endif
Serial.println("HTTP web server started");
// webSocketsServer.begin();
@ -730,15 +830,33 @@ void setSolidColor(uint8_t r, uint8_t g, uint8_t b)
// increase or decrease the current pattern number, and wrap around at the ends
void adjustPattern(bool up)
{
#ifdef RANDOM_AUTOPLAY_PATTERN
if (autoplay == 1)
{
uint8_t lastpattern = currentPatternIndex;
while (currentPatternIndex == lastpattern)
{
uint8_t newpattern = random8(0, patternCount - 2);
if (newpattern != lastpattern)currentPatternIndex = newpattern;
}
}
#else // RANDOM_AUTOPLAY_PATTERN
if (up)
currentPatternIndex++;
else
currentPatternIndex--;
#endif
if (autoplay == 0)
{
if (up)
currentPatternIndex++;
else
currentPatternIndex--;
}
// wrap around at the ends
if (currentPatternIndex < 0)
currentPatternIndex = patternCount - 1;
if (currentPatternIndex >= patternCount)
if (currentPatternIndex >= (patternCount-1))
currentPatternIndex = 0;
if (autoplay == 0) {
@ -854,6 +972,36 @@ void showSolidColor()
// Patterns from FastLED example DemoReel100: https://github.com/FastLED/FastLED/blob/master/examples/DemoReel100/DemoReel100.ino
void rainbow_strobe()
{
if (autoplay == 1)adjustPattern(true);
static bool p = false;
static long lm = 0;
if (millis() - lm > (128 - (speed / 2)))
{
if (p) fill_solid(leds, NUM_LEDS, CRGB(0, 0, 0));
else fill_solid(leds, NUM_LEDS, CHSV(gHue, 255, 255));
lm = millis();
p = !p;
}
}
void strobe()
{
if (autoplay == 1)adjustPattern(true);
static bool p = false;
static long lm = 0;
if (millis() - lm > (128 - (speed / 2)))
{
if (p) fill_solid(leds, NUM_LEDS, CRGB(0, 0, 0));
else fill_solid(leds, NUM_LEDS, solidColor);
lm = millis();
p = !p;
}
}
void rainbow()
{
// FastLED's built-in rainbow generator
@ -1317,3 +1465,159 @@ void SetCustomPattern()
}
//Serial.println("");
}
// #################### Sound Reactive and Alexa below
void soundReactive()
{
static int minlevel = 0;
static int decay = 60;
static double lastlevel = 2;
static double level = 0;
#define arrsize 3
static double measure8avg[arrsize] = { 0,0,0 };
static int iter = 0;
#if SENSOR_TYPE == 0
if (digitalRead(SOUND_SENSOR_PIN) > 0)level++;
else level--;
if (level < minlevel)level = minlevel;
if (level > LEDS_PER_LINE)level = LEDS_PER_LINE;
fill_solid(leds, level, CHSV(gHue, 255, 255));
fadeToBlackBy(leds + level, LEDS_PER_LINE - level, decay);
#endif
#if SENSOR_TYPE > 0
#if SENSOR_TYPE == 2
int measure = 0;
for (int it = 0; it < 5; it++)
{
int m = analogRead(SOUND_SENSOR_PIN);
Serial.println(m);
if (m < 450 && m >350) m = 0;
else if (m < 350)m = (400 - m) * 2;
if (m > 400)m -= 400;
measure += m;
}
measure /= 5;
#endif
#if SENSOR_TYPE == 1
int measure = 0;
for (int it = 0; it < 5; it++)
{
int m = analogRead(SOUND_SENSOR_PIN);
m -= 800;
m *= -1;
if (m < 100)m = 0;
measure += m;
}
measure /= 5;
measure /= 2; // cut the volts in half
#endif
//Serial.println(measure);
iter++;
if (iter > arrsize)iter = 0;
measure8avg[iter] = measure;
double avg = 0;
for (int x = 0; x < arrsize; x++)
{
avg += measure8avg[x];
}
avg /= arrsize;
avg = measure;
int mlevel = map(avg, 30, 300, 1, NUM_LEDS);
if (mlevel < 1)mlevel = 1;
//if (lastlevel > mlevel) level = lastlevel - 0.8;
//else if (lastlevel < mlevel) level = lastlevel+1;
level = mlevel;
if (level < minlevel)level = minlevel;
if (level > NUM_LEDS)level = NUM_LEDS;
fill_solid(leds, level, CHSV(gHue, 255, 255));
fadeToBlackBy(leds + (int)level, NUM_LEDS - (int)level, decay);
lastlevel = level;
//Serial.print(mlevel); Serial.print(" "); Serial.println(level);
//Serial.printf("%d, %d\n", mlevel, level);
#endif
}
//############################## ALEXA Device Events ##############################
#ifdef ENABLE_ALEXA_SUPPORT
void mainAlexaEvent(EspalexaDevice* d) {
if (d == nullptr) return;
Serial.print("Alexa update: rgb: "); Serial.print(d->getR() + d->getG() + d->getB()); Serial.print(", b: "); Serial.println(d->getValue());
if (d->getValue() == 0)setPower(0); else {
setPower(1);
setBrightness(d->getValue());
}
static int lr;
static int lg;
static int lb;
if ((lr != NULL && lr != d->getR() && lg != d->getG() && lb != d->getB()) || currentPatternIndex == patternCount - 1)
{
setSolidColor(d->getR(), d->getG(), d->getB());
setPattern(patternCount - 1);
}
lr = d->getR();
lg = d->getG();
lb = d->getB();
}
#ifdef AddStrobeDevice
void AlexaStrobeEvent(EspalexaDevice* d) {
if (d == nullptr) return;
Serial.print("Alexa Strobe update: rgb: "); Serial.print(d->getR() + d->getG() + d->getB()); Serial.print(", b: "); Serial.println(d->getValue());
if (d->getValue() == 0)setPattern(patternCount - 1); else {
if (d->getValue() == 255)
{
setBrightness(255);
setPattern(13);
}
else speed = d->getValue();
d->setValue(speed);
}
static int lr;
static int lg;
static int lb;
if ((lr != NULL && lr != d->getR() && lg != d->getG() && lb != d->getB()) || currentPatternIndex == patternCount - 1)
{
setSolidColor(d->getR(), d->getG(), d->getB());
setPattern(12);
}
lr = d->getR();
lg = d->getG();
lb = d->getB();
}
#endif
#ifdef AddAutoplayDevice
void AlexaAutoplayEvent(EspalexaDevice* d) {
if (d == nullptr) return;
Serial.print("Alexa Autoplay update: state: "); Serial.println(d->getPercent());
if (d->getValue() > 0)
{
setAutoplay(1);
setAutoplayDuration(d->getPercent());
}
else setAutoplay(0);
}
#endif
#ifdef AddSpecificPatternDevice
void AlexaSpecificEvent(EspalexaDevice* d) {
if (d == nullptr) return;
Serial.print("Alexa Specific Pattern update: state: "); Serial.println(d->getValue());
if (d->getValue() != 0)setPattern(SpecificPattern);
else setPattern(patternCount - 1);
}
#endif
#endif