/*
* E131_Test.ino - Simple sketch to listen for E1.31 data on an ESP32 
*                  and print some statistics.
*
* Project: ESPAsyncE131 - Asynchronous E.131 (sACN) library for Arduino ESP8266 and ESP32
* Copyright (c) 2019 Shelby Merrick
* http://www.forkineye.com
*
*  This program is provided free for you to use in any way that you wish,
*  subject to the laws and regulations where you are using it.  Due diligence
*  is strongly suggested before using this code.  Please give credit where due.
*
*  The Author makes no warranty of any kind, express or implied, with regard
*  to this program or the documentation contained in this document.  The
*  Author shall not be liable in any event for incidental or consequential
*  damages in connection with, or arising out of, the furnishing, performance
*  or use of these programs.
*
*/

#include <ESPAsyncE131.h>

#define UNIVERSE 1       // First DMX Universe to listen for
#define UNIVERSE_COUNT 1 // Total number of Universes to listen for, starting at UNIVERSE

const char ssid[] = "dmx";                        // Replace with your SSID
const char passphrase[] = "DGqnu6p8ut6H2QQQ2LQH"; // Replace with your WPA2 passphrase

unsigned long packets_processed = 0;
unsigned long last_update;

void on_packet(e131_packet_t *packet, IPAddress address)
{
    /*
    Serial.printf("Universe %u / %u Channels | CH1: %u\n",
                  htons(packet->universe),
                  htons(packet->property_value_count) - 1,
                  packet->property_values[1]);
    */

    packets_processed += 1;
}

// ESPAsyncE131 instance with callback
ESPAsyncE131 e131(on_packet);

void setup()
{
    Serial.begin(500000);
    delay(10);

    // Make sure you're in station mode
    WiFi.mode(WIFI_STA);

    Serial.println("");
    Serial.print(F("Connecting to "));
    Serial.print(ssid);

    if (passphrase != NULL)
        WiFi.begin(ssid, passphrase);
    else
        WiFi.begin(ssid);

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.print(F("Connected with IP: "));
    Serial.println(WiFi.localIP());

    // Choose one to begin listening for E1.31 data
    //if (e131.begin(E131_UNICAST))                               // Listen via Unicast
    if (e131.begin(E131_MULTICAST, UNIVERSE, UNIVERSE_COUNT)) // Listen via Multicast
        Serial.println(F("Listening for data..."));
    else
        Serial.println(F("*** e131.begin failed ***"));

    last_update = millis();
}

void loop()
{
    unsigned long now = millis();

    if (now - last_update > 1000)
    {
        last_update = now;
        Serial.printf(
            "%lu %u packets processed.\n",
            now,
            packets_processed);
    }
}