Skip to content
Snippets Groups Projects
esp8266-fastled-iot-webserver.ino 149 KiB
Newer Older
  • Learn to ignore specific revisions
  •    ESP8266 FastLED WebServer: https://github.com/jasoncoon/esp8266-fastled-webserver
       Copyright (C) 2015-2018 Jason Coon
    
       This program is free software: you can redistribute it and/or modify
       it under the terms of the GNU General Public License as published by
       the Free Software Foundation, either version 3 of the License, or
       (at your option) any later version.
    
       This program is distributed in the hope that it will be useful,
       but WITHOUT ANY WARRANTY; without even the implied warranty of
       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       GNU General Public License for more details.
    
       You should have received a copy of the GNU General Public License
       along with this program.  If not, see <http://www.gnu.org/licenses/>.
    */
    
    #define FASTLED_INTERRUPT_RETRY_COUNT 1
    
    NimmLor's avatar
    NimmLor committed
    //#define FASTLED_ALLOW_INTERRUPTS 0
    
    #include <FastLED.h>
    FASTLED_USING_NAMESPACE
    extern "C" {
    #include "user_interface.h"
    }
    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>
    #include <FS.h>
    #include <EEPROM.h>
    #include "GradientPalettes.h"
    #include "Field.h"
    
    /*
        ______ _____  ____   ____  ___   _____  _____
       / ____// ___/ / __ \ ( __ )|__ \ / ___/ / ___/
      / __/   \__ \ / /_/ // __  |__/ // __ \ / __ \
     / /___  ___/ // ____// /_/ // __// /_/ // /_/ /
    /_____/ /____//_/     \____//____/\____/ \____/
        ______ ___    _____ ______ __     ______ ____
       / ____//   |  / ___//_  __// /    / ____// __ \
      / /_   / /| |  \__ \  / /  / /    / __/  / / / /
     / __/  / ___ | ___/ / / /  / /___ / /___ / /_/ /
    /_/    /_/  |_|/____/ /_/  /_____//_____//_____/
        ____ ____  ______
       /  _// __ \/_  __/
       / / / / / / / /
     _/ / / /_/ / / /
    /___/ \____/ /_/
     _       __ ______ ____  _____  ______ ____  _    __ ______ ____
    | |     / // ____// __ )/ ___/ / ____// __ \| |  / // ____// __ \
    | | /| / // __/  / __  |\__ \ / __/  / /_/ /| | / // __/  / /_/ /
    | |/ |/ // /___ / /_/ /___/ // /___ / _, _/ | |/ // /___ / _, _/
    |__/|__//_____//_____//____//_____//_/ |_|  |___//_____//_/ |_|
    
    */ 
    
    /*######################## MAIN CONFIG ########################*/
    
    NimmLor's avatar
    NimmLor committed
    #define LED_TYPE            WS2812B                     // You might also use a WS2811 or any other strip that is Fastled compatible 
    #define DATA_PIN            D3                          // Be aware: the pin mapping might be different on boards like the NodeMCU
    //#define CLK_PIN             D5                        // Only required when using 4-pin SPI-based LEDs
    #define CORRECTION          UncorrectedColor            // If colors are weird use TypicalLEDStrip
    #define COLOR_ORDER         GRB                         // Change this if colors are swapped (in my case, red was swapped with green)
    #define MILLI_AMPS          10000                       // IMPORTANT: set the max milli-Amps of your power supply (4A = 4000mA)
    #define VOLTS               5                           // Voltage of the Power Supply
    
    NimmLor's avatar
    NimmLor committed
    //#define REMOVE_VISUALIZATION          // remove the comment to completly disable all udp-based visualization patterns
    
    #define DEFAULT_HOSTNAME "LEDs"         // Name that appears in your network, don't use whitespaces, use "-" instead
    
    NimmLor's avatar
    NimmLor committed
    #define DEVICE_TYPE 0                   // The following types are available
    
    NimmLor's avatar
    NimmLor committed
        0: Generic LED-Strip: a regular LED-Strip without any special arrangement (and Infinity Mirror + Bottle Lighting Pad)
            * Easiest: 5V WS2812B LED-Strip:            https://s.click.aliexpress.com/e/_dZ1hCJ7
            * (Long Ranges) 12V WS2811 LED-Strip:       https://s.click.aliexpress.com/e/_d7Ehe3L
            * (High-Speed) 5V SK9822 LED-Strip:         https://s.click.aliexpress.com/e/_d8pzc89
            * (Expensive) 5V APA102 LED-Strip:          https://s.click.aliexpress.com/e/_Bf9wVZUD
            * (Flexible) 5V WS2812 S LED-Strip:         https://s.click.aliexpress.com/e/_d6XxPOH
            * Wemos D1 Mini:                            https://s.click.aliexpress.com/e/_dTVGMGl
            * 5V Power Supply:                          https://s.click.aliexpress.com/e/_dY5zCWt
            * Solderless LED-Connector:                 https://s.click.aliexpress.com/e/_dV4rsjF
            * 3D-Printed Wemos-D1 case:                 https://www.thingiverse.com/thing:3544576
        1: LED-Matrix: With a flexible LED-Matrix you can display the audio like a Audio Visualizer
            * Flexible WS2812 Matrix:                   https://s.click.aliexpress.com/e/_d84R5kp
            * Wemos D1 Mini:                            https://s.click.aliexpress.com/e/_dTVGMGl
            * 5V Power Supply:                          https://s.click.aliexpress.com/e/_dY5zCWt
        2: 3D-Printed 7-Segment Clock, display the time in a cool 7-segment style, syncs with a ntp of your choice
            * unfortunatly the "thing's" description isn't updated yet to the new standalone system
            * Project link, small version:              https://www.thingiverse.com/thing:3117494
            * Project link, large version:              https://www.thingiverse.com/thing:2968056
        3: 3D-Printed Desk Lamp, a Lamp that reacts to sound for your desk
            * Project link, twisted version:            https://www.thingiverse.com/thing:4129249
            * Project link, round version:              https://www.thingiverse.com/thing:3676533
        4: 3D-Printed Nanoleafs, a Nanoleaf clone that can be made for cheap
            * Project link:                             https://www.thingiverse.com/thing:3354082
        5: 3D-Printed Animated RGB Logos
            * Project link, Twenty-One-Pilots:          https://www.thingiverse.com/thing:3523487
            * Project link, Thingiverse:                https://www.thingiverse.com/thing:3531086
    
    */
    
    //---------------------------------------------------------------------------------------------------------//
    // Device Configuration:
    //---------------------------------------------------------------------------------------------------------//
    
    NimmLor's avatar
    NimmLor committed
    #if DEVICE_TYPE == 0                // Generic LED-Strip
    
    NimmLor's avatar
    NimmLor committed
        #define NUM_LEDS 24
    
    NimmLor's avatar
    NimmLor committed
        //#define NUM_LEDS 33
        //#define NUM_LEDS 183
        #define BAND_GROUPING    1            // Groups part of the band to save performance and network traffic
    #elif DEVICE_TYPE == 1              // LED MATRIX
        #define LENGTH 32
        #define HEIGHT 8
        //#define AddLogoVisualizers          // (only 32x8) Adds Visualization patterns with logo (currently only HBz)
    #elif DEVICE_TYPE == 2              // 7-Segment Clock
        #define NTP_REFRESH_INTERVAL_SECONDS 600            // 10 minutes
        const char* ntpServerName = "at.pool.ntp.org";      // Austrian ntp-timeserver
    
        int t_offset = 1;                                   // offset added to the time from the ntp server
        bool updateColorsEverySecond = false;               // if set to false it will update colors every minute (time patterns only)
    
    NimmLor's avatar
    NimmLor committed
        const int NTP_PACKET_SIZE = 48;
    
        bool switchedTimePattern = true;
    
    NimmLor's avatar
    NimmLor committed
        #define NUM_LEDS 30
        #define Digit1 0
        #define Digit2 7
        #define Digit3 16
        #define Digit4 23
        // Values for the Big Clock: 58, 0, 14, 30, 44
    
    #elif DEVICE_TYPE == 3              // Desk Lamp
        #define LINE_COUNT    8             // Amount of led strip pieces
        #define LEDS_PER_LINE 10            // Amount of led pixel per single led strip piece
    
    #elif DEVICE_TYPE == 4              // Nanoleafs
        #define LEAFCOUNT 12                // Amount of triangles
        #define PIXELS_PER_LEAF 12          // Amount of LEDs inside 1x Tringle
    
    #elif DEVICE_TYPE == 5              // Animated Logos
        // Choose your logo below, remove the comment in front of your design
        // Important: see "LOGO CONFIG" below
    
        //#define TWENTYONEPILOTS
        #define THINGIVERSE
    
    
    #endif
    
    //---------------------------------------------------------------------------------------------------------//
    // Feature Configuration: Enabled by removing the "//" in front of the define statements
    //---------------------------------------------------------------------------------------------------------//
    
        //#define ENABLE_OTA_SUPPORT                // requires ArduinoOTA - library, not working on esp's with 1MB memory (esp-01, Wemos D1 lite ...)
    
    NimmLor's avatar
    NimmLor committed
            //#define OTA_PASSWORD "passwd123"      //  password that is required to update the esp's firmware wireless
    
    NimmLor's avatar
    NimmLor committed
        #define ENABLE_MULTICAST_DNS              // allows to access the UI via "http://<HOSTNAME>.local/", implemented by GitHub/WarDrake
    
    NimmLor's avatar
    NimmLor committed
        #define RANDOM_AUTOPLAY_PATTERN             // if enabled the next pattern for autoplay is choosen at random
        #define AUTOPLAY_IGNORE_UDP_PATTERNS        // remove visualization patterns from autoplay
    
    NimmLor's avatar
    NimmLor committed
        //#define ENABLE_ALEXA_SUPPORT              // Espalexa library required
    
    NimmLor's avatar
    NimmLor committed
        //#define SOUND_SENSOR_SUPPORT              // allows to control the leds using a physical sound-sensor, configuration below
    
    NimmLor's avatar
    NimmLor committed
        //#define ENABLE_SERIAL_AMBILIGHT           // allows to function as an ambilight behind a monitor by using data from usb-serial (integration of adalight)
    
    NimmLor's avatar
    NimmLor committed
        //#define ENABLE_MQTT_SUPPORT               // allows integration in homeassistant/googlehome/mqtt, 
                                                    // mqtt server required, see MQTT Configuration for more, implemented by GitHub/WarDrake
    
    
    //---------------------------------------------------------------------------------------------------------//
    
    
    /*############ 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. Or click
     * the alexa button in the navbar.
     * 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 strip,
     * the code must create multiple alexa devices. However you can
     * use
     *
     * To add those extra devices remove the two "//" in front of the,
     * defines below.
     *
     * The Devices with specific pattern, require the corresponding SpecificPatternX 
     * statement, as argument you have to provide the zero-based index of the `patterns`
     * array below. (Hint: CTRL + F -> "patterns =")
     * 
     */
    #ifdef ENABLE_ALEXA_SUPPORT
    
        //#define ALEXA_DEVICE_NAME           DEFAULT_HOSTNAME
        //#define AddAutoplayDevice             ((String)DEFAULT_HOSTNAME + (String)" Autoplay")
        //#define AddStrobeDevice               ((String)DEFAULT_HOSTNAME + (String)" Strobe")
        //#define AddSpecificPatternDeviceA     ((String)DEFAULT_HOSTNAME + (String)" Party")
        //#define AddSpecificPatternDeviceB     ((String)DEFAULT_HOSTNAME + (String)" Chill")
        //#define AddSpecificPatternDeviceC     ((String)DEFAULT_HOSTNAME + (String)" Rainbow")
        //#define AddAudioDevice                ((String)DEFAULT_HOSTNAME + (String)" Audio")
    
    NimmLor's avatar
    NimmLor committed
        //#define SpecificPatternA 37           // Parameter defines what pattern gets executed
        //#define SpecificPatternB 12           // Parameter defines what pattern gets executed
        //#define SpecificPatternC 0            // Parameter defines what pattern gets executed
        //#define AudioPattern 44               // Parameter defines what pattern gets executed
    
    
    #endif // ENABLE_ALEXA_SUPPORT
    /*########## Alexa Configuration END ##########*/
    
    
    
    /*######################## ANIMATED RGB LOGO CONFIG ########################*/
    
    #ifdef TWENTYONEPILOTS
    
    NimmLor's avatar
    NimmLor committed
        #define RING_LENGTH 24                                      // amount of pixels for the Ring (should be 24)
        #define DOUBLE_STRIP_LENGTH 2                               // amount of pixels used for the straight double line
        #define DOT_LENGTH 1                                        // amount of pixels used for the dot
        #define ITALIC_STRIP_LENGTH 2                               // amount of pixels used for the 
        #define ANIMATION_NAME "Twenty One Pilots - Animated"       // name for the Logo animation, displayed on the webserver
        #define ANIMATION_NAME_STATIC "Twenty One Pilots - Static"  // logo for the static logo, displayed on the webserver
        #define ANIMATION_RING_DURATION 30                          // longer values result into a longer loop duration
        #define STATIC_RING_COLOR CRGB(222,255,5)                   // Color for the outer ring in static mode
        #define STATIC_LOGO_COLOR CRGB(150,240,3)                   // Color for the inner logo in static mode
    
    /*
    Wiring order:
    The array below will determine the order of the wiring,
      the first value is for the ring, I've hooked it up after the inner part,
      so it's the start value is the total length of all other pixels (2+1+2)
    the second one is for the vertical double line
      in my case it was the first one that is connected to the esp8266,
    the third one is for the dot and the fourth one for the angled double line
    if you have connected the ring first it should look like this: const int twpOffsets[] = { 0,24,26,27 };
    */
    // Syntax: { <RING>, <VERTICAL>, <HORIZONTAL_DOT>, <ANGLED> };
    // The values represent the zero-based index on the strip of the element
    
    NimmLor's avatar
    NimmLor committed
        const int twpOffsets[] = { 5,0,2,3 };
    
    #endif  // TWENTYONEPILOTS
    
    #ifdef THINGIVERSE
    
    NimmLor's avatar
    NimmLor committed
        #define RING_LENGTH 24                                  // amount of pixels for the Ring (should be 24)
        #define HORIZONTAL_LENGTH 3                             // amount of pixels used for the straight double line
        #define VERTICAL_LENGTH 2                               // amount of pixels used for the straight double line
        #define ANIMATION_NAME "Thingiverse - Animated"         // name for the Logo animation, displayed on the webserver
        #define ANIMATION_NAME_STATIC "Thingiverse - Static"    // logo for the static logo, displayed on the webserver
        #define ANIMATION_RING_DURATION 30                      // longer values result into a longer loop duration
        #define STATIC_RING_COLOR CRGB(0,149,255)               // Color for the outer ring in static mode
        #define STATIC_LOGO_COLOR CRGB(0,149,255)               // Color for the inner logo in static mode
        #define RINGFIRST false                                 // change this to <true> if you have wired the ring first
        #define HORIZONTAL_BEFORE_VERTICAL true                 // change this to <true> if you have wired the horizontal strip before the vertical
    
    #endif  // THINGIVERSE
    
    /*###################### ANIMATED RGB LOGO CONFIG END ######################*/
    
    /*-------- SOUND SENSOR (LEGACY) --------*/
    #ifdef SOUND_SENSOR_SUPPORT
    
    NimmLor's avatar
    NimmLor committed
        #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
        // Values for MAX44666:
        int16_t audioMinVol = 135;        // minimal Voltage from Mic, higher Value = less sensitive
        int16_t audioMaxVol = 145;        // maximal Voltage from Mic, lower Value = more LED on with lower Volume
    
    #endif
    /*------ SOUND SENSOR (LEGACY) END ------*/
    
    
    /*######################## MQTT Configuration ########################*/
    #ifdef ENABLE_MQTT_SUPPORT
    
        // these are deafault settings which can be changed in the web interface "settings" page
        #define MQTT_ENABLED 0
        #define MQTT_HOSTNAME "homeassistant.local"
        #define MQTT_PORT 1883
        #define MQTT_USER "MyUserName"
        #define MQTT_PASS ""
    
    NimmLor's avatar
    NimmLor committed
        #if DEVICE_TYPE == 0
            #define MQTT_TOPIC "homeassistant/light/ledstrip"               // MQTT Topic to Publish to for state and config (Home Assistant)
            #define MQTT_TOPIC_SET "/set"                                   // MQTT Topic to subscribe to for changes(Home Assistant)
            #define MQTT_DEVICE_NAME "Ledstrip"
        #elif DEVICE_TYPE == 1
            #define MQTT_TOPIC "homeassistant/light/ledmatrix"              // MQTT Topic to Publish to for state and config (Home Assistant)
            #define MQTT_TOPIC_SET "/set"                                   // MQTT Topic to subscribe to for changes(Home Assistant)
            #define MQTT_DEVICE_NAME "Led Matrix"
        #elif DEVICE_TYPE == 2
            #define MQTT_TOPIC "homeassistant/light/7-segment-clock"        // MQTT Topic to Publish to for state and config (Home Assistant)
            #define MQTT_TOPIC_SET "/set"                                   // MQTT Topic to subscribe to for changes(Home Assistant)
            #define MQTT_DEVICE_NAME "7 Segment Clock"
        #elif DEVICE_TYPE == 3
            #define MQTT_TOPIC "homeassistant/light/desklamp"               // MQTT Topic to Publish to for state and config (Home Assistant)
            #define MQTT_TOPIC_SET "/set"                                   // MQTT Topic to subscribe to for changes(Home Assistant)
            #define MQTT_DEVICE_NAME "Led Desk Lamp"
        #elif DEVICE_TYPE == 4
            #define MQTT_TOPIC "homeassistant/light/nanoleafs"              // MQTT Topic to Publish to for state and config (Home Assistant)
            #define MQTT_TOPIC_SET "/set"                                   // MQTT Topic to subscribe to for changes(Home Assistant)
            #define MQTT_DEVICE_NAME "Nanoleafs"
        #elif DEVICE_TYPE == 5
            #define MQTT_TOPIC "homeassistant/light/ledlogo"                // MQTT Topic to Publish to for state and config (Home Assistant)
            #define MQTT_TOPIC_SET "/set"                                   // MQTT Topic to subscribe to for changes(Home Assistant)
            #define MQTT_DEVICE_NAME "Animated Logo"
        #endif
        #define MQTT_UNIQUE_IDENTIFIER WiFi.macAddress()                    // A Unique Identifier for the device in Homeassistant (MAC Address used by default)
        #define MQTT_MAX_PACKET_SIZE 512
        #define MQTT_MAX_TRANSFER_SIZE 512
    
        #include <PubSubClient.h>                                           // Include the MQTT Library, must be installed via the library manager
        #include <ArduinoJson.h> 
        WiFiClient espClient;
        PubSubClient mqttClient(espClient);
    
    #endif
    /*###################### MQTT Configuration END ######################*/
    
    /*#########################################################################################################//
    -----------------------------------------------------------------------------------------------------------//
      _____ ____   _  __ ____ ____ _____    ____ _  __ ___ 
     / ___// __ \ / |/ // __//  _// ___/   / __// |/ // _ \
    / /__ / /_/ //    // _/ _/ / / (_ /   / _/ /    // // /
    \___/ \____//_/|_//_/  /___/ \___/   /___//_/|_//____/ 
    -----------------------------------------------------------------------------------------------------------//
    ###########################################################################################################*/
    
    #ifdef DEVICE_TYPE
    
    #include <WiFiUdp.h>
    
    NimmLor's avatar
    NimmLor committed
        #define PACKET_LENGTH LENGTH
        #define NUM_LEDS (HEIGHT * LENGTH)
        #define PACKET_LENGTH LENGTH
    
    NimmLor's avatar
    NimmLor committed
        #define BAND_GROUPING    1
    
    NimmLor's avatar
    NimmLor committed
        #define PACKET_LENGTH NUM_LEDS
    
    NimmLor's avatar
    NimmLor committed
        #define BAND_GROUPING    1
    
    NimmLor's avatar
    NimmLor committed
        IPAddress timeServerIP;
        WiFiUDP udpTime;
    
    NimmLor's avatar
    NimmLor committed
        byte packetBuffer[NTP_PACKET_SIZE];
        int hours = 0; int mins = 0; int secs = 0;
        unsigned int localPortTime = 2390;
        unsigned long update_timestamp = 0;
        unsigned long last_diff = 0;
        unsigned long ntp_timestamp = 0;
    
    NimmLor's avatar
    NimmLor committed
        #define NUM_LEDS      (LINE_COUNT * LEDS_PER_LINE)
        #define PACKET_LENGTH LEDS_PER_LINE
    
    NimmLor's avatar
    NimmLor committed
        #define BAND_GROUPING    1
    
    NimmLor's avatar
    NimmLor committed
        #define NUM_LEDS (PIXELS_PER_LEAF * LEAFCOUNT)
        #define PACKET_LENGTH (LEAFCOUNT * 3)
    
    NimmLor's avatar
    NimmLor committed
        #define BAND_GROUPING    1
    
    
    #elif VISUALIZER_TYPE == 5
    
    NimmLor's avatar
    NimmLor committed
        #define BAND_GROUPING    1
    
    NimmLor's avatar
    NimmLor committed
        #ifdef TWENTYONEPILOTS
            #define NUM_LEDS      (RING_LENGTH+DOT_LENGTH+DOUBLE_STRIP_LENGTH+ITALIC_STRIP_LENGTH)
        #endif
        #ifdef THINGIVERSE
            #define NUM_LEDS      (RING_LENGTH+HORIZONTAL_LENGTH+VERTICAL_LENGTH)
        #endif
    
    NimmLor's avatar
    NimmLor committed
        #ifdef BAND_GROUPING
            #define PACKET_LENGTH (int)((NUM_LEDS/BAND_GROUPING))
        #else
            #define PACKET_LENGTH NUM_LEDS
        #endif
    
        #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager/tree/development
        WiFiManager wifiManager;
    
    
    // Misc Params
    #define AVG_ARRAY_SIZE 10
    
    NimmLor's avatar
    NimmLor committed
    #define BAND_START 0
    
    NimmLor's avatar
    NimmLor committed
    #define BAND_END 3        // can be increased when working with bigger spectrums (40+)
    
    NimmLor's avatar
    NimmLor committed
        WiFiUDP Udp;
        unsigned int localUdpPort = UDP_PORT;  // local port to listen on
        uint8_t incomingPacket[PACKET_LENGTH + 1];
    
    // include config management
    #include "config.h"
    
    ESP8266WebServer webServer(80);
    
    #include "FSBrowser.h"
    #define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
    #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 FRAMES_PER_SECOND
    
    #ifdef ENABLE_OTA_SUPPORT
    #include <ArduinoOTA.h>
    #endif
    
    #ifdef ENABLE_ALEXA_SUPPORT
    #include <Espalexa.h>
    void mainAlexaEvent(EspalexaDevice*);
    Espalexa espalexa;
    ESP8266WebServer webServer2(80);
    EspalexaDevice* alexa_main;
    #endif // ENABLE_ALEXA_SUPPORT
    
    #ifdef ENABLE_MULTICAST_DNS
    #include <ESP8266mDNS.h>
    #endif // ENABLE_MULTICAST_DNS
    
    
    CRGB leds[NUM_LEDS];
    
    const uint8_t brightnessCount = 5;
    uint8_t brightnessMap[brightnessCount] = { 5, 32, 64, 128, 255 };
    
    uint8_t brightnessIndex = 3;
    
    
    // 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;
    
    ///////////////////////////////////////////////////////////////////////
    
    // Forward declarations of an array of cpt-city gradient palettes, and
    // a count of how many there are.  The actual color palette definitions
    // are at the bottom of this file.
    extern const TProgmemRGBGradientPalettePtr gGradientPalettes[];
    
    uint8_t gCurrentPaletteNumber = 0;
    
    CRGBPalette16 gCurrentPalette(CRGB::Black);
    CRGBPalette16 gTargetPalette(gGradientPalettes[0]);
    
    CRGBPalette16 IceColors_p = CRGBPalette16(CRGB::Black, CRGB::Blue, CRGB::Aqua, CRGB::White);
    
    uint8_t currentPatternIndex = 2; // Index number of which pattern is current
    uint8_t autoplay = 0;
    
    uint8_t autoplayDuration = 10;
    unsigned long autoPlayTimeout = 0;
    
    uint8_t currentPaletteIndex = 0;
    
    uint8_t gHue = 0; // rotating "base color" used by many of the patterns
    
    uint8_t slowHue = 0; // slower gHue
    
    NimmLor's avatar
    NimmLor committed
    uint8_t verySlowHue = 0; // very slow gHue
    
    
    CRGB solidColor = CRGB::Blue;
    
    // scale the brightness of all pixels down
    void dimAll(byte value)
    {
    
    NimmLor's avatar
    NimmLor committed
        for (int i = 0; i < NUM_LEDS; i++) {
            leds[i].nscale8(value);
        }
    
    }
    
    typedef void(*Pattern)();
    typedef Pattern PatternList[];
    typedef struct {
    
    NimmLor's avatar
    NimmLor committed
        Pattern pattern;
        String name;
    
        // these settings decide if certain controls/fields are displayed in the web interface
    
        bool show_palette;
        bool show_speed;
        bool show_color_picker;
        bool show_cooling_sparking;
        bool show_twinkle;
    
    } PatternAndName;
    typedef PatternAndName PatternAndNameList[];
    
    #include "Twinkles.h"
    #include "TwinkleFOX.h"
    
    // List of patterns to cycle through.  Each is defined as a separate function below.
    
    PatternAndNameList patterns = {
    
    
    NimmLor's avatar
    NimmLor committed
        // Time patterns
    
    #if DEVICE_TYPE == 2                                 // palet  speed  color  spark  twinkle
        { displayTimeStatic,        "Time",                 true,  true,  true,  false, false},
        { displayTimeColorful,      "Time Colorful",        true,  true,  true,  false, false},
        { displayTimeGradient,      "Time Gradient",        true,  true,  true,  false, false},
        { displayTimeGradientLarge, "Time Gradient large",  true,  true,  true,  false, false},
        { displayTimeRainbow,       "Time Rainbow",         true,  true,  true,  false, false},
    
    #if DEVICE_TYPE == 3                                 // palet  speed  color  spark  twinkle
        { pride_Waves,            "Pride Waves",            true,  true,  true,  false, false},
        { pride_Rings,            "Pride Rings",            true,  true,  true,  false, false},
        { colorWaves_hori,        "Vertical Waves",         true,  true,  true,  false, false},
        { colorWaves_vert,        "Color Rings",            true,  true,  true,  false, false},
        { rainbow_vert,           "Vertical Rainbow",       true,  true,  true,  false, false},
    
        // animation patterns                            // palet  speed  color  spark  twinkle
        { pride,                  "Pride",                  false, false, false, false, false},
        { colorWaves,             "Color Waves",            false, false, false, false, false},
        { rainbow,                "Horizontal Rainbow",     false, false, false, false, false},
        { rainbowSolid,           "Solid Rainbow",          false, false, false, false, false},
        { confetti,               "Confetti",               false, false, false, false, false},
        { sinelon,                "Sinelon",                true,  true,  false, false, false},
        { bpm,                    "Beat",                   true,  true,  false, false, false},
        { juggle,                 "Juggle",                 false, false, false, false, false},
        { fire,                   "Fire",                   false, false, false, true,  false},
        { water,                  "Water",                  false, false, false, true,  false},
        { strobe,                 "Strobe",                 false, true,  true,  false, false},
        { rainbow_strobe,         "Rainbow Strobe",         false, true,  false, false, false},
        { smooth_rainbow_strobe,  "Smooth Rainbow Strobe",  false, true,  false, false, false},
    
        // DigitalJohnson patterns                       // palet  speed  color  spark  twinkle
        { rainbowRoll,            "Rainbow Roll",           false, false, false, false, false},
        { rainbowBeat,            "Rainbow Beat",           false, true,  false, false, false},
        { randomPaletteFades,     "Palette Fades",          true,  false, false, false, false},
        { rainbowChase,           "Rainbow Chase",          false, false, false, false, false},
        { randomDots,             "Rainbow Dots",           false, false, false, false, false},
        { randomFades,            "Rainbow Fades",          false, false, false, false, false},
        { policeLights,           "Police Lights",          false, false, false, false, false},
        { glitter,                "Glitter",                false, true,  false, false, false},
        { snowFlakes,             "Snow Flakes",            false, false, false, false, false},
        { lightning,              "Lightning",              false, false, false, false, false},
    
        // twinkle patterns                              // palet  speed  color  spark  twinkle
        { rainbowTwinkles,        "Rainbow Twinkles",       false, false, false, false, false},
        { snowTwinkles,           "Snow Twinkles",          false, false, false, false, false},
        { cloudTwinkles,          "Cloud Twinkles",         false, false, false, false, false},
        { incandescentTwinkles,   "Incandescent Twinkles",  false, false, false, false, false},
    
        // TwinkleFOX patterns                                 // palet  speed  color  spark  twinkle
        { retroC9Twinkles,        "Retro C9 Twinkles",            false, false, false, false, true},
        { redWhiteTwinkles,       "Red & White Twinkles",         false, false, false, false, true},
        { blueWhiteTwinkles,      "Blue & White Twinkles",        false, false, false, false, true},
        { redGreenWhiteTwinkles,  "Red, Green & White Twinkles",  false, false, false, false, true},
        { fairyLightTwinkles,     "Fairy Light Twinkles",         false, false, false, false, true},
        { snow2Twinkles,          "Snow 2 Twinkles",              false, false, false, false, true},
        { hollyTwinkles,          "Holly Twinkles",               false, false, false, false, true},
        { iceTwinkles,            "Ice Twinkles",                 false, false, false, false, true},
        { partyTwinkles,          "Party Twinkles",               false, false, false, false, true},
        { forestTwinkles,         "Forest Twinkles",              false, false, false, false, true},
        { lavaTwinkles,           "Lava Twinkles",                false, false, false, false, true},
        { fireTwinkles,           "Fire Twinkles",                false, false, false, false, true},
        { cloud2Twinkles,         "Cloud 2 Twinkles",             false, false, false, false, true},
        { oceanTwinkles,          "Ocean Twinkles",               false, false, false, false, true},
    
    
    #ifndef REMOVE_VISUALIZATION
    
    NimmLor's avatar
    NimmLor committed
        // Visualization Patterns
    
    #if DEVICE_TYPE == 1                      // Matrix                          // palet  speed  color  spark  twinkle
        { RainbowVisualizer,                  "Rainbow Visualization",              true,  true,  true,  false, false},
        { SingleColorVisualizer,              "Single Color Visualization",         true,  true,  true,  false, false},
        { RainbowVisualizerDoubleSided,       "Rainbow Visualization Outside",      true,  true,  true,  false, false},
        { SingleColorVisualizerDoubleSided,   "Single Color Visualization Outside"  true,  true,  true,  false, false},
    
    NimmLor's avatar
    NimmLor committed
        
        #ifdef AddLogoVisualizers
    
            #if LENGTH == 32 && HEIGHT == 8   // Logo Visualizers
    
          { HbzVisualizerRainbow,             "Hbz Visualizer Spectrum",            true,  true,  true,  false, false},
            { HbzVisualizerWhite,             "Hbz Visualizer",                     true,  true,  true,  false, false},
    
    NimmLor's avatar
    NimmLor committed
            #endif
        #endif
    
      #ifdef DEVICE_TYPE            // Generic Visualization Patterns                // palet  speed  color  spark  twinkle
        { vuMeterSolid,                 "Solid Volume Visualizer",                      true,  true,  true,  false, false},
        { vuMeterStaticRainbow,         "Static Rainbow Volume Visualizer",             true,  true,  true,  false, false},
        { vuMeterRainbow,               "Flowing Rainbow Volume Visualizer",            true,  true,  true,  false, false},
        { vuMeterTriColor,              "Tri-Color Volume Visualizer",                  true,  true,  true,  false, false},
        { RefreshingVisualizer,         "Wave Visualizer",                              true,  true,  true,  false, false},
        { CentralVisualizer,            "Center Visualizer",                            true,  true,  true,  false, false},
        { SolidColorDualTone,           "Solid-Color Pair Bullet Visualizer",           true,  true,  true,  false, false},
        { SolidColorComplementary,      "Solid-Color Complementary Bullet Visualizer",  true,  true,  true,  false, false},
        { BluePurpleBullets,            "Blue/Purple Bullet Visualizer",                true,  true,  true,  false, false},
        { BulletVisualizer,             "Beat-Bullet Visualization",                    true,  true,  true,  false, false},
    
        //{ RainbowPeaks,                 "Rainbow Peak Visualizer"},                     // broken
    
        { RainbowBassRings,             "Bass Ring Visualizer",                         true,  true,  true,  false, false},
        { RainbowKickRings,             "Kick Ring Visualizer",                         true,  true,  true,  false, false},
    
        //{ TrailingBulletsVisualizer,    "Trailing Bullet Visualization"},               // obsolete
        //{ BrightnessVisualizer,         "Brightness Visualizer"},                       // broken
    
        { RainbowBandVisualizer,        "Rainbow Band Visualizer",                      true,  true,  true,  false, false},
        { SingleColorBandVisualizer,    "Single Color Band Visualizer",                 true,  true,  true,  false, false},
    
    #if DEVICE_TYPE == 4                                                       // palet  speed  color  spark  twinkle
        { NanoleafWaves,                "Nanoleaf Wave Visualizer",               true,  true,  true,  false, false},
        { NanoleafBand,                 "Nanoleaf Rainbow Band Visualizer",       true,  true,  true,  false, false},
        { NanoleafSingleBand,           "Nanoleaf Solid Color Band Visualizer",   true,  true,  true,  false, false},
    
      #ifdef ENABLE_SERIAL_AMBILIGHT                       // palet  speed  color  spark  twinkle
        { ambilight,                    "⋆Serial Ambilight",  true,  true,  true,  false, false},
    
      #endif // ENABLE_SERIAL_AMBILIGHT
    #ifdef SOUND_SENSOR_SUPPORT
    
        { soundReactive,                "Sound Reactive",     true,  true,  true,  false, false},
    
        { showSolidColor,               "Solid Color",        false, false, true,  false, false}
    
    };
    
    
    const uint8_t patternCount = ARRAY_SIZE(patterns);
    
    typedef struct {
    
    NimmLor's avatar
    NimmLor committed
        CRGBPalette16 palette;
        String name;
    
    } PaletteAndName;
    typedef PaletteAndName PaletteAndNameList[];
    
    const CRGBPalette16 palettes[] = {
      RainbowColors_p,
      RainbowStripeColors_p,
      CloudColors_p,
      LavaColors_p,
      OceanColors_p,
      ForestColors_p,
      PartyColors_p,
      HeatColors_p
    };
    
    const uint8_t paletteCount = ARRAY_SIZE(palettes);
    
    const String paletteNames[paletteCount] = {
      "Rainbow",
      "Rainbow Stripe",
      "Cloud",
      "Lava",
      "Ocean",
      "Forest",
      "Party",
      "Heat",
    };
    
    #include "Fields.h"
    
    
    
    
    Ing. Jan Kaláb's avatar
    Ing. Jan Kaláb committed
    void setSolidColor(uint8_t r, uint8_t g, uint8_t b, bool updatePattern)
    
    NimmLor's avatar
    NimmLor committed
        solidColor = CRGB(r, g, b);
    
        cfg.red = r;
        cfg.green = g;
        cfg.blue = b;
        save_config = true;
    
    NimmLor's avatar
    NimmLor committed
        if (updatePattern && currentPatternIndex != patternCount - 2)setPattern(patternCount - 1);
    
    NimmLor's avatar
    NimmLor committed
        broadcastString("color", String(solidColor.r) + "," + String(solidColor.g) + "," + String(solidColor.b));
    
    Ing. Jan Kaláb's avatar
    Ing. Jan Kaláb committed
    void setSolidColor(CRGB color, bool updatePattern)
    
    NimmLor's avatar
    NimmLor committed
        setSolidColor(color.r, color.g, color.b, updatePattern);
    
    NimmLor's avatar
    NimmLor committed
        return "<html><head><meta http-equiv=\"refresh\" content=\"4; url=/\"/></head><body><font face='arial'><b><h2>Rebooting... returning in 4 seconds</h2></b></font></body></html>";
    
    NimmLor's avatar
    NimmLor committed
        webServer.send(200, "text/html", getRebootString());
        delay(500);
        ESP.restart();
    
    #ifdef ENABLE_ALEXA_SUPPORT
    
    NimmLor's avatar
    NimmLor committed
        webServer2.send(200, "text/html", getRebootString());
        delay(500);
        ESP.restart();
    
    Ing. Jan Kaláb's avatar
    Ing. Jan Kaláb committed
    void addRebootPage(int webServerNr)
    
    NimmLor's avatar
    NimmLor committed
        if (webServerNr < 2)
        {
            webServer.on("/reboot", handleReboot);
        }
        #ifdef ENABLE_ALEXA_SUPPORT
        else if (webServerNr == 2)
        {
            webServer2.on("/reboot", handleReboot2);
        }
        #endif // ENABLE_ALEXA_SUPPORT
    
    // we can't assing wifiManager.resetSettings(); to reset, somewhow it gets called straight away.
    void setWiFiConf(String ssid, String password)
    {
    #ifdef ESP8266
        struct station_config conf;
    
        wifi_station_get_config(&conf);
    
        memset(conf.ssid, 0, sizeof(conf.ssid));
        for (int i = 0; i < ssid.length() && i < sizeof(conf.ssid); i++)
            conf.ssid[i] = ssid.charAt(i);
    
        memset(conf.password, 0, sizeof(conf.password));
        for (int i = 0; i < password.length() && i < sizeof(conf.password); i++)
            conf.password[i] = password.charAt(i);
    
        wifi_station_set_config(&conf);
    
    // untested due to lack of ESP32
    #elif defined(ESP32)
        if(WiFiGenericClass::getMode() != WIFI_MODE_NULL){
    
              wifi_config_t conf;
              esp_wifi_get_config(WIFI_IF_STA, &conf);
    
              memset(conf.sta.ssid, 0, sizeof(conf.sta.ssid));
              ssid.toCharArray(conf.sta.ssid, sizeof(conf.sta.ssid));
              memset(conf.sta.password, 0, sizeof(conf.sta.password));
              password.toCharArray(conf.sta.password, sizeof(conf.sta.password));
    
              esp_wifi_set_config(WIFI_IF_STA, &conf);
        }
    #endif
    }
    
    NimmLor's avatar
    NimmLor committed
        WiFi.setSleepMode(WIFI_NONE_SLEEP);
        Serial.begin(115200);
    
    NimmLor's avatar
    NimmLor committed
        delay(100);
        Serial.setDebugOutput(true);
    
    
    #if LED_TYPE == WS2812 || LED_TYPE == WS2812B || LED_TYPE == WS2811 || LED_TYPE == WS2813 || LED_TYPE == NEOPIXEL
    
    NimmLor's avatar
    NimmLor committed
        FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);         // WS2812 (Neopixel)
    
    #elif defined CLK_PIN
    
    NimmLor's avatar
    NimmLor committed
        FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS); // for APA102 (Dotstar)
    
    NimmLor's avatar
    NimmLor committed
        FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);         // misc. 3-pin
    
    NimmLor's avatar
    NimmLor committed
        
        FastLED.setDither(false);
        FastLED.setCorrection(CORRECTION);
        FastLED.setBrightness(brightness);
        FastLED.setMaxPowerInVoltsAndMilliamps(VOLTS, MILLI_AMPS);
        fill_solid(leds, NUM_LEDS, CRGB::Black);
        FastLED.show();
    
    
        // set a default config to be used on config reset
        default_cfg.brightness = brightness;
        default_cfg.currentPatternIndex = currentPatternIndex;
        default_cfg.power = power;
        default_cfg.autoplay = autoplay;
        default_cfg.autoplayDuration = autoplayDuration;
        default_cfg.currentPaletteIndex = currentPaletteIndex;
        default_cfg.speed = speed;
    
    
    NimmLor's avatar
    NimmLor committed
    
        FastLED.setBrightness(brightness);
    
        //  irReceiver.enableIRIn(); // Start the receiver
    
        Serial.println();
        Serial.print(F("Heap: ")); Serial.println(system_get_free_heap_size());
        Serial.print(F("Boot Vers: ")); Serial.println(system_get_boot_version());
        Serial.print(F("CPU: ")); Serial.println(system_get_cpu_freq());
        Serial.print(F("SDK: ")); Serial.println(system_get_sdk_version());
        Serial.print(F("Chip ID: ")); Serial.println(system_get_chip_id());
        Serial.print(F("Flash ID: ")); Serial.println(spi_flash_get_id());
        Serial.print(F("Flash Size: ")); Serial.println(ESP.getFlashChipRealSize());
        Serial.print(F("Vcc: ")); Serial.println(ESP.getVcc());
        Serial.println();
    
    
    #ifdef SOUND_REACTIVE
    #if SENSOR_TYPE == 0
    
    NimmLor's avatar
    NimmLor committed
        pinMode(SOUND_SENSOR_PIN, INPUT);
    
    NimmLor's avatar
    NimmLor committed
        SPIFFS.begin();
        {
            Serial.println("SPIFFS contents:");
    
    NimmLor's avatar
    NimmLor committed
            Dir dir = SPIFFS.openDir("/");
            while (dir.next()) {
                String fileName = dir.fileName();
                size_t fileSize = dir.fileSize();
                Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), String(fileSize).c_str());
            }
            Serial.printf("\n");
        }
    
    NimmLor's avatar
    NimmLor committed
        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);
        macID.toUpperCase();
    
        String nameString = String(cfg.hostname) + String(" - ") + macID;
    
    NimmLor's avatar
    NimmLor committed
        char nameChar[nameString.length() + 1];
    
        nameString.toCharArray(nameChar, sizeof(nameChar));
    
        wifiManager.setHostname(cfg.hostname);
    
        wifiManager.setConfigPortalBlocking(false);
        wifiManager.setSaveConfigCallback(handleReboot);
    
    NimmLor's avatar
    NimmLor committed
    
        //automatically connect using saved credentials if they exist
        //If connection fails it starts an access point with the specified name
        if (wifiManager.autoConnect(nameChar)) {
    
            Serial.println("Wi-Fi connected");
    
            Serial.println("Wi-Fi manager portal running");
        }
    
    
    NimmLor's avatar
    NimmLor committed
        webServer.on("/ota", HTTP_GET, []() {
            IPAddress ip = WiFi.localIP();
            String h = "<font face='arial'><h1> OTA Update Mode</h1>";
            h += "<h2>Procedure: </h3>";
            h += "The UI won't be available until reset.<br>";
            h += "<b>Open your Arduino IDE and select the new PORT in Tools menu and upload the code!</b>";
            h += "<br>Exit OTA mode: <a href=\"http://" + ip.toString() + "/reboot\"); ' value='Reboot'>Reboot</a>";
            h += "</font>";
    
            webServer.send(200, "text/html", h);
            delay(100);
            //webServer.stop();
            //delay(500);
            //webServer.close();
            //delay(500);
            //addRebootPage();
            //delay(100);
            //webServer.stop();
            //delay(500);
            //webServer.close();
            //delay(500);
    
            ArduinoOTA.setHostname(cfg.hostname);
    
    #ifdef OTA_PASSWORD
    
    NimmLor's avatar
    NimmLor committed
            ArduinoOTA.setPassword(OTA_PASSWORD);
    
    NimmLor's avatar
    NimmLor committed
            ArduinoOTA.onStart([]() {
                String type;
                SPIFFS.end();
                if (ArduinoOTA.getCommand() == U_FLASH) {
                    type = "sketch";
                }
                else { // U_FS
                    type = "filesystem";
                }
    
                // NOTE: if updating FS this would be the place to unmount FS using FS.end()
                Serial.println("Start updating " + type);
                });
            ArduinoOTA.onEnd([]() {
                Serial.println("\nEnd");
                delay(500);
                ESP.restart();
                });
            ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
                Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
                });
            ArduinoOTA.onError([](ota_error_t error) {
                Serial.printf("Error[%u]: ", error);
                if (error == OTA_AUTH_ERROR) {
                    Serial.println("Auth Failed");
                }
                else if (error == OTA_BEGIN_ERROR) {
                    Serial.println("Begin Failed");
                }
                else if (error == OTA_CONNECT_ERROR) {
                    Serial.println("Connect Failed");
                }
                else if (error == OTA_RECEIVE_ERROR) {
                    Serial.println("Receive Failed");
                }
                else if (error == OTA_END_ERROR) {
                    Serial.println("End Failed");
                }
                });
            ArduinoOTA.begin();
            delay(100);
            while (1)
            {
                ArduinoOTA.handle();
                delay(1);
                webServer.handleClient();
                delay(1);
            }
            });
    
    #endif
    
    #ifdef ENABLE_ALEXA_SUPPORT
    #ifdef ALEXA_DEVICE_NAME
    
    NimmLor's avatar
    NimmLor committed
        alexa_main = new EspalexaDevice(ALEXA_DEVICE_NAME, mainAlexaEvent, EspalexaDeviceType::color);
    
        alexa_main = new EspalexaDevice(cfg.hostname, mainAlexaEvent, EspalexaDeviceType::color);
    
    NimmLor's avatar
    NimmLor committed
        espalexa.addDevice(alexa_main);
    
    #ifdef AddAutoplayDevice
    
    NimmLor's avatar
    NimmLor committed
        espalexa.addDevice(AddAutoplayDevice, AlexaAutoplayEvent, EspalexaDeviceType::onoff); //non-dimmable device
    
    #endif
    #ifdef AddStrobeDevice
    
    NimmLor's avatar
    NimmLor committed
        espalexa.addDevice(AddStrobeDevice, AlexaStrobeEvent, EspalexaDeviceType::color); //non-dimmable device
    
    #endif
    #ifdef AddSpecificPatternDeviceA
    
    NimmLor's avatar
    NimmLor committed
        espalexa.addDevice(AddSpecificPatternDeviceA, AlexaSpecificEventA, EspalexaDeviceType::onoff); //non-dimmable device
    
    #endif
    #ifdef AddSpecificPatternDeviceB
    
    NimmLor's avatar
    NimmLor committed
        espalexa.addDevice(AddSpecificPatternDeviceB, AlexaSpecificEventB, EspalexaDeviceType::onoff); //non-dimmable device
    
    #endif
    #ifdef AddSpecificPatternDeviceC
    
    NimmLor's avatar
    NimmLor committed
        espalexa.addDevice(AddSpecificPatternDeviceC, AlexaSpecificEventC, EspalexaDeviceType::onoff); //non-dimmable device
    
    #endif
    #ifdef AddAudioDevice
    
    NimmLor's avatar
    NimmLor committed
        espalexa.addDevice(AddAudioDevice, AlexaAudioEvent, EspalexaDeviceType::onoff); //non-dimmable device
    
    NimmLor's avatar
    NimmLor committed
        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");
            }
            });
    
    
    NimmLor's avatar
    NimmLor committed
        addRebootPage(0);
    
    NimmLor's avatar
    NimmLor committed
    
        webServer.on("/alexa", HTTP_GET, []() {
            IPAddress ip = WiFi.localIP();
            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.";
            h += "<br>Exit pairing mode: <a href=\"http://" + ip.toString() + "/reboot\"); ' value='Reboot'>Reboot</a>";
            h += "</font>";
    
            webServer.send(200, "text/html", h);
            webServer2.on("/alexa", [&]() {webServer2.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");
                }
                });
            addRebootPage(2);
            delay(100);
            webServer.stop();
            delay(500);
            webServer.close();
            delay(500);
            espalexa.begin(&webServer2);
            delay(100);
            while (1)
            {
                espalexa.loop();
                delay(1);
            }
            });
    
    #else
        addRebootPage(0);
    
    NimmLor's avatar
    NimmLor committed
        webServer.on("/all", HTTP_GET, []() {
            String json = getFieldsJson(fields, fieldCount);
            json += ",{\"name\":\"lines\",\"label\":\"Amount of Lines for the Visualizer\",\"type\":\"String\",\"value\":";
            json += PACKET_LENGTH;
            json += "}";
    
            json += ",{\"name\":\"hostname\",\"label\":\"Name of the device\",\"type\":\"Setting\",\"value\":\"";
            json += cfg.hostname;
    
    NimmLor's avatar
    NimmLor committed
            json += "\"}";
    
            json += ",{\"name\":\"otaSupport\",\"label\":\"Device supports OTA\",\"type\":\"Setting\",\"value\":";
    #ifdef ENABLE_OTA_SUPPORT
            json += "true";
    #else
            json += "false";
    #endif
            json += "}";
            json += ",{\"name\":\"alexaSupport\",\"label\":\"Device supports Alexa\",\"type\":\"Setting\",\"value\":";
    #ifdef ENABLE_ALEXA_SUPPORT
            json += "true";
    #else
            json += "false";
    #endif
            json += "}";
            json += ",{\"name\":\"mqttSupport\",\"label\":\"Device supports MQTT\",\"type\":\"Setting\",\"value\":";
    #ifdef ENABLE_MQTT_SUPPORT
            json += "true";
    #else
            json += "false";
    #endif
            json += "}";
    #ifdef ENABLE_MQTT_SUPPORT