diff --git a/ampel-firmware/co2_sensor.cpp b/ampel-firmware/co2_sensor.cpp deleted file mode 100644 index b7a98d213ddf4e3625db19a5f284907c32072216..0000000000000000000000000000000000000000 --- a/ampel-firmware/co2_sensor.cpp +++ /dev/null @@ -1,348 +0,0 @@ -#include "co2_sensor.h" - -#include "web_config.h" -#include "ntp.h" -#include "led_effects.h" -#include "sensor_console.h" -#include - -// The SCD30 from Sensirion is a high quality Nondispersive Infrared (NDIR) based CO₂ sensor capable of detecting 400 to 10000ppm with an accuracy of ±(30ppm+3%). -// https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library -#include "src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.h" // From: http://librarymanager/All#SparkFun_SCD30 - -namespace config { - const uint16_t measurement_timestep_bootup = 5; // [s] Measurement timestep during acclimatization. - const uint8_t max_deviation_during_bootup = 20; // [%] - const int8_t max_deviation_during_calibration = 30; // [ppm] - const int16_t timestep_during_calibration = 10; // [s] WARNING: Measurements can be unreliable for timesteps shorter than 10s. - const int8_t stable_measurements_before_calibration = 120 / timestep_during_calibration; // [-] Stable measurements during at least 2 minutes. - const uint16_t co2_alert_threshold = 2000; // [ppm] Display a flashing led ring, if concentration exceeds this value - const bool debug_sensor_states = false; // If true, log state transitions over serial console -} - -namespace sensor { - SCD30 scd30; - uint16_t co2 = 0; - float temperature = 0; - float humidity = 0; - char timestamp[23]; - int16_t stable_measurements = 0; - - /** - * Define sensor states - * BOOTUP -> initial state, until first >0 ppm values are returned - * READY -> sensor does output valid information (> 0 ppm) and no other condition takes place - * NEEDS_CALIBRATION -> sensor measurements are too low (< 250 ppm) - * PREPARE_CALIBRATION_UNSTABLE -> forced calibration was initiated, last measurements were too far apart - * PREPARE_CALIBRATION_STABLE -> forced calibration was initiated, last measurements were close to each others - */ - enum state { - BOOTUP, - READY, - NEEDS_CALIBRATION, - PREPARE_CALIBRATION_UNSTABLE, - PREPARE_CALIBRATION_STABLE - }; - const char *state_names[] = { - "BOOTUP", - "READY", - "NEEDS_CALIBRATION", - "PREPARE_CALIBRATION_UNSTABLE", - "PREPARE_CALIBRATION_STABLE" }; - - state current_state = BOOTUP; - void switchState(state); - void setCO2forDebugging(int32_t fakeCo2); - void calibrateSensorToSpecificPPM(int32_t calibrationLevel); - void calibrateSensorRightNow(int32_t calibrationLevel); - void setAutoCalibration(int32_t autoCalibration); - - void initialize() { -#if defined(ESP8266) - Wire.begin(12, 14); // ESP8266 - D6, D5; -#endif -#if defined(ESP32) - Wire.begin(21, 22); // ESP32 - /** - * SCD30 ESP32 - * VCC --- 3V3 - * GND --- GND - * SCL --- SCL (GPIO22) //NOTE: GPIO3 Would be more convenient (right next to GND) - * SDA --- SDA (GPIO21) //NOTE: GPIO1 would be more convenient (right next to GPO3) - */ -#endif - Serial.println(); - scd30.enableDebugging(); // Prints firmware version in the console. - - if (!scd30.begin(config::auto_calibrate_sensor)) { - Serial.println(F("ERROR - CO2 sensor not detected. Please check wiring!")); - led_effects::showKITTWheel(color::red, 30); - ESP.restart(); - } - - // Changes of the SCD30's measurement timestep do not come into effect - // before the next measurement takes place. That means that after a hard reset - // of the ESP the SCD30 sometimes needs a long time until switching back to 2 s - // for acclimatization. Resetting it after startup seems to fix this behaviour. - scd30.reset(); - - //NOTE: It seems that the sensor needs some time for getting/setting temperature offset. - delay(500); - Serial.print(F("Setting temperature offset to -")); - Serial.print(abs(config::temperature_offset)); - Serial.println(F(" K.")); - scd30.setTemperatureOffset(abs(config::temperature_offset)); // setTemperatureOffset only accepts positive numbers, but shifts the temperature down. - delay(500); - - //NOTE: Even once the temperature offset is saved, the sensor still needs some time (~10 minutes?) to apply it. - Serial.print(F("Temperature offset is : ")); - Serial.print(getTemperatureOffset()); - Serial.println(F(" K")); - - Serial.print(F("Auto-calibration is ")); - Serial.println(config::auto_calibrate_sensor ? "ON." : "OFF."); - - // SCD30 has its own timer. - //NOTE: The timer seems to be inaccurate, though, possibly depending on voltage. Should it be offset? - Serial.println(); - Serial.print(F("Setting SCD30 timestep to ")); - Serial.print(config::measurement_timestep_bootup); - Serial.println(F(" s during acclimatization.")); - scd30.setMeasurementInterval(config::measurement_timestep_bootup); // [s] - - sensor_console::defineIntCommand("co2", setCO2forDebugging, F("1500 (Sets co2 level, for debugging)")); - sensor_console::defineIntCommand("timer", setTimer, F("30 (Sets measurement interval, in s)")); - sensor_console::defineCommand("calibrate", startCalibrationProcess, F("(Starts calibration process)")); - sensor_console::defineIntCommand("calibrate", calibrateSensorToSpecificPPM, - F("600 (Starts calibration process, to given ppm)")); - sensor_console::defineIntCommand("calibrate!", calibrateSensorRightNow, - F("600 (Calibrates right now, to given ppm)")); - sensor_console::defineIntCommand("auto_calibrate", setAutoCalibration, F("0/1 (Disables/enables autocalibration)")); - sensor_console::defineCommand("reset_scd", resetSCD, F("(Resets SCD30)")); - } - - bool hasSensorSettled() { - static uint16_t last_co2 = 0; - uint16_t delta; - delta = abs(co2 - last_co2); - last_co2 = co2; - // We assume the sensor has acclimated to the environment if measurements - // change less than a specified percentage of the current value. - return (co2 > 0 && delta < ((uint32_t) co2 * config::max_deviation_during_bootup / 100)); - } - - bool enoughStableMeasurements() { - static int16_t previous_co2 = 0; - if (co2 > (previous_co2 - config::max_deviation_during_calibration) - && co2 < (previous_co2 + config::max_deviation_during_calibration)) { - stable_measurements++; - Serial.print(F("Number of stable measurements : ")); - Serial.print(stable_measurements); - Serial.print(F(" / ")); - Serial.println(config::stable_measurements_before_calibration); - switchState(PREPARE_CALIBRATION_STABLE); - } else { - stable_measurements = 0; - switchState(PREPARE_CALIBRATION_UNSTABLE); - } - previous_co2 = co2; - return (stable_measurements == config::stable_measurements_before_calibration); - } - - void startCalibrationProcess() { - /** From the sensor documentation: - * Before applying FRC, SCD30 needs to be operated for 2 minutes with the desired measurement period in continuous mode. - */ - Serial.print(F("Setting SCD30 timestep to ")); - Serial.print(config::timestep_during_calibration); - Serial.println(F("s, prior to calibration.")); - scd30.setMeasurementInterval(config::timestep_during_calibration); // [s] The change will only take effect after next measurement. - Serial.println(F("Waiting until the measurements are stable for at least 2 minutes.")); - Serial.println(F("It could take a very long time.")); - switchState(PREPARE_CALIBRATION_UNSTABLE); - } - - void calibrate() { - Serial.print(F("Calibrating SCD30 now...")); - scd30.setAltitudeCompensation(config::altitude_above_sea_level); - scd30.setForcedRecalibrationFactor(config::co2_calibration_level); - Serial.println(F(" Done!")); - Serial.println(F("Sensor calibrated.")); - switchState(BOOTUP); // In order to stop the calibration and select the desired timestep. - //WARNING: Do not reset the ampel or the SCD30! - //At least one measurement needs to happen in order for the calibration to be correctly applied. - } - - void logToSerial() { - Serial.print(timestamp); - Serial.print(F(" - co2(ppm): ")); - Serial.print(co2); - Serial.print(F(" temp(C): ")); - Serial.print(temperature, 1); - Serial.print(F(" humidity(%): ")); - Serial.println(humidity, 1); - } - - void switchState(state new_state) { - if (new_state == current_state) { - return; - } - if (config::debug_sensor_states) { - Serial.print(F("Changing sensor state: ")); - Serial.print(state_names[current_state]); - Serial.print(F(" -> ")); - Serial.println(state_names[new_state]); - } - current_state = new_state; - } - - void switchStateForCurrentPPM() { - if (current_state == BOOTUP) { - if (!hasSensorSettled()) { - return; - } - switchState(READY); - Serial.println(F("Sensor acclimatization finished.")); - Serial.print(F("Setting SCD30 timestep to ")); - Serial.print(config::measurement_timestep); - Serial.println(F(" s.")); - if (config::measurement_timestep < 10) { - Serial.println(F("WARNING: Timesteps shorter than 10s can lead to unreliable measurements!")); - } - scd30.setMeasurementInterval(config::measurement_timestep); // [s] - } - - // Check for pre-calibration states first, because we do not want to - // leave them before calibration is done. - if ((current_state == PREPARE_CALIBRATION_UNSTABLE) || (current_state == PREPARE_CALIBRATION_STABLE)) { - if (enoughStableMeasurements()) { - calibrate(); - } - } else if (co2 < 250) { - // Sensor should be calibrated. - switchState(NEEDS_CALIBRATION); - } else { - switchState(READY); - } - } - - void displayCO2OnLedRing() { - /** - * Display data, even if it's "old" (with breathing). - * A short delay is required in order to let background tasks run on the ESP8266. - * see https://github.com/esp8266/Arduino/issues/3241#issuecomment-301290392 - */ - if (co2 < config::co2_alert_threshold) { - led_effects::displayCO2color(co2); - delay(100); - } else { - // Display a flashing led ring, if concentration exceeds a specific value - led_effects::alert(color::red); - } - } - - void showState() { - switch (current_state) { - case BOOTUP: - led_effects::showWaitingLED(color::blue); - break; - case READY: - displayCO2OnLedRing(); - break; - case NEEDS_CALIBRATION: - led_effects::showWaitingLED(color::magenta); - break; - case PREPARE_CALIBRATION_UNSTABLE: - led_effects::showWaitingLED(color::red); - break; - case PREPARE_CALIBRATION_STABLE: - led_effects::showWaitingLED(color::green); - break; - default: - Serial.println(F("Encountered unknown sensor state")); // This should not happen. - } - } - - /** Gets fresh data if available, checks calibration status, displays CO2 levels. - * Returns true if fresh data is available, for further processing (e.g. MQTT, CSV or LoRa) - */ - bool processData() { - bool freshData = scd30.dataAvailable(); - - if (freshData) { - ntp::getLocalTime(timestamp); - co2 = scd30.getCO2(); - temperature = scd30.getTemperature(); - humidity = scd30.getHumidity(); - - switchStateForCurrentPPM(); - - // Log every time fresh data is available. - logToSerial(); - } - - showState(); - - // Report data for further processing only if the data is reliable - // (state 'READY') or manual calibration is necessary (state 'NEEDS_CALIBRATION'). - return freshData && (current_state == READY || current_state == NEEDS_CALIBRATION); - } - - float getTemperatureOffset() { - return -abs(scd30.getTemperatureOffset()); - } - - /***************************************************************** - * Callbacks for sensor commands * - *****************************************************************/ - void setCO2forDebugging(int32_t fakeCo2) { - Serial.print(F("DEBUG. Setting CO2 to ")); - co2 = fakeCo2; - Serial.println(co2); - switchStateForCurrentPPM(); - } - - void setAutoCalibration(int32_t autoCalibration) { - config::auto_calibrate_sensor = autoCalibration; - scd30.setAutoSelfCalibration(autoCalibration); - Serial.print(F("Setting auto-calibration to : ")); - Serial.println(autoCalibration ? F("On.") : F("Off.")); - } - - void setTimer(int32_t timestep) { - if (timestep >= 2 && timestep <= 1800) { - Serial.print(F("Setting Measurement Interval to : ")); - Serial.print(timestep); - Serial.println(F("s (change will only be applied after next measurement).")); - scd30.setMeasurementInterval(timestep); - config::measurement_timestep = timestep; - led_effects::showKITTWheel(color::green, 1); - } - } - - void calibrateSensorToSpecificPPM(int32_t calibrationLevel) { - if (calibrationLevel >= 400 && calibrationLevel <= 2000) { - Serial.print(F("Force calibration, at ")); - config::co2_calibration_level = calibrationLevel; - Serial.print(config::co2_calibration_level); - Serial.println(F(" ppm.")); - startCalibrationProcess(); - } - } - - void calibrateSensorRightNow(int32_t calibrationLevel) { - if (calibrationLevel >= 400 && calibrationLevel <= 2000) { - Serial.print(F("Force calibration, right now, at ")); - config::co2_calibration_level = calibrationLevel; - Serial.print(config::co2_calibration_level); - Serial.println(F(" ppm.")); - calibrate(); - } - } - - void resetSCD() { - Serial.print(F("Resetting SCD30...")); - scd30.reset(); - Serial.println(F("done.")); - } -} diff --git a/ampel-firmware/co2_sensor.h b/ampel-firmware/co2_sensor.h deleted file mode 100644 index e152f2777e87947d0b15a7712985fe9deddf1e7a..0000000000000000000000000000000000000000 --- a/ampel-firmware/co2_sensor.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef CO2_SENSOR_H_ -#define CO2_SENSOR_H_ - -#include // For uint16_t - -namespace sensor { - extern uint16_t co2; - extern float temperature; - extern float humidity; - extern char timestamp[]; - - void initialize(); - bool processData(); - void startCalibrationProcess(); - void setTimer(int32_t timestep); - void resetSCD(); - float getTemperatureOffset(); -} -#endif diff --git a/ampel-firmware/config.public.h b/ampel-firmware/config.public.h deleted file mode 100644 index d328f42da1424fc69424f8ea5bb2ee302b4bdfcb..0000000000000000000000000000000000000000 --- a/ampel-firmware/config.public.h +++ /dev/null @@ -1,192 +0,0 @@ -#ifndef CONFIG_H_INCLUDED -# define CONFIG_H_INCLUDED - -/*** _ _ - * / \ _ __ ___ _ __ ___| | - * / _ \ | '_ ` _ \| '_ \ / _ \ | - * / ___ \| | | | | | |_) | __/ | - * /_/ __\_\_| |_| |_| .__/_\___|_| - * / ___|___ _ __|_/ _(_) __ _ - * | | / _ \| '_ \| |_| |/ _` | - * | |__| (_) | | | | _| | (_| | - * \____\___/|_| |_|_| |_|\__, | - * |___/ - ***/ - -// This file is a config template, and can be copied to config.h. -// Please don't save any important password in this template. -// IMPORTANT: Parameters defined in config.h are only default values, and are applied if: -// * the ampel is flashed for the first time -// * or 'reset_config' command is called -// * or AMPEL_CONFIG_VERSION has been changed. -// Once those default values have been applied, uploading the firmware with a modified config.h will not update the ampel configuration! -// Every parameter can be modified and saved later via the web-config. -// Some of those parameters can also be modified via commands in the Serial monitor : -// e.g. 'wifi 0' to turn WiFi off, or 'csv 60' to log data in csv every minute. -/*** - * AMPEL - */ -// You can rename the Ampel if you want. -// This name will be used for CSV files and the mDNS address. -// You'll get a new CSV file after renaming, which can be convenient, e.g. after moving -// the ampel to another room. -// If left empty, the name will be ESPxxxxxx, where xxxxxx represent the last half of the MAC address. -# define AMPEL_NAME "" - -// This password will be used for Access Point (without username), and for web-server available at http://local_ip with user 'admin', without quotes. -// If left empty, the password will have to be set during the first configuration, via access point. -// In order to be set successfully, it should have at least 8 characters. -# define AMPEL_PASSWORD "" - -// AMPEL_CONFIG_VERSION should be defined, and have exactly 3 characters. -// If you modify this string, every parameter saved on the Ampel will be replaced by the ones in config.h. -// AMPEL_CONFIG_VERSION should also be updated if the configuration structure is modified. -// The structure of the Ampel configuration has been modified 11 times, so it's called "a11" for now. -# define AMPEL_CONFIG_VERSION "a11" - -/** - * SERVICES - */ - -// Define the default for corresponding services. They can be enabled/disabled later in the web-config. -# define AMPEL_WIFI true // Should ESP connect to WiFi? Web configuration will not be available when set to false. Use "wifi 1" command to set to true. -# define AMPEL_MQTT true // Should data be sent over MQTT? (AMPEL_WIFI should be enabled too) -# define AMPEL_CSV true // Should data be logged as CSV, on the ESP flash memory? -# define AMPEL_LORAWAN false // Should data be sent over LoRaWAN? (Requires ESP32 + LoRa modem, and "MCCI LoRaWAN LMIC library") - -/** - * WIFI - */ - -// SSID and PASSWORD need to be defined, but can be empty. -# define WIFI_SSID "" -# define WIFI_PASSWORD "" -// How long should the Ampel try to connect to WIFI_SSID? -# define WIFI_TIMEOUT 30 // [s] -// If the Ampel cannot connect to WIFI_SSID, it will start an Access Point for ACCESS_POINT_TIMEOUT seconds. -// If someone connects to this Access Point, the Ampel will stay in this mode until everybody logs out. -// If nobody connects to the Access Point before ACCESS_POINT_TIMEOUT seconds, the Ampel will try to connect WIFI_SSID again. -# define ACCESS_POINT_TIMEOUT 60 // [s] - -/** - * Sensor - */ - -// How often should measurement be performed, and displayed? -//WARNING: On some sensors, measurements become very unreliable when timestep is set to 2s. -//NOTE: 10s or longer should be fine in order to get reliable results. -//NOTE: SCD30 timer does not seem to be very precise. Time variations may occur. -# define MEASUREMENT_TIMESTEP 60 // [s] Value between 2 and 1800 (range for SCD30 sensor) - -// How often should measurements be appended to CSV ? -// Set to 0 if you want to send values after each measurement -// WARNING: Writing too often might damage the ESP memory -# define CSV_INTERVAL 300 // [s] - -// Residual heat from CO2 sensor seems to be high enough to change the temperature reading. How much should it be offset? -// NOTE: Sign isn't relevant. The returned temperature will always be shifted down. -# define TEMPERATURE_OFFSET -3 // [K] - -// Altitude above sea level -// Used for CO2 calibration -// here: Stuttgart, Schellingstr. 24. (Source: Google Earth) -# define ALTITUDE_ABOVE_SEA_LEVEL 260 // [m] - -// The reference CO2 concentration has to be within the range 400 ppm ≤ cref(CO2) ≤ 2000 ppm. -// Used for CO2 calibration -// here : measured concentration in Stuttgart -# define ATMOSPHERIC_CO2_CONCENTRATION 425 // [ppm] - -// Should the sensor try to calibrate itself? -// Sensirion recommends 7 days of continuous readings with at least 1 hour a day of 'fresh air' for self-calibration to complete. -# define AUTO_CALIBRATE_SENSOR false // [true / false] - -/** - * LEDs - */ - -// LED brightness, which can vary between min and max brightness ("LED breathing") -// MAX_BRIGHTNESS must be defined, and should be between 0 and 255. -# define MAX_BRIGHTNESS 255 -// MIN_BRIGHTNESS, if defined, should be between 0 and MAX_BRIGHTNESS - 1 -// If MIN_BRIGHTNESS is set to MAX_BRIGHTNESS, breathing is disabled. -# define MIN_BRIGHTNESS 60 -// How many LEDs in the ring? 12 and 16 are currently supported. -# define LED_COUNT 12 - -/** - * MQTT - */ - -/* - * If AMPEL_MQTT is enabled, co2ampel will publish data every MQTT_SENDING_INTERVAL seconds. - * An MQTT subscriber can then get the data from the corresponding broker, either encrypted or unencrypted: - * - * ❯ mosquitto_sub -h 'test.mosquitto.org' -p 8883 -t 'CO2sensors/#' --cafile mosquitto.org.crt -v - * CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:14:37+01", "co2":571, "temp":18.9, "rh":50.9} - * CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:14:48+01", "co2":573, "temp":18.9, "rh":50.2} - * ... - * - * ❯ mosquitto_sub -h 'test.mosquitto.org' -t 'CO2sensors/#' -v - * CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:15:09+01", "co2":568, "temp":18.9, "rh":50.1} - * CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:15:20+01", "co2":572, "temp":18.9, "rh":50.3} - * ... - */ - -/* - * Allow sensor to be configured over MQTT? Very useful for debugging. For example: - * mosquitto_pub -h 'test.mosquitto.org' -t 'CO2sensors/ESPe08dc9/control' -m 'timer 30' - * mosquitto_pub -h 'test.mosquitto.org' -t 'CO2sensors/ESPe08dc9/control' -m 'calibrate' - * mosquitto_pub -h 'test.mosquitto.org' -t 'CO2sensors/ESPe08dc9/control' -m 'reset' - */ -# define ALLOW_MQTT_COMMANDS false - -// How often should measurements be sent to MQTT server? -// Set to 0 if you want to send values after each measurement -// # define MQTT_SENDING_INTERVAL MEASUREMENT_TIMESTEP * 5 // [s] -# define MQTT_SENDING_INTERVAL 300 // [s] -# define MQTT_SERVER "test.mosquitto.org" // MQTT server URL or IP address -# define MQTT_PORT 8883 -# define MQTT_ENCRYPTED true // Set to false for unencrypted MQTT (e.g. with port 1883). -# define MQTT_USER "" -# define MQTT_PASSWORD "" -# define MQTT_TOPIC_PREFIX "CO2sensors/" // ESPxxxxxx will be added to the prefix, so complete topic will be "CO2sensors/ESPxxxxxx". The prefix should probably end with '/' - -/** - * LoRaWAN - */ - -// 1) Requires "MCCI LoRaWAN LMIC library", which will be automatically used with PlatformIO but should be added in "Arduino IDE". -// 2) Region and transceiver type should be specified in: -// * Arduino/libraries/MCCI_LoRaWAN_LMIC_library/project_config/lmic_project_config.h for Arduino IDE -// * platformio.ini for PlatformIO -// See https://github.com/mcci-catena/arduino-lmic#configuration for more information -// 3) It has been tested with "TTGO ESP32 SX1276 LoRa 868" and will only work with an ESP32 + LoRa modem -// 4) In order to use LoRaWAN, a gateway should be close to the co2ampel, and an account, an application and a device should be registered, -// e.g. on https://www.thethingsindustries.com/docs/integrations/ -// with "Europe 863-870 MHz (SF9 for RX2 - recommended)", "MAC v1.0.3" -// 5) The corresponding keys should be defined in LORAWAN_DEVICE_EUI, LORAWAN_APPLICATION_EUI and LORAWAN_APPLICATION_KEY -// How often should measurements be sent over LoRaWAN? -# define LORAWAN_SENDING_INTERVAL 300 // [s] This value should not be too low. See https://www.thethingsnetwork.org/docs/lorawan/duty-cycle.html#maximum-duty-cycle - -// WARNING: If AMPEL_LORAWAN is true, you need to modify the 3 following constants -// They are written as hexadecimal strings, and will be parsed in the correct order. - -// This EUI must be in big-endian format, so most-significant-byte first. -// You can copy the string from TheThingsNetwork as-is, without reversing the bytes. -// For TheThingsNetwork issued EUIs the string should start with "70B3D5..." -# define LORAWAN_DEVICE_EUI "70B3D57ED004CB17" -// This should also be in big-endian format, and can be copied as is from TheThingsNetwork. -# define LORAWAN_APPLICATION_EUI "0102030405060708" -// This should also be in big-endian format, and can be copied as is from TheThingsNetwork. -# define LORAWAN_APPLICATION_KEY "9D06308E20B974919DA6404E063BE01D" - -/** - * NTP - */ - -# define NTP_SERVER "pool.ntp.org" -# define UTC_OFFSET 1 // [h] +1 for Paris/Berlin, -5 for NYC -# define DAYLIGHT_SAVING_TIME false // true in summer, false in winter - -#endif diff --git a/ampel-firmware/csv_writer.cpp b/ampel-firmware/csv_writer.cpp deleted file mode 100644 index d7189477defdb5bc1855960280c749535f3bfafd..0000000000000000000000000000000000000000 --- a/ampel-firmware/csv_writer.cpp +++ /dev/null @@ -1,202 +0,0 @@ -#include "csv_writer.h" - -#include "web_config.h" -#include "ntp.h" -#include "led_effects.h" -#include "sensor_console.h" - -namespace csv_writer { - unsigned long last_written_at = 0; - char last_successful_write[23]; - -#if defined(ESP8266) - /** - * SPECIFIC FUNCTIONS FOR LITTLEFS - */ - FSInfo fs_info; - - bool mountFS() { - return LittleFS.begin(); // format if needed. - } - - void updateFsInfo() { - FS_LIB.info(fs_info); - } - - int getTotalSpace() { - return fs_info.totalBytes; - } - - int getUsedSpace() { - return fs_info.usedBytes; - } - - void showFilesystemContent() { - Dir dir = FS_LIB.openDir("/"); - while (dir.next()) { - Serial.print(" "); - Serial.print(dir.fileName()); - Serial.print(" - "); - if (dir.fileSize()) { - File f = dir.openFile("r"); - Serial.println(f.size()); - f.close(); - } else { - Serial.println("0"); - } - } - } -#elif defined(ESP32) - /** - * SPECIFIC FUNCTIONS FOR SPIFFS - */ - bool mountFS() { - return SPIFFS.begin(true); // format if needed. - } - - void updateFsInfo() { - // Nothing to do. - } - - int getTotalSpace() { - return SPIFFS.totalBytes(); - } - - int getUsedSpace() { - return SPIFFS.usedBytes(); - } - - void showFilesystemContent() { - File root = SPIFFS.open("/"); - File file = root.openNextFile(); - while (file) { - Serial.print(" "); - Serial.print(file.name()); - Serial.print(" - "); - Serial.println(file.size()); - file = root.openNextFile(); - } - } -#endif - - char filename[20]; // e.g. "/ESPxxxxxx.csv\0" - - int getAvailableSpace() { - return getTotalSpace() - getUsedSpace(); - } - - void initialize(const char *basename) { - snprintf(filename, sizeof(filename), "/%.14s.csv", basename); - - Serial.println(); - Serial.print(F("Initializing FS...")); - if (mountFS()) { - Serial.println(F("done.")); - } else { - Serial.println(F("fail.")); - return; - } - - updateFsInfo(); - - Serial.println(F("File system info:")); - - Serial.print(F(" Total space : ")); - Serial.print(getTotalSpace() / 1024); - Serial.println("kB"); - - Serial.print(F(" Used space : ")); - Serial.print(getUsedSpace() / 1024); - Serial.println("kB"); - - Serial.print(F(" Available space: ")); - Serial.print(getAvailableSpace() / 1024); - Serial.println("kB"); - Serial.println(); - - // Open dir folder - Serial.println(F("Filesystem content:")); - showFilesystemContent(); - Serial.println(); - - sensor_console::defineIntCommand("csv", setCSVinterval, F("60 (Sets CSV writing interval, in s)")); - sensor_console::defineCommand("format_filesystem", formatFilesystem, F("(Deletes the whole filesystem)")); - sensor_console::defineCommand("show_csv", showCSVContent, F("(Displays the complete CSV file on Serial)")); - } - - File openOrCreate() { - File csv_file; - if (FS_LIB.exists(filename)) { - csv_file = FS_LIB.open(filename, "a+"); - } else { - csv_file = FS_LIB.open(filename, "w"); - csv_file.print(F("Sensor time;CO2 concentration;Temperature;Humidity\r\n")); - csv_file.print(F("YYYY-MM-DD HH:MM:SS+ZZ;ppm;degC;%\r\n")); - } - return csv_file; - } - - void log(const char *timestamp, const int16_t &co2, const float &temperature, const float &humidity) { - led_effects::onBoardLEDOn(); - File csv_file = openOrCreate(); - char csv_line[42]; - snprintf(csv_line, sizeof(csv_line), "%s;%d;%.1f;%.1f\r\n", timestamp, co2, temperature, humidity); - if (csv_file) { - size_t written_bytes = csv_file.print(csv_line); - csv_file.close(); - if (written_bytes == 0) { - Serial.println(F("Nothing written. Disk full?")); - } else { - Serial.print(F("CSV - Wrote : ")); - Serial.print(csv_line); - ntp::getLocalTime(last_successful_write); - } - updateFsInfo(); - delay(50); - } else { - //NOTE: Can it ever happen that outfile is false? - Serial.println(F("Problem on create file!")); - } - led_effects::onBoardLEDOff(); - } - - void logIfTimeHasCome(const char *timeStamp, const int16_t &co2, const float &temperature, const float &humidity) { - unsigned long now = seconds(); - if (now - last_written_at > config::csv_interval) { - last_written_at = now; - log(timeStamp, co2, temperature, humidity); - } - } - - /***************************************************************** - * Callbacks for sensor commands * - *****************************************************************/ - void setCSVinterval(int32_t csv_interval) { - config::csv_interval = csv_interval; - Serial.print(F("Setting CSV Interval to : ")); - Serial.print(config::csv_interval); - Serial.println("s."); - led_effects::showKITTWheel(color::green, 1); - } - - void showCSVContent() { - //TODO: Now that ampel_name can be set, should show the content of every csv - Serial.print(F("### ")); - Serial.print(filename); - Serial.println(F(" ###")); - File csv_file; - if (FS_LIB.exists(filename)) { - csv_file = FS_LIB.open(filename, "r"); - while (csv_file.available()) { - Serial.write(csv_file.read()); - } - csv_file.close(); - } - Serial.println(F("######################")); - } - - void formatFilesystem() { - FS_LIB.format(); - led_effects::showKITTWheel(color::blue, 2); - } -} diff --git a/ampel-firmware/csv_writer.h b/ampel-firmware/csv_writer.h deleted file mode 100644 index 25963cdfd5afa3ed322a3835ffeed96a55362f2d..0000000000000000000000000000000000000000 --- a/ampel-firmware/csv_writer.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef CSV_WRITER_H_ -#define CSV_WRITER_H_ - -#if defined(ESP8266) -# include -# define FS_LIB LittleFS -#elif defined(ESP32) -# include -# define FS_LIB SPIFFS -#else -# error Board should be either ESP8266 or ESP832 -#endif -//NOTE: LittleFS will be available for Arduino esp32 core v2 - -namespace csv_writer { - extern char last_successful_write[]; - void initialize(const char *basename); - void logIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temperature, const float &humidity); - int getAvailableSpace(); - extern char filename[]; - - void setCSVinterval(int32_t csv_interval); - void showCSVContent(); - void formatFilesystem(); -} - -#endif diff --git a/ampel-firmware/led_effects.cpp b/ampel-firmware/led_effects.cpp deleted file mode 100644 index d7672a56fb98b31988f9708973e7751f2b0a5dce..0000000000000000000000000000000000000000 --- a/ampel-firmware/led_effects.cpp +++ /dev/null @@ -1,288 +0,0 @@ -#include "led_effects.h" - -#include "web_config.h" -#include "sensor_console.h" - -// Adafruit NeoPixel (Arduino library for controlling single-wire-based LED pixels and strip) -// https://github.com/adafruit/Adafruit_NeoPixel -// Documentation : http://adafruit.github.io/Adafruit_NeoPixel/html/class_adafruit___neo_pixel.html -#include "src/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.h" - -/***************************************************************** - * Configuration * - *****************************************************************/ -namespace config { - const int kitt_tail = 3; // How many dimmer LEDs follow in K.I.T.T. wheel - const uint16_t poor_air_quality_ppm = 1600; // Above this threshold, LED breathing effect is faster. - bool display_led = true; // Will be set to false during "night mode". - //NOTE: One value has been prepended, to make calculations easier and avoid out of bounds index. - uint16_t co2_ticks[16 + 1] = { 0, 500, 600, 700, 800, 900, 1000 }; // rest will be filled later - // For a given LED, which color should be displayed? First LED will be pure green (hue angle 120°), - // LEDs >= 1600ppm will be pure red (hue angle 0°), LEDs in-between will be yellowish. - uint16_t led_hues[16]; -} - -#if defined(ESP8266) -// NeoPixels on GPIO05, aka D1 on ESP8266. -const int NEOPIXELS_PIN = 5; -#elif defined(ESP32) -// NeoPixels on GPIO23 on ESP32. To avoid conflict with LoRa_SCK on TTGO. -const int NEOPIXELS_PIN = 23; -#endif - -// config::led_count is not yet known, will be set later. -Adafruit_NeoPixel pixels(0, NEOPIXELS_PIN, NEO_GRB + NEO_KHZ800); - -namespace led_effects { - //On-board LED on D4, aka GPIO02 - const int ONBOARD_LED_PIN = 2; - - void setupOnBoardLED() { - pinMode(ONBOARD_LED_PIN, OUTPUT); - } - - void onBoardLEDOff() { - //NOTE: OFF is LOW on ESP32 and HIGH on ESP8266 :-/ -#ifdef ESP8266 - digitalWrite(ONBOARD_LED_PIN, HIGH); -#else - digitalWrite(ONBOARD_LED_PIN, LOW); -#endif - } - - void onBoardLEDOn() { -#ifdef ESP8266 - digitalWrite(ONBOARD_LED_PIN, LOW); -#else - digitalWrite(ONBOARD_LED_PIN, HIGH); -#endif - } - - void LEDsOff() { - pixels.clear(); - pixels.show(); - onBoardLEDOff(); - } - - void showColor(int32_t color) { - config::display_led = false; // In order to avoid overwriting the desired color next time CO2 is displayed - pixels.setBrightness(255); - pixels.fill(color); - pixels.show(); - } - - void setupRing() { - Serial.print(F("Ring : ")); - Serial.print(config::led_count); - Serial.println(F(" LEDs.")); - - pixels.updateLength(config::led_count); - - if (config::led_count == 12) { - config::co2_ticks[7] = 1200; - config::co2_ticks[8] = 1400; - config::co2_ticks[9] = 1600; - config::co2_ticks[10] = 1800; - config::co2_ticks[11] = 2000; - config::co2_ticks[12] = 2200; - - config::led_hues[0] = 21845U; - config::led_hues[1] = 19114U; - config::led_hues[2] = 16383U; - config::led_hues[3] = 13653U; - config::led_hues[4] = 10922U; - config::led_hues[5] = 8191U; - config::led_hues[6] = 5461U; - config::led_hues[7] = 2730U; - config::led_hues[8] = 0; - config::led_hues[9] = 0; - config::led_hues[10] = 0; - config::led_hues[11] = 0; - } else if (config::led_count == 16) { - config::co2_ticks[7] = 1100; - config::co2_ticks[8] = 1200; - config::co2_ticks[9] = 1300; - config::co2_ticks[10] = 1400; - config::co2_ticks[11] = 1500; - config::co2_ticks[12] = 1600; - config::co2_ticks[13] = 1700; - config::co2_ticks[14] = 1800; - config::co2_ticks[15] = 2000; - config::co2_ticks[16] = 2200; - - config::led_hues[0] = 21845U; - config::led_hues[1] = 19859U; - config::led_hues[2] = 17873U; - config::led_hues[3] = 15887U; - config::led_hues[4] = 13901U; - config::led_hues[5] = 11915U; - config::led_hues[6] = 9929U; - config::led_hues[7] = 7943U; - config::led_hues[8] = 5957U; - config::led_hues[9] = 3971U; - config::led_hues[10] = 1985U; - config::led_hues[11] = 0; - config::led_hues[12] = 0; - config::led_hues[13] = 0; - config::led_hues[14] = 0; - config::led_hues[15] = 0; - } else { - // "Only 12 and 16 LEDs rings are currently supported." - config::display_led = false; - } - pixels.begin(); - pixels.setBrightness(config::max_brightness); - LEDsOff(); - sensor_console::defineIntCommand("led", turnLEDsOnOff, F("0/1 (Turns LEDs on/off)")); - sensor_console::defineIntCommand("color", showColor, F("0xFF0015 (Shows color, specified as RGB, for debugging)")); - } - - void toggleNightMode() { - turnLEDsOnOff(!config::display_led); - } - - void turnLEDsOnOff(int32_t display_led) { - //TODO: Could use strategy pattern with 2 different Effects classes. - config::display_led = display_led; - if (config::display_led) { - Serial.println(F("LEDs are on!")); - } else { - Serial.println(F("Night mode!")); - LEDsOff(); - } - } - - //NOTE: basically one iteration of KITT wheel - void showWaitingLED(uint32_t color) { - using namespace config; - delay(80); - if (!display_led) { - return; - } - static uint16_t kitt_offset = 0; - pixels.clear(); - for (int j = kitt_tail; j >= 0; j--) { - int ledNumber = abs((kitt_offset - j + led_count) % (2 * led_count) - led_count) % led_count; // Triangular function - pixels.setPixelColor(ledNumber, color * pixels.gamma8(255 - j * 76) / 255); - } - pixels.show(); - kitt_offset++; - } - - // Start K.I.T.T. led effect. Red color as default. - // Simulate a moving LED with tail. First LED starts at 0, and moves along a triangular function. The tail follows, with decreasing brightness. - // Takes approximately 1s for each direction. - void showKITTWheel(uint32_t color, uint16_t duration_s) { - pixels.setBrightness(config::max_brightness); - for (int i = 0; i < duration_s * config::led_count; ++i) { - showWaitingLED(color); - } - } - - /* - * For a given CO2 level and ledId, which brightness should be displayed? 0 for off, 255 for on. Something in-between for partial LED. - * For example, for 1500ppm, every LED between 0 and 7 (500 -> 1400ppm) should be on, LED at 8 (1600ppm) should be half-on. - */ - uint8_t getLedBrightness(uint16_t co2, int ledId) { - if (co2 >= config::co2_ticks[ledId + 1]) { - return 255; - } else { - if (2 * co2 >= config::co2_ticks[ledId] + config::co2_ticks[ledId + 1]) { - // Show partial LED if co2 more than halfway between ticks. - return 27; // Brightness isn't linear, so 27 / 255 looks much brighter than 10% - } else { - // LED off because co2 below previous tick - return 0; - } - } - } - - /** - * If enabled, slowly varies the brightness between MAX_BRIGHTNESS & MIN_BRIGHTNESS. - */ - void breathe(int16_t co2) { - static uint8_t breathing_offset = 0; - uint8_t brightness_amplitude = config::max_brightness - config::min_brightness; - uint16_t brightness = config::min_brightness + pixels.sine8(breathing_offset) * brightness_amplitude / 255; - pixels.setBrightness(brightness); - pixels.show(); - breathing_offset += co2 > config::poor_air_quality_ppm ? 6 : 3; // breathing speed. +3 looks like slow human breathing. - } - - /** - * Fills the whole ring with green, yellow, orange or black, depending on co2 input and CO2_TICKS. - */ - void displayCO2color(uint16_t co2) { - if (!config::display_led) { - return; - } - pixels.setBrightness(config::max_brightness); - for (int ledId = 0; ledId < config::led_count; ++ledId) { - uint8_t brightness = getLedBrightness(co2, ledId); - pixels.setPixelColor(ledId, pixels.ColorHSV(config::led_hues[ledId], 255, brightness)); - } - pixels.show(); - if (config::max_brightness > config::min_brightness) { - breathe(co2); - } - } - - void showRainbowWheel(uint16_t duration_ms) { - if (!config::display_led) { - return; - } - static uint16_t wheel_offset = 0; - static uint16_t sine_offset = 0; - unsigned long t0 = millis(); - pixels.setBrightness(config::max_brightness); - while (millis() - t0 < duration_ms) { - for (int i = 0; i < config::led_count; i++) { - pixels.setPixelColor(i, pixels.ColorHSV(i * 65535 / config::led_count + wheel_offset)); - wheel_offset += (pixels.sine8(sine_offset++ / 50) - 127) / 2; - } - pixels.show(); - delay(10); - } - } - - void alert(uint32_t color) { - if (!config::display_led) { - onBoardLEDOn(); - delay(500); - onBoardLEDOff(); - delay(500); - return; - } - for (int i = 0; i < 10; i++) { - pixels.setBrightness(static_cast(config::max_brightness * (1 - i * 0.1))); - delay(50); - pixels.fill(color); - pixels.show(); - } - } - - /** - * Displays a complete blue circle, and starts removing LEDs one by one. - * Does nothing in night mode and returns false then. Returns true if - * the countdown has finished. Can be used for calibration, e.g. when countdown is 0. - * NOTE: This function is blocking and returns only after the button has - * been released or after every LED has been turned off. - */ - bool countdownToZero() { - if (!config::display_led) { - Serial.println(F("Night mode. Not doing anything.")); - delay(1000); // Wait for a while, to avoid coming back to this function too many times when button is pressed. - return false; - } - pixels.fill(color::blue); - pixels.show(); - int countdown; - for (countdown = config::led_count; countdown >= 0 && !digitalRead(0); countdown--) { - pixels.setPixelColor(countdown, color::black); - pixels.show(); - Serial.println(countdown); - delay(500); - } - return countdown < 0; - } -} diff --git a/ampel-firmware/led_effects.h b/ampel-firmware/led_effects.h deleted file mode 100644 index d37cb5c3bd569ab1a19d273df6c2bbbb5ae5fe37..0000000000000000000000000000000000000000 --- a/ampel-firmware/led_effects.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef LED_EFFECTS_H_INCLUDED -#define LED_EFFECTS_H_INCLUDED - -#include // For uint32_t - -namespace color { - const uint32_t red = 0xFF0000; - const uint32_t green = 0x00FF00; - const uint32_t blue = 0x0000FF; - const uint32_t black = 0x000000; - const uint32_t magenta = 0xFF00FF; -} - -namespace led_effects { - void setupOnBoardLED(); - void onBoardLEDOff(); - void onBoardLEDOn(); - void toggleNightMode(); - void turnLEDsOnOff(int32_t); - void LEDsOff(); - - void setupRing(); - void alert(uint32_t color); - bool countdownToZero(); - void showWaitingLED(uint32_t color); - void showKITTWheel(uint32_t color, uint16_t duration_s = 2); - void showRainbowWheel(uint16_t duration_ms = 1000); - void displayCO2color(uint16_t co2); -} -#endif diff --git a/ampel-firmware/lorawan.cpp b/ampel-firmware/lorawan.cpp deleted file mode 100644 index ad4e22ee049f55eba9af65c44870b80a86ae46ef..0000000000000000000000000000000000000000 --- a/ampel-firmware/lorawan.cpp +++ /dev/null @@ -1,279 +0,0 @@ -#include "lorawan.h" - -#if defined(ESP32) - -#include "web_config.h" -#include "led_effects.h" -#include "sensor_console.h" -#include "util.h" -#include "ntp.h" - -// Requires "MCCI LoRaWAN LMIC library", which will be automatically used with PlatformIO but should be added in "Arduino IDE" -// Tested successfully with v3.2.0 and connected to a thethingsnetwork.org app. -#include -#include -#include -#include - -namespace config { -#if defined(CFG_eu868) - const char *lorawan_frequency_plan = "Europe 868"; -#elif defined(CFG_us915) - const char *lorawan_frequency_plan = "US 915"; -#elif defined(CFG_au915) - const char *lorawan_frequency_plan = "Australia 915"; -#elif defined(CFG_as923) - const char *lorawan_frequency_plan = "Asia 923"; -#elif defined(CFG_kr920) - const char *lorawan_frequency_plan = "Korea 920"; -#elif defined(CFG_in866) - const char *lorawan_frequency_plan = "India 866"; -#else -# error "Region should be specified" -#endif -} - -// Payloads will be automatically sent via MQTT by TheThingsNetwork, and can be seen with: -// mosquitto_sub -h eu.thethings.network -t '+/devices/+/up' -u 'APPLICATION-NAME' -P 'ttn-account-v2.4xxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx' -v -// or encrypted: -// mosquitto_sub -h eu.thethings.network -t '+/devices/+/up' -u 'APPLICATION-NAME' -P 'ttn-account-v2.4xxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx' -v --cafile mqtt-ca.pem -p 8883 -// -> -// co2ampel-test/devices/esp3a7c94/up {"app_id":"co2ampel-test","dev_id":"esp3a7c94","hardware_serial":"00xxxxxxxx","port":1,"counter":5,"payload_raw":"TJd7","payload_fields":{"co2":760,"rh":61.5,"temp":20.2},"metadata":{"time":"2020-12-23T23:00:51.44020438Z","frequency":867.5,"modulation":"LORA","data_rate":"SF7BW125","airtime":51456000,"coding_rate":"4/5","gateways":[{"gtw_id":"eui-xxxxxxxxxxxxxxxxxx","timestamp":1765406908,"time":"2020-12-23T23:00:51.402519Z","channel":5,"rssi":-64,"snr":7.5,"rf_chain":0,"latitude":22.7,"longitude":114.24,"altitude":450}]}} -// More info : https://www.thethingsnetwork.org/docs/applications/mqtt/quick-start.html - -namespace lorawan { - bool waiting_for_confirmation = false; - bool connected = false; - char last_transmission[23] = ""; - - void initialize() { - Serial.print(F("Starting LoRaWAN. Frequency plan : ")); - Serial.print(config::lorawan_frequency_plan); - Serial.println(F(" MHz.")); - - // More info about pin mapping : https://github.com/mcci-catena/arduino-lmic#pin-mapping - // Has been tested successfully with ESP32 TTGO LoRa32 V1, and might work with other ESP32+LoRa boards. - const lmic_pinmap *pPinMap = Arduino_LMIC::GetPinmap_ThisBoard(); - // LMIC init. - os_init_ex(pPinMap); - // Reset the MAC state. Session and pending data transfers will be discarded. - LMIC_reset(); - // Join, but don't send anything yet. - LMIC_startJoining(); - sensor_console::defineIntCommand("lora", setLoRaInterval, F("300 (Sets LoRaWAN sending interval, in s)")); - } - - // Checks if OTAA is connected, or if payload should be sent. - // NOTE: while a transaction is in process (i.e. until the TXcomplete event has been received), no blocking code (e.g. delay loops etc.) are allowed, otherwise the LMIC/OS code might miss the event. - // If this rule is not followed, a typical symptom is that the first send is ok and all following ones end with the 'TX not complete' failure. - void process() { - os_runloop_once(); - } - - void printHex2(unsigned v) { - v &= 0xff; - if (v < 16) - Serial.print('0'); - Serial.print(v, HEX); - } - - void onEvent(ev_t ev) { - char current_time[23]; - ntp::getLocalTime(current_time); - Serial.print(F("LoRa - ")); - Serial.print(current_time); - Serial.print(F(" - ")); - switch (ev) { - case EV_JOINING: - Serial.println(F("EV_JOINING")); - break; - case EV_JOINED: - waiting_for_confirmation = false; - connected = true; - led_effects::onBoardLEDOff(); - Serial.println(F("EV_JOINED")); - { - u4_t netid = 0; - devaddr_t devaddr = 0; - u1_t nwkKey[16]; - u1_t artKey[16]; - LMIC_getSessionKeys(&netid, &devaddr, nwkKey, artKey); - //NOTE: Saving session to EEPROM seems like a good idea at first, but unfortunately: too much info is needed, and a counter would need to be save every single time data is sent. - Serial.print(F(" netid: ")); - Serial.println(netid, DEC); - Serial.print(F(" devaddr: ")); - Serial.println(devaddr, HEX); - Serial.print(F(" AppSKey: ")); - for (size_t i = 0; i < sizeof(artKey); ++i) { - if (i != 0) - Serial.print("-"); - printHex2(artKey[i]); - } - Serial.println(); - Serial.print(F(" NwkSKey: ")); - for (size_t i = 0; i < sizeof(nwkKey); ++i) { - if (i != 0) - Serial.print("-"); - printHex2(nwkKey[i]); - } - Serial.println(); - } - Serial.println(F("Other services may resume, and will not be frozen anymore.")); - // Disable link check validation (automatically enabled during join) - LMIC_setLinkCheckMode(0); - break; - case EV_JOIN_FAILED: - Serial.println(F("EV_JOIN_FAILED")); - break; - case EV_REJOIN_FAILED: - Serial.println(F("EV_REJOIN_FAILED")); - break; - case EV_TXCOMPLETE: - ntp::getLocalTime(last_transmission); - Serial.println(F("EV_TXCOMPLETE")); - break; - case EV_TXSTART: - waiting_for_confirmation = !connected; - Serial.println(F("EV_TXSTART")); - break; - case EV_TXCANCELED: - waiting_for_confirmation = false; - led_effects::onBoardLEDOff(); - Serial.println(F("EV_TXCANCELED")); - break; - case EV_JOIN_TXCOMPLETE: - waiting_for_confirmation = false; - led_effects::onBoardLEDOff(); - Serial.println(F("EV_JOIN_TXCOMPLETE: no JoinAccept.")); - Serial.println(F("Other services may resume.")); - break; - default: - Serial.print(F("LoRa event: ")); - Serial.println((unsigned) ev); - break; - } - if (waiting_for_confirmation) { - led_effects::onBoardLEDOn(); - Serial.println(F("LoRa - waiting for OTAA confirmation. Freezing every other service!")); - } - } - - void preparePayload(int16_t co2, float temperature, float humidity) { - // Check if there is not a current TX/RX job running - if (LMIC.opmode & OP_TXRXPEND) { - Serial.println(F("OP_TXRXPEND, not sending")); - } else { - uint8_t buff[3]; - // Mapping CO2 from 0ppm to 5100ppm to [0, 255], with 20ppm increments. - buff[0] = (util::min(util::max(co2, 0), 5100) + 10) / 20; - // Mapping temperatures from [-10°C, 41°C] to [0, 255], with 0.2°C increment - buff[1] = static_cast((util::min(util::max(temperature, -10), 41) + 10.1f) * 5); - // Mapping humidity from [0%, 100%] to [0, 200], with 0.5°C increment (0.4°C would also be possible) - buff[2] = static_cast(util::min(util::max(humidity, 0) + 0.25f, 100) * 2); - - Serial.print(F("LoRa - Payload : '")); - printHex2(buff[0]); - Serial.print(" "); - printHex2(buff[1]); - Serial.print(" "); - printHex2(buff[2]); - Serial.print(F("', ")); - Serial.print(buff[0] * 20); - Serial.print(F(" ppm, ")); - Serial.print(buff[1] * 0.2 - 10); - Serial.print(F(" °C, ")); - Serial.print(buff[2] * 0.5); - Serial.println(F(" %.")); - - // Prepare upstream data transmission at the next possible time. - LMIC_setTxData2(1, buff, sizeof(buff), 0); - - //NOTE: To decode in TheThingsNetwork: - // function decodeUplink(input) { - // return { - // data: { - // co2: input.bytes[0] * 20, - // temp: input.bytes[1] / 5.0 - 10, - // rh: input.bytes[2] / 2.0 - // }, - // warnings: [], - // errors: [] - // }; - // } - } - } - - void preparePayloadIfTimeHasCome(const int16_t &co2, const float &temperature, const float &humidity) { - static unsigned long last_sent_at = 0; - unsigned long now = seconds(); - if (connected && (now - last_sent_at > config::lorawan_sending_interval)) { - last_sent_at = now; - preparePayload(co2, temperature, humidity); - } - } - - /***************************************************************** - * Callbacks for sensor commands * - *****************************************************************/ - void setLoRaInterval(int32_t sending_interval) { - config::lorawan_sending_interval = sending_interval; - Serial.print(F("Setting LoRa sending interval to : ")); - Serial.print(config::lorawan_sending_interval); - Serial.println("s."); - led_effects::showKITTWheel(color::green, 1); - } -} - -void onEvent(ev_t ev) { - lorawan::onEvent(ev); -} - -// 'A' -> 10, 'F' -> 15, 'f' -> 15, 'z' -> -1 -int8_t hexCharToInt(char c) { - int8_t v = -1; - if ((c >= '0') && (c <= '9')) { - v = (c - '0'); - } else if ((c >= 'A') && (c <= 'F')) { - v = (c - 'A' + 10); - } else if ((c >= 'a') && (c <= 'f')) { - v = (c - 'a' + 10); - } - return v; -} - -/** - * Parses hex string and saves the corresponding bytes in buf. - * msb is true for most-significant-byte, false for least-significant-byte. - * - * "112233" will be loaded into {0x11, 0x22, 0x33} in MSB, {0x33, 0x22, 0x11} in LSB. - */ -void hexStringToByteArray(uint8_t *buf, const char *hex, uint max_n, bool msb) { - int n = util::min(strlen(hex) / 2, max_n); - - for (int i = 0; i < n; i++) { - int j; - if (msb) { - j = i; - } else { - j = n - 1 - i; - } - uint8_t r = hexCharToInt(hex[j * 2]) * 16 + hexCharToInt(hex[j * 2 + 1]); - buf[i] = r; - } -} - -// Load config into LMIC byte arrays. - -void os_getArtEui(u1_t *buf) { - hexStringToByteArray(buf, config::lorawan_app_eui, 8, false); -} - -void os_getDevEui(u1_t *buf) { - hexStringToByteArray(buf, config::lorawan_device_eui, 8, false); -} - -void os_getDevKey(u1_t *buf) { - hexStringToByteArray(buf, config::lorawan_app_key, 16, true); -} - -#endif diff --git a/ampel-firmware/lorawan.h b/ampel-firmware/lorawan.h deleted file mode 100644 index e89e8c3c474ed678921f9d817a3acb11f18636a0..0000000000000000000000000000000000000000 --- a/ampel-firmware/lorawan.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef AMPEL_LORAWAN_H_ -#define AMPEL_LORAWAN_H_ - -# if defined(ESP32) - -#include // For uint32_t & uint16_t - -namespace config { - extern const char *lorawan_frequency_plan; // e.g. "Europe 868" -} - -namespace lorawan { - extern bool waiting_for_confirmation; - extern bool connected; - extern char last_transmission[]; - void initialize(); - void process(); - void preparePayloadIfTimeHasCome(const int16_t &co2, const float &temp, const float &hum); - - void setLoRaInterval(int32_t sending_interval); -} - -# endif -#endif diff --git a/ampel-firmware/mqtt.cpp b/ampel-firmware/mqtt.cpp deleted file mode 100644 index ddb10848f6a13d8638bdffaa8c4a2c8c2e95accb..0000000000000000000000000000000000000000 --- a/ampel-firmware/mqtt.cpp +++ /dev/null @@ -1,198 +0,0 @@ -#include "mqtt.h" - -#include "web_config.h" -#include "led_effects.h" -#include "sensor_console.h" -#include "wifi_util.h" -#include "ntp.h" -#include "src/lib/PubSubClient/src/PubSubClient.h" - -#if defined(ESP8266) -# include -#elif defined(ESP32) -# include -#endif - -namespace config { - // Values should be defined in config.h or over webconfig - //INFO: Listen to every CO2 sensor which is connected to the server: - // mosquitto_sub -h MQTT_SERVER -t 'CO2sensors/#' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -v - const unsigned long wait_after_fail = 900; // [s] Wait 15 minutes after an MQTT connection fail, before trying again. -} - -#if defined(ESP32) -# include -#endif - -WiFiClient *espClient; - -PubSubClient mqttClient; - -namespace mqtt { - unsigned long last_sent_at = 0; - unsigned long last_failed_at = 0; - bool connected = false; - - char publish_topic[42]; // "MQTT_TOPIC_PREFIX/ESPxxxxxx\0", e.g. "CO2sensors/ESPxxxxxx\0" - const char *json_sensor_format; - char last_successful_publish[23] = ""; - - void initialize(const char *sensorId) { - json_sensor_format = PSTR("{\"time\":\"%s\", \"co2\":%d, \"temp\":%.1f, \"rh\":%.1f}"); - snprintf(publish_topic, sizeof(publish_topic), "%s%s", config::mqtt_topic_prefix, sensorId); - - if (config::mqtt_encryption) { - // The sensor doesn't check the fingerprint of the MQTT broker, because otherwise this fingerprint should be updated - // on the sensor every 3 months. The connection can still be encrypted, though: - WiFiClientSecure *secureClient = new WiFiClientSecure(); - secureClient->setInsecure(); - espClient = secureClient; - } else { - espClient = new WiFiClient(); - } - mqttClient.setClient(*espClient); - - mqttClient.setServer(config::mqtt_server, config::mqtt_port); - - sensor_console::defineIntCommand("mqtt", setMQTTinterval, F("60 (Sets MQTT sending interval, in s)")); - sensor_console::defineCommand("send_local_ip", sendInfoAboutLocalNetwork, - F("(Sends local IP and SSID via MQTT. Can be useful to find sensor)")); - } - - void publish(const char *timestamp, int16_t co2, float temperature, float humidity) { - if (wifi::connected() && mqttClient.connected()) { - led_effects::onBoardLEDOn(); - Serial.print(F("MQTT - Publishing message to '")); - Serial.print(publish_topic); - Serial.print(F("' ... ")); - - char payload[75]; // Should be enough for json... - snprintf(payload, sizeof(payload), json_sensor_format, timestamp, co2, temperature, humidity); - // Topic is 'MQTT_TOPIC_PREFIX/ESP123456' - if (mqttClient.publish(publish_topic, payload)) { - Serial.println(F("OK")); - ntp::getLocalTime(last_successful_publish); - } else { - Serial.println(F("Failed.")); - } - led_effects::onBoardLEDOff(); - } - } - - /** - * Allows sensor to be controlled by commands over MQTT - * - * mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "reset" - * mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "timer 30" - * mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "mqtt 900" - * mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "calibrate 700" - */ - void controlSensorCallback(char *sub_topic, byte *message, unsigned int length) { - if (length == 0) { - return; - } - led_effects::onBoardLEDOn(); - Serial.print(F("Message arrived on topic: ")); - Serial.println(sub_topic); - char command[length + 1]; - for (unsigned int i = 0; i < length; i++) { - command[i] = message[i]; - } - command[length] = 0; - sensor_console::execute(command); - led_effects::onBoardLEDOff(); - } - - void reconnect() { - if (last_failed_at > 0 && (seconds() - last_failed_at < config::wait_after_fail)) { - // It failed less than wait_after_fail ago. Not even trying. - return; - } - if (!wifi::connected()) { //NOTE: Sadly, WiFi.status is sometimes WL_CONNECTED even though it's really not - // No WIFI - return; - } - - Serial.print(F("MQTT - Attempting connection to ")); - Serial.print(config::mqtt_server); - Serial.print(config::mqtt_encryption ? F(" (Encrypted") : F(" (Unencrypted")); - Serial.print(F(", port ")); - Serial.print(config::mqtt_port); - Serial.print(F(") ")); - Serial.print(F("User:'")); - Serial.print(config::mqtt_user); - Serial.print(F("' ...")); - - led_effects::onBoardLEDOn(); - // Wait for connection, at most 15s (default) - mqttClient.connect(publish_topic, config::mqtt_user, config::mqtt_password); - led_effects::onBoardLEDOff(); - - connected = mqttClient.connected(); - - if (connected) { - if (config::allow_mqtt_commands) { - char control_topic[50]; // Should be enough for "MQTT_TOPIC_PREFIX/ESPd03cc5/control\0" - snprintf(control_topic, sizeof(control_topic), "%s/control", publish_topic); - mqttClient.subscribe(control_topic); - mqttClient.setCallback(controlSensorCallback); - } - Serial.println(F(" Connected.")); - last_failed_at = 0; - } else { - // As defined in PubSubClient, between -4 and 5 - const __FlashStringHelper *mqtt_statuses[] = { F("Connection timeout"), F("Connection lost"), F( - "Connection failed"), F("Disconnected"), F("Connected"), F("Bad protocol"), F("Bad client ID"), F( - "Unavailable"), F("Bad credentials"), F("Unauthorized") }; - last_failed_at = seconds(); - Serial.print(mqtt_statuses[mqttClient.state() + 4]); - Serial.print("! (Code="); - Serial.print(mqttClient.state()); - Serial.print(F("). Will try again in ")); - Serial.print(config::wait_after_fail); - Serial.println("s."); - } - } - - void publishIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temp, const float &hum) { - // Send message via MQTT according to sending interval - unsigned long now = seconds(); - if (now - last_sent_at > config::mqtt_sending_interval) { - last_sent_at = now; - publish(timestamp, co2, temp, hum); - } - } - - void keepConnection() { - // Keep MQTT connection - if (!mqttClient.connected()) { - reconnect(); - } - mqttClient.loop(); - } - - /***************************************************************** - * Callbacks for sensor commands * - *****************************************************************/ - void setMQTTinterval(int32_t sending_interval) { - config::mqtt_sending_interval = sending_interval; - Serial.print(F("Setting MQTT sending interval to : ")); - Serial.print(config::mqtt_sending_interval); - Serial.println(F("s.")); - led_effects::showKITTWheel(color::green, 1); - } - - // It can be hard to find the local IP of a sensor if it isn't connected to Serial port, and if mDNS is disabled. - // If the sensor can be reach by MQTT, it can answer with info about local_ip and ssid. - // The sensor will send the info to "CO2sensors/ESP123456/info". - void sendInfoAboutLocalNetwork() { - char info_topic[50]; // Should be enough for "MQTT_TOPIC_PREFIX/ESP123456/info" - snprintf(info_topic, sizeof(info_topic), "%s/info", publish_topic); - - char payload[75]; // Should be enough for info json... - const char *json_info_format = PSTR("{\"local_ip\":\"%s\", \"ssid\":\"%s\"}"); - snprintf(payload, sizeof(payload), json_info_format, wifi::local_ip, config::selected_ssid()); - - mqttClient.publish(info_topic, payload); - } -} diff --git a/ampel-firmware/mqtt.h b/ampel-firmware/mqtt.h deleted file mode 100644 index d9ee39efcdbe649f4ef2e3311a5e40317bbc1978..0000000000000000000000000000000000000000 --- a/ampel-firmware/mqtt.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef MQTT_H_INCLUDED -#define MQTT_H_INCLUDED - -#include // For uint32_t & uint16_t - -namespace mqtt { - extern char last_successful_publish[]; - extern bool connected; - void initialize(const char *sensorId); - void keepConnection(); - void publishIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temp, const float &hum); - - void setMQTTinterval(int32_t sending_interval); - void sendInfoAboutLocalNetwork(); -} -#endif diff --git a/ampel-firmware/ntp.cpp b/ampel-firmware/ntp.cpp deleted file mode 100644 index 2806c9b88a4f358433685228f9c9050fc951cea3..0000000000000000000000000000000000000000 --- a/ampel-firmware/ntp.cpp +++ /dev/null @@ -1,53 +0,0 @@ -#include "ntp.h" -#include "sensor_console.h" -#include "web_config.h" -#include // required for NTP -#include "src/lib/NTPClient/NTPClient.h" // NTP - -//NOTE: ESP32 sometimes couldn't access the NTP server, and every loop would take +1000ms -// ifdefs could be used to define functions specific to ESP32, e.g. with configTime -namespace ntp { - WiFiUDP ntpUDP; - NTPClient timeClient(ntpUDP); - bool connected_at_least_once = false; - void setLocalTime(int32_t unix_seconds); - - // Should be defined, even offline - void initialize() { - timeClient.setTimeOffset((config::time_zone + config::daylight_saving_time) * 3600); - sensor_console::defineIntCommand("set_time", ntp::setLocalTime, F("1618829570 (Sets time to the given UNIX time)")); - } - - void connect(){ - timeClient.setPoolServerName(config::ntp_server); - timeClient.setUpdateInterval(60000UL); - Serial.print("NTP - Trying to connect to : "); - Serial.println(config::ntp_server); - timeClient.begin(); - } - - void update() { - connected_at_least_once |= timeClient.update(); - } - - void getLocalTime(char *timestamp) { - timeClient.getFormattedDate(timestamp); - } - - void setLocalTime(int32_t unix_seconds) { - char time[23]; - timeClient.getFormattedDate(time); - Serial.print(F("Current time : ")); - Serial.println(time); - if (connected_at_least_once) { - Serial.println(F("NTP update already happened. Not changing anything.")); - return; - } - Serial.print(F("Setting UNIX time to : ")); - Serial.println(unix_seconds); - timeClient.setEpochTime(unix_seconds - seconds()); - timeClient.getFormattedDate(time); - Serial.print(F("Current time : ")); - Serial.println(time); - } -} diff --git a/ampel-firmware/ntp.h b/ampel-firmware/ntp.h deleted file mode 100644 index 1a10d67bebe2c9569b626bb7d701df83a4cc10ca..0000000000000000000000000000000000000000 --- a/ampel-firmware/ntp.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef AMPEL_TIME_H_INCLUDED -#define AMPEL_TIME_H_INCLUDED - -namespace ntp { - extern bool connected_at_least_once; - void initialize(); - void connect(); - void update(); - void getLocalTime(char *timestamp); -} - -//NOTE: Only use seconds() for duration comparison, not timestamps comparison. Otherwise, problems happen when millis roll over. -#define seconds() (millis() / 1000UL) - -#endif diff --git a/ampel-firmware/src/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.cpp b/ampel-firmware/src/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.cpp deleted file mode 100644 index a1216d9c72bc6980ef6099ae60049cfdcbd0d497..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.cpp +++ /dev/null @@ -1,3440 +0,0 @@ -/*! - * @file Adafruit_NeoPixel.cpp - * - * @mainpage Arduino Library for driving Adafruit NeoPixel addressable LEDs, - * FLORA RGB Smart Pixels and compatible devicess -- WS2811, WS2812, WS2812B, - * SK6812, etc. - * - * @section intro_sec Introduction - * - * This is the documentation for Adafruit's NeoPixel library for the - * Arduino platform, allowing a broad range of microcontroller boards - * (most AVR boards, many ARM devices, ESP8266 and ESP32, among others) - * to control Adafruit NeoPixels, FLORA RGB Smart Pixels and compatible - * devices -- WS2811, WS2812, WS2812B, SK6812, etc. - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing products - * from Adafruit! - * - * @section author Author - * - * Written by Phil "Paint Your Dragon" Burgess for Adafruit Industries, - * with contributions by PJRC, Michael Miller and other members of the - * open source community. - * - * @section license License - * - * This file is part of the Adafruit_NeoPixel library. - * - * Adafruit_NeoPixel is free software: you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * Adafruit_NeoPixel 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with NeoPixel. If not, see - * . - * - */ - -#include "Adafruit_NeoPixel.h" - -#if defined(TARGET_LPC1768) -#include -#endif - -#if defined(NRF52) || defined(NRF52_SERIES) -#include "nrf.h" - -// Interrupt is only disabled if there is no PWM device available -// Note: Adafruit Bluefruit nrf52 does not use this option -//#define NRF52_DISABLE_INT -#endif - -#if defined(ARDUINO_ARCH_NRF52840) -#if defined __has_include -#if __has_include() -#include -#endif -#endif -#endif - -/*! - @brief NeoPixel constructor when length, pin and pixel type are known - at compile-time. - @param n Number of NeoPixels in strand. - @param p Arduino pin number which will drive the NeoPixel data in. - @param t Pixel type -- add together NEO_* constants defined in - Adafruit_NeoPixel.h, for example NEO_GRB+NEO_KHZ800 for - NeoPixels expecting an 800 KHz (vs 400 KHz) data stream - with color bytes expressed in green, red, blue order per - pixel. - @return Adafruit_NeoPixel object. Call the begin() function before use. -*/ -Adafruit_NeoPixel::Adafruit_NeoPixel(uint16_t n, int16_t p, neoPixelType t) - : begun(false), brightness(0), pixels(NULL), endTime(0) { - updateType(t); - updateLength(n); - setPin(p); -#if defined(ARDUINO_ARCH_RP2040) - // Find a free SM on one of the PIO's - sm = pio_claim_unused_sm(pio, false); // don't panic - // Try pio1 if SM not found - if (sm < 0) { - pio = pio1; - sm = pio_claim_unused_sm(pio, true); // panic if no SM is free - } - init = true; -#endif -} - -/*! - @brief "Empty" NeoPixel constructor when length, pin and/or pixel type - are not known at compile-time, and must be initialized later with - updateType(), updateLength() and setPin(). - @return Adafruit_NeoPixel object. Call the begin() function before use. - @note This function is deprecated, here only for old projects that - may still be calling it. New projects should instead use the - 'new' keyword with the first constructor syntax (length, pin, - type). -*/ -Adafruit_NeoPixel::Adafruit_NeoPixel() - : -#if defined(NEO_KHZ400) - is800KHz(true), -#endif - begun(false), numLEDs(0), numBytes(0), pin(-1), brightness(0), - pixels(NULL), rOffset(1), gOffset(0), bOffset(2), wOffset(1), endTime(0) { -} - -/*! - @brief Deallocate Adafruit_NeoPixel object, set data pin back to INPUT. -*/ -Adafruit_NeoPixel::~Adafruit_NeoPixel() { - free(pixels); - if (pin >= 0) - pinMode(pin, INPUT); -} - -/*! - @brief Configure NeoPixel pin for output. -*/ -void Adafruit_NeoPixel::begin(void) { - if (pin >= 0) { - pinMode(pin, OUTPUT); - digitalWrite(pin, LOW); - } - begun = true; -} - -/*! - @brief Change the length of a previously-declared Adafruit_NeoPixel - strip object. Old data is deallocated and new data is cleared. - Pin number and pixel format are unchanged. - @param n New length of strip, in pixels. - @note This function is deprecated, here only for old projects that - may still be calling it. New projects should instead use the - 'new' keyword with the first constructor syntax (length, pin, - type). -*/ -void Adafruit_NeoPixel::updateLength(uint16_t n) { - free(pixels); // Free existing data (if any) - - // Allocate new data -- note: ALL PIXELS ARE CLEARED - numBytes = n * ((wOffset == rOffset) ? 3 : 4); - if ((pixels = (uint8_t *)malloc(numBytes))) { - memset(pixels, 0, numBytes); - numLEDs = n; - } else { - numLEDs = numBytes = 0; - } -} - -/*! - @brief Change the pixel format of a previously-declared - Adafruit_NeoPixel strip object. If format changes from one of - the RGB variants to an RGBW variant (or RGBW to RGB), the old - data will be deallocated and new data is cleared. Otherwise, - the old data will remain in RAM and is not reordered to the - new format, so it's advisable to follow up with clear(). - @param t Pixel type -- add together NEO_* constants defined in - Adafruit_NeoPixel.h, for example NEO_GRB+NEO_KHZ800 for - NeoPixels expecting an 800 KHz (vs 400 KHz) data stream - with color bytes expressed in green, red, blue order per - pixel. - @note This function is deprecated, here only for old projects that - may still be calling it. New projects should instead use the - 'new' keyword with the first constructor syntax - (length, pin, type). -*/ -void Adafruit_NeoPixel::updateType(neoPixelType t) { - bool oldThreeBytesPerPixel = (wOffset == rOffset); // false if RGBW - - wOffset = (t >> 6) & 0b11; // See notes in header file - rOffset = (t >> 4) & 0b11; // regarding R/G/B/W offsets - gOffset = (t >> 2) & 0b11; - bOffset = t & 0b11; -#if defined(NEO_KHZ400) - is800KHz = (t < 256); // 400 KHz flag is 1<<8 -#endif - - // If bytes-per-pixel has changed (and pixel data was previously - // allocated), re-allocate to new size. Will clear any data. - if (pixels) { - bool newThreeBytesPerPixel = (wOffset == rOffset); - if (newThreeBytesPerPixel != oldThreeBytesPerPixel) - updateLength(numLEDs); - } -} - -// RP2040 specific driver -#if defined(ARDUINO_ARCH_RP2040) -void Adafruit_NeoPixel::rp2040Init(uint8_t pin, bool is800KHz) -{ - uint offset = pio_add_program(pio, &ws2812_program); - - if (is800KHz) - { - // 800kHz, 8 bit transfers - ws2812_program_init(pio, sm, offset, pin, 800000, 8); - } - else - { - // 400kHz, 8 bit transfers - ws2812_program_init(pio, sm, offset, pin, 400000, 8); - } -} -// Not a user API -void Adafruit_NeoPixel::rp2040Show(uint8_t pin, uint8_t *pixels, uint32_t numBytes, bool is800KHz) -{ - if (this->init) - { - // On first pass through initialise the PIO - rp2040Init(pin, is800KHz); - this->init = false; - } - - while(numBytes--) - // Bits for transmission must be shifted to top 8 bits - pio_sm_put_blocking(pio, sm, ((uint32_t)*pixels++)<< 24); -} - -#endif - -#if defined(ESP8266) -// ESP8266 show() is external to enforce ICACHE_RAM_ATTR execution -extern "C" IRAM_ATTR void espShow(uint16_t pin, uint8_t *pixels, - uint32_t numBytes, uint8_t type); -#elif defined(ESP32) -extern "C" void espShow(uint16_t pin, uint8_t *pixels, uint32_t numBytes, - uint8_t type); -#endif // ESP8266 - -#if defined(K210) -#define KENDRYTE_K210 1 -#endif - -#if defined(KENDRYTE_K210) -extern "C" void k210Show(uint8_t pin, uint8_t *pixels, uint32_t numBytes, - boolean is800KHz); -#endif // KENDRYTE_K210 -/*! - @brief Transmit pixel data in RAM to NeoPixels. - @note On most architectures, interrupts are temporarily disabled in - order to achieve the correct NeoPixel signal timing. This means - that the Arduino millis() and micros() functions, which require - interrupts, will lose small intervals of time whenever this - function is called (about 30 microseconds per RGB pixel, 40 for - RGBW pixels). There's no easy fix for this, but a few - specialized alternative or companion libraries exist that use - very device-specific peripherals to work around it. -*/ -void Adafruit_NeoPixel::show(void) { - - if (!pixels) - return; - - // Data latch = 300+ microsecond pause in the output stream. Rather than - // put a delay at the end of the function, the ending time is noted and - // the function will simply hold off (if needed) on issuing the - // subsequent round of data until the latch time has elapsed. This - // allows the mainline code to start generating the next frame of data - // rather than stalling for the latch. - while (!canShow()) - ; - // endTime is a private member (rather than global var) so that multiple - // instances on different pins can be quickly issued in succession (each - // instance doesn't delay the next). - - // In order to make this code runtime-configurable to work with any pin, - // SBI/CBI instructions are eschewed in favor of full PORT writes via the - // OUT or ST instructions. It relies on two facts: that peripheral - // functions (such as PWM) take precedence on output pins, so our PORT- - // wide writes won't interfere, and that interrupts are globally disabled - // while data is being issued to the LEDs, so no other code will be - // accessing the PORT. The code takes an initial 'snapshot' of the PORT - // state, computes 'pin high' and 'pin low' values, and writes these back - // to the PORT register as needed. - - // NRF52 may use PWM + DMA (if available), may not need to disable interrupt -#if !(defined(NRF52) || defined(NRF52_SERIES)) - noInterrupts(); // Need 100% focus on instruction timing -#endif - -#if defined(__AVR__) - // AVR MCUs -- ATmega & ATtiny (no XMEGA) --------------------------------- - - volatile uint16_t i = numBytes; // Loop counter - volatile uint8_t *ptr = pixels, // Pointer to next byte - b = *ptr++, // Current byte value - hi, // PORT w/output bit set high - lo; // PORT w/output bit set low - - // Hand-tuned assembly code issues data to the LED drivers at a specific - // rate. There's separate code for different CPU speeds (8, 12, 16 MHz) - // for both the WS2811 (400 KHz) and WS2812 (800 KHz) drivers. The - // datastream timing for the LED drivers allows a little wiggle room each - // way (listed in the datasheets), so the conditions for compiling each - // case are set up for a range of frequencies rather than just the exact - // 8, 12 or 16 MHz values, permitting use with some close-but-not-spot-on - // devices (e.g. 16.5 MHz DigiSpark). The ranges were arrived at based - // on the datasheet figures and have not been extensively tested outside - // the canonical 8/12/16 MHz speeds; there's no guarantee these will work - // close to the extremes (or possibly they could be pushed further). - // Keep in mind only one CPU speed case actually gets compiled; the - // resulting program isn't as massive as it might look from source here. - -// 8 MHz(ish) AVR --------------------------------------------------------- -#if (F_CPU >= 7400000UL) && (F_CPU <= 9500000UL) - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - - volatile uint8_t n1, n2 = 0; // First, next bits out - - // Squeezing an 800 KHz stream out of an 8 MHz chip requires code - // specific to each PORT register. - - // 10 instruction clocks per bit: HHxxxxxLLL - // OUT instructions: ^ ^ ^ (T=0,2,7) - - // PORTD OUTPUT ---------------------------------------------------- - -#if defined(PORTD) -#if defined(PORTB) || defined(PORTC) || defined(PORTF) - if (port == &PORTD) { -#endif // defined(PORTB/C/F) - - hi = PORTD | pinMask; - lo = PORTD & ~pinMask; - n1 = lo; - if (b & 0x80) - n1 = hi; - - // Dirty trick: RJMPs proceeding to the next instruction are used - // to delay two clock cycles in one instruction word (rather than - // using two NOPs). This was necessary in order to squeeze the - // loop down to exactly 64 words -- the maximum possible for a - // relative branch. - - asm volatile( - "headD:" - "\n\t" // Clk Pseudocode - // Bit 7: - "out %[port] , %[hi]" - "\n\t" // 1 PORT = hi - "mov %[n2] , %[lo]" - "\n\t" // 1 n2 = lo - "out %[port] , %[n1]" - "\n\t" // 1 PORT = n1 - "rjmp .+0" - "\n\t" // 2 nop nop - "sbrc %[byte] , 6" - "\n\t" // 1-2 if(b & 0x40) - "mov %[n2] , %[hi]" - "\n\t" // 0-1 n2 = hi - "out %[port] , %[lo]" - "\n\t" // 1 PORT = lo - "rjmp .+0" - "\n\t" // 2 nop nop - // Bit 6: - "out %[port] , %[hi]" - "\n\t" // 1 PORT = hi - "mov %[n1] , %[lo]" - "\n\t" // 1 n1 = lo - "out %[port] , %[n2]" - "\n\t" // 1 PORT = n2 - "rjmp .+0" - "\n\t" // 2 nop nop - "sbrc %[byte] , 5" - "\n\t" // 1-2 if(b & 0x20) - "mov %[n1] , %[hi]" - "\n\t" // 0-1 n1 = hi - "out %[port] , %[lo]" - "\n\t" // 1 PORT = lo - "rjmp .+0" - "\n\t" // 2 nop nop - // Bit 5: - "out %[port] , %[hi]" - "\n\t" // 1 PORT = hi - "mov %[n2] , %[lo]" - "\n\t" // 1 n2 = lo - "out %[port] , %[n1]" - "\n\t" // 1 PORT = n1 - "rjmp .+0" - "\n\t" // 2 nop nop - "sbrc %[byte] , 4" - "\n\t" // 1-2 if(b & 0x10) - "mov %[n2] , %[hi]" - "\n\t" // 0-1 n2 = hi - "out %[port] , %[lo]" - "\n\t" // 1 PORT = lo - "rjmp .+0" - "\n\t" // 2 nop nop - // Bit 4: - "out %[port] , %[hi]" - "\n\t" // 1 PORT = hi - "mov %[n1] , %[lo]" - "\n\t" // 1 n1 = lo - "out %[port] , %[n2]" - "\n\t" // 1 PORT = n2 - "rjmp .+0" - "\n\t" // 2 nop nop - "sbrc %[byte] , 3" - "\n\t" // 1-2 if(b & 0x08) - "mov %[n1] , %[hi]" - "\n\t" // 0-1 n1 = hi - "out %[port] , %[lo]" - "\n\t" // 1 PORT = lo - "rjmp .+0" - "\n\t" // 2 nop nop - // Bit 3: - "out %[port] , %[hi]" - "\n\t" // 1 PORT = hi - "mov %[n2] , %[lo]" - "\n\t" // 1 n2 = lo - "out %[port] , %[n1]" - "\n\t" // 1 PORT = n1 - "rjmp .+0" - "\n\t" // 2 nop nop - "sbrc %[byte] , 2" - "\n\t" // 1-2 if(b & 0x04) - "mov %[n2] , %[hi]" - "\n\t" // 0-1 n2 = hi - "out %[port] , %[lo]" - "\n\t" // 1 PORT = lo - "rjmp .+0" - "\n\t" // 2 nop nop - // Bit 2: - "out %[port] , %[hi]" - "\n\t" // 1 PORT = hi - "mov %[n1] , %[lo]" - "\n\t" // 1 n1 = lo - "out %[port] , %[n2]" - "\n\t" // 1 PORT = n2 - "rjmp .+0" - "\n\t" // 2 nop nop - "sbrc %[byte] , 1" - "\n\t" // 1-2 if(b & 0x02) - "mov %[n1] , %[hi]" - "\n\t" // 0-1 n1 = hi - "out %[port] , %[lo]" - "\n\t" // 1 PORT = lo - "rjmp .+0" - "\n\t" // 2 nop nop - // Bit 1: - "out %[port] , %[hi]" - "\n\t" // 1 PORT = hi - "mov %[n2] , %[lo]" - "\n\t" // 1 n2 = lo - "out %[port] , %[n1]" - "\n\t" // 1 PORT = n1 - "rjmp .+0" - "\n\t" // 2 nop nop - "sbrc %[byte] , 0" - "\n\t" // 1-2 if(b & 0x01) - "mov %[n2] , %[hi]" - "\n\t" // 0-1 n2 = hi - "out %[port] , %[lo]" - "\n\t" // 1 PORT = lo - "sbiw %[count], 1" - "\n\t" // 2 i-- (don't act on Z flag yet) - // Bit 0: - "out %[port] , %[hi]" - "\n\t" // 1 PORT = hi - "mov %[n1] , %[lo]" - "\n\t" // 1 n1 = lo - "out %[port] , %[n2]" - "\n\t" // 1 PORT = n2 - "ld %[byte] , %a[ptr]+" - "\n\t" // 2 b = *ptr++ - "sbrc %[byte] , 7" - "\n\t" // 1-2 if(b & 0x80) - "mov %[n1] , %[hi]" - "\n\t" // 0-1 n1 = hi - "out %[port] , %[lo]" - "\n\t" // 1 PORT = lo - "brne headD" - "\n" // 2 while(i) (Z flag set above) - : [byte] "+r"(b), [n1] "+r"(n1), [n2] "+r"(n2), [count] "+w"(i) - : [port] "I"(_SFR_IO_ADDR(PORTD)), [ptr] "e"(ptr), [hi] "r"(hi), - [lo] "r"(lo)); - -#if defined(PORTB) || defined(PORTC) || defined(PORTF) - } else // other PORT(s) -#endif // defined(PORTB/C/F) -#endif // defined(PORTD) - - // PORTB OUTPUT ---------------------------------------------------- - -#if defined(PORTB) -#if defined(PORTD) || defined(PORTC) || defined(PORTF) - if (port == &PORTB) { -#endif // defined(PORTD/C/F) - - // Same as above, just switched to PORTB and stripped of comments. - hi = PORTB | pinMask; - lo = PORTB & ~pinMask; - n1 = lo; - if (b & 0x80) - n1 = hi; - - asm volatile( - "headB:" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 6" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 5" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 4" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 3" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 2" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 1" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 0" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "sbiw %[count], 1" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "ld %[byte] , %a[ptr]+" - "\n\t" - "sbrc %[byte] , 7" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "brne headB" - "\n" - : [byte] "+r"(b), [n1] "+r"(n1), [n2] "+r"(n2), [count] "+w"(i) - : [port] "I"(_SFR_IO_ADDR(PORTB)), [ptr] "e"(ptr), [hi] "r"(hi), - [lo] "r"(lo)); - -#if defined(PORTD) || defined(PORTC) || defined(PORTF) - } -#endif -#if defined(PORTC) || defined(PORTF) - else -#endif // defined(PORTC/F) -#endif // defined(PORTB) - - // PORTC OUTPUT ---------------------------------------------------- - -#if defined(PORTC) -#if defined(PORTD) || defined(PORTB) || defined(PORTF) - if (port == &PORTC) { -#endif // defined(PORTD/B/F) - - // Same as above, just switched to PORTC and stripped of comments. - hi = PORTC | pinMask; - lo = PORTC & ~pinMask; - n1 = lo; - if (b & 0x80) - n1 = hi; - - asm volatile( - "headC:" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 6" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 5" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 4" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 3" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 2" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 1" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 0" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "sbiw %[count], 1" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "ld %[byte] , %a[ptr]+" - "\n\t" - "sbrc %[byte] , 7" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "brne headC" - "\n" - : [byte] "+r"(b), [n1] "+r"(n1), [n2] "+r"(n2), [count] "+w"(i) - : [port] "I"(_SFR_IO_ADDR(PORTC)), [ptr] "e"(ptr), [hi] "r"(hi), - [lo] "r"(lo)); - -#if defined(PORTD) || defined(PORTB) || defined(PORTF) - } -#endif // defined(PORTD/B/F) -#if defined(PORTF) - else -#endif -#endif // defined(PORTC) - - // PORTF OUTPUT ---------------------------------------------------- - -#if defined(PORTF) -#if defined(PORTD) || defined(PORTB) || defined(PORTC) - if (port == &PORTF) { -#endif // defined(PORTD/B/C) - - hi = PORTF | pinMask; - lo = PORTF & ~pinMask; - n1 = lo; - if (b & 0x80) - n1 = hi; - - asm volatile( - "headF:" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 6" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 5" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 4" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 3" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 2" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 1" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "rjmp .+0" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n2] , %[lo]" - "\n\t" - "out %[port] , %[n1]" - "\n\t" - "rjmp .+0" - "\n\t" - "sbrc %[byte] , 0" - "\n\t" - "mov %[n2] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "sbiw %[count], 1" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "mov %[n1] , %[lo]" - "\n\t" - "out %[port] , %[n2]" - "\n\t" - "ld %[byte] , %a[ptr]+" - "\n\t" - "sbrc %[byte] , 7" - "\n\t" - "mov %[n1] , %[hi]" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "brne headF" - "\n" - : [byte] "+r"(b), [n1] "+r"(n1), [n2] "+r"(n2), [count] "+w"(i) - : [port] "I"(_SFR_IO_ADDR(PORTF)), [ptr] "e"(ptr), [hi] "r"(hi), - [lo] "r"(lo)); - -#if defined(PORTD) || defined(PORTB) || defined(PORTC) - } -#endif // defined(PORTD/B/C) -#endif // defined(PORTF) - -#if defined(NEO_KHZ400) - } else { // end 800 KHz, do 400 KHz - - // Timing is more relaxed; unrolling the inner loop for each bit is - // not necessary. Still using the peculiar RJMPs as 2X NOPs, not out - // of need but just to trim the code size down a little. - // This 400-KHz-datastream-on-8-MHz-CPU code is not quite identical - // to the 800-on-16 code later -- the hi/lo timing between WS2811 and - // WS2812 is not simply a 2:1 scale! - - // 20 inst. clocks per bit: HHHHxxxxxxLLLLLLLLLL - // ST instructions: ^ ^ ^ (T=0,4,10) - - volatile uint8_t next, bit; - - hi = *port | pinMask; - lo = *port & ~pinMask; - next = lo; - bit = 8; - - asm volatile("head20:" - "\n\t" // Clk Pseudocode (T = 0) - "st %a[port], %[hi]" - "\n\t" // 2 PORT = hi (T = 2) - "sbrc %[byte] , 7" - "\n\t" // 1-2 if(b & 128) - "mov %[next], %[hi]" - "\n\t" // 0-1 next = hi (T = 4) - "st %a[port], %[next]" - "\n\t" // 2 PORT = next (T = 6) - "mov %[next] , %[lo]" - "\n\t" // 1 next = lo (T = 7) - "dec %[bit]" - "\n\t" // 1 bit-- (T = 8) - "breq nextbyte20" - "\n\t" // 1-2 if(bit == 0) - "rol %[byte]" - "\n\t" // 1 b <<= 1 (T = 10) - "st %a[port], %[lo]" - "\n\t" // 2 PORT = lo (T = 12) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 14) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 16) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 18) - "rjmp head20" - "\n\t" // 2 -> head20 (next bit out) - "nextbyte20:" - "\n\t" // (T = 10) - "st %a[port], %[lo]" - "\n\t" // 2 PORT = lo (T = 12) - "nop" - "\n\t" // 1 nop (T = 13) - "ldi %[bit] , 8" - "\n\t" // 1 bit = 8 (T = 14) - "ld %[byte] , %a[ptr]+" - "\n\t" // 2 b = *ptr++ (T = 16) - "sbiw %[count], 1" - "\n\t" // 2 i-- (T = 18) - "brne head20" - "\n" // 2 if(i != 0) -> (next byte) - : [port] "+e"(port), [byte] "+r"(b), [bit] "+r"(bit), - [next] "+r"(next), [count] "+w"(i) - : [hi] "r"(hi), [lo] "r"(lo), [ptr] "e"(ptr)); - } -#endif // NEO_KHZ400 - -// 12 MHz(ish) AVR -------------------------------------------------------- -#elif (F_CPU >= 11100000UL) && (F_CPU <= 14300000UL) - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - - // In the 12 MHz case, an optimized 800 KHz datastream (no dead time - // between bytes) requires a PORT-specific loop similar to the 8 MHz - // code (but a little more relaxed in this case). - - // 15 instruction clocks per bit: HHHHxxxxxxLLLLL - // OUT instructions: ^ ^ ^ (T=0,4,10) - - volatile uint8_t next; - - // PORTD OUTPUT ---------------------------------------------------- - -#if defined(PORTD) -#if defined(PORTB) || defined(PORTC) || defined(PORTF) - if (port == &PORTD) { -#endif // defined(PORTB/C/F) - - hi = PORTD | pinMask; - lo = PORTD & ~pinMask; - next = lo; - if (b & 0x80) - next = hi; - - // Don't "optimize" the OUT calls into the bitTime subroutine; - // we're exploiting the RCALL and RET as 3- and 4-cycle NOPs! - asm volatile("headD:" - "\n\t" // (T = 0) - "out %[port], %[hi]" - "\n\t" // (T = 1) - "rcall bitTimeD" - "\n\t" // Bit 7 (T = 15) - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeD" - "\n\t" // Bit 6 - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeD" - "\n\t" // Bit 5 - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeD" - "\n\t" // Bit 4 - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeD" - "\n\t" // Bit 3 - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeD" - "\n\t" // Bit 2 - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeD" - "\n\t" // Bit 1 - // Bit 0: - "out %[port] , %[hi]" - "\n\t" // 1 PORT = hi (T = 1) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 3) - "ld %[byte] , %a[ptr]+" - "\n\t" // 2 b = *ptr++ (T = 5) - "out %[port] , %[next]" - "\n\t" // 1 PORT = next (T = 6) - "mov %[next] , %[lo]" - "\n\t" // 1 next = lo (T = 7) - "sbrc %[byte] , 7" - "\n\t" // 1-2 if(b & 0x80) (T = 8) - "mov %[next] , %[hi]" - "\n\t" // 0-1 next = hi (T = 9) - "nop" - "\n\t" // 1 (T = 10) - "out %[port] , %[lo]" - "\n\t" // 1 PORT = lo (T = 11) - "sbiw %[count], 1" - "\n\t" // 2 i-- (T = 13) - "brne headD" - "\n\t" // 2 if(i != 0) -> (next byte) - "rjmp doneD" - "\n\t" - "bitTimeD:" - "\n\t" // nop nop nop (T = 4) - "out %[port], %[next]" - "\n\t" // 1 PORT = next (T = 5) - "mov %[next], %[lo]" - "\n\t" // 1 next = lo (T = 6) - "rol %[byte]" - "\n\t" // 1 b <<= 1 (T = 7) - "sbrc %[byte], 7" - "\n\t" // 1-2 if(b & 0x80) (T = 8) - "mov %[next], %[hi]" - "\n\t" // 0-1 next = hi (T = 9) - "nop" - "\n\t" // 1 (T = 10) - "out %[port], %[lo]" - "\n\t" // 1 PORT = lo (T = 11) - "ret" - "\n\t" // 4 nop nop nop nop (T = 15) - "doneD:" - "\n" - : [byte] "+r"(b), [next] "+r"(next), [count] "+w"(i) - : [port] "I"(_SFR_IO_ADDR(PORTD)), [ptr] "e"(ptr), - [hi] "r"(hi), [lo] "r"(lo)); - -#if defined(PORTB) || defined(PORTC) || defined(PORTF) - } else // other PORT(s) -#endif // defined(PORTB/C/F) -#endif // defined(PORTD) - - // PORTB OUTPUT ---------------------------------------------------- - -#if defined(PORTB) -#if defined(PORTD) || defined(PORTC) || defined(PORTF) - if (port == &PORTB) { -#endif // defined(PORTD/C/F) - - hi = PORTB | pinMask; - lo = PORTB & ~pinMask; - next = lo; - if (b & 0x80) - next = hi; - - // Same as above, just set for PORTB & stripped of comments - asm volatile("headB:" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeB" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeB" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeB" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeB" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeB" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeB" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeB" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "rjmp .+0" - "\n\t" - "ld %[byte] , %a[ptr]+" - "\n\t" - "out %[port] , %[next]" - "\n\t" - "mov %[next] , %[lo]" - "\n\t" - "sbrc %[byte] , 7" - "\n\t" - "mov %[next] , %[hi]" - "\n\t" - "nop" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "sbiw %[count], 1" - "\n\t" - "brne headB" - "\n\t" - "rjmp doneB" - "\n\t" - "bitTimeB:" - "\n\t" - "out %[port], %[next]" - "\n\t" - "mov %[next], %[lo]" - "\n\t" - "rol %[byte]" - "\n\t" - "sbrc %[byte], 7" - "\n\t" - "mov %[next], %[hi]" - "\n\t" - "nop" - "\n\t" - "out %[port], %[lo]" - "\n\t" - "ret" - "\n\t" - "doneB:" - "\n" - : [byte] "+r"(b), [next] "+r"(next), [count] "+w"(i) - : [port] "I"(_SFR_IO_ADDR(PORTB)), [ptr] "e"(ptr), - [hi] "r"(hi), [lo] "r"(lo)); - -#if defined(PORTD) || defined(PORTC) || defined(PORTF) - } -#endif -#if defined(PORTC) || defined(PORTF) - else -#endif // defined(PORTC/F) -#endif // defined(PORTB) - - // PORTC OUTPUT ---------------------------------------------------- - -#if defined(PORTC) -#if defined(PORTD) || defined(PORTB) || defined(PORTF) - if (port == &PORTC) { -#endif // defined(PORTD/B/F) - - hi = PORTC | pinMask; - lo = PORTC & ~pinMask; - next = lo; - if (b & 0x80) - next = hi; - - // Same as above, just set for PORTC & stripped of comments - asm volatile("headC:" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "rjmp .+0" - "\n\t" - "ld %[byte] , %a[ptr]+" - "\n\t" - "out %[port] , %[next]" - "\n\t" - "mov %[next] , %[lo]" - "\n\t" - "sbrc %[byte] , 7" - "\n\t" - "mov %[next] , %[hi]" - "\n\t" - "nop" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "sbiw %[count], 1" - "\n\t" - "brne headC" - "\n\t" - "rjmp doneC" - "\n\t" - "bitTimeC:" - "\n\t" - "out %[port], %[next]" - "\n\t" - "mov %[next], %[lo]" - "\n\t" - "rol %[byte]" - "\n\t" - "sbrc %[byte], 7" - "\n\t" - "mov %[next], %[hi]" - "\n\t" - "nop" - "\n\t" - "out %[port], %[lo]" - "\n\t" - "ret" - "\n\t" - "doneC:" - "\n" - : [byte] "+r"(b), [next] "+r"(next), [count] "+w"(i) - : [port] "I"(_SFR_IO_ADDR(PORTC)), [ptr] "e"(ptr), - [hi] "r"(hi), [lo] "r"(lo)); - -#if defined(PORTD) || defined(PORTB) || defined(PORTF) - } -#endif // defined(PORTD/B/F) -#if defined(PORTF) - else -#endif -#endif // defined(PORTC) - - // PORTF OUTPUT ---------------------------------------------------- - -#if defined(PORTF) -#if defined(PORTD) || defined(PORTB) || defined(PORTC) - if (port == &PORTF) { -#endif // defined(PORTD/B/C) - - hi = PORTF | pinMask; - lo = PORTF & ~pinMask; - next = lo; - if (b & 0x80) - next = hi; - - // Same as above, just set for PORTF & stripped of comments - asm volatile("headF:" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port], %[hi]" - "\n\t" - "rcall bitTimeC" - "\n\t" - "out %[port] , %[hi]" - "\n\t" - "rjmp .+0" - "\n\t" - "ld %[byte] , %a[ptr]+" - "\n\t" - "out %[port] , %[next]" - "\n\t" - "mov %[next] , %[lo]" - "\n\t" - "sbrc %[byte] , 7" - "\n\t" - "mov %[next] , %[hi]" - "\n\t" - "nop" - "\n\t" - "out %[port] , %[lo]" - "\n\t" - "sbiw %[count], 1" - "\n\t" - "brne headF" - "\n\t" - "rjmp doneC" - "\n\t" - "bitTimeC:" - "\n\t" - "out %[port], %[next]" - "\n\t" - "mov %[next], %[lo]" - "\n\t" - "rol %[byte]" - "\n\t" - "sbrc %[byte], 7" - "\n\t" - "mov %[next], %[hi]" - "\n\t" - "nop" - "\n\t" - "out %[port], %[lo]" - "\n\t" - "ret" - "\n\t" - "doneC:" - "\n" - : [byte] "+r"(b), [next] "+r"(next), [count] "+w"(i) - : [port] "I"(_SFR_IO_ADDR(PORTF)), [ptr] "e"(ptr), - [hi] "r"(hi), [lo] "r"(lo)); - -#if defined(PORTD) || defined(PORTB) || defined(PORTC) - } -#endif // defined(PORTD/B/C) -#endif // defined(PORTF) - -#if defined(NEO_KHZ400) - } else { // 400 KHz - - // 30 instruction clocks per bit: HHHHHHxxxxxxxxxLLLLLLLLLLLLLLL - // ST instructions: ^ ^ ^ (T=0,6,15) - - volatile uint8_t next, bit; - - hi = *port | pinMask; - lo = *port & ~pinMask; - next = lo; - bit = 8; - - asm volatile("head30:" - "\n\t" // Clk Pseudocode (T = 0) - "st %a[port], %[hi]" - "\n\t" // 2 PORT = hi (T = 2) - "sbrc %[byte] , 7" - "\n\t" // 1-2 if(b & 128) - "mov %[next], %[hi]" - "\n\t" // 0-1 next = hi (T = 4) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 6) - "st %a[port], %[next]" - "\n\t" // 2 PORT = next (T = 8) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 10) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 12) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 14) - "nop" - "\n\t" // 1 nop (T = 15) - "st %a[port], %[lo]" - "\n\t" // 2 PORT = lo (T = 17) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 19) - "dec %[bit]" - "\n\t" // 1 bit-- (T = 20) - "breq nextbyte30" - "\n\t" // 1-2 if(bit == 0) - "rol %[byte]" - "\n\t" // 1 b <<= 1 (T = 22) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 24) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 26) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 28) - "rjmp head30" - "\n\t" // 2 -> head30 (next bit out) - "nextbyte30:" - "\n\t" // (T = 22) - "nop" - "\n\t" // 1 nop (T = 23) - "ldi %[bit] , 8" - "\n\t" // 1 bit = 8 (T = 24) - "ld %[byte] , %a[ptr]+" - "\n\t" // 2 b = *ptr++ (T = 26) - "sbiw %[count], 1" - "\n\t" // 2 i-- (T = 28) - "brne head30" - "\n" // 1-2 if(i != 0) -> (next byte) - : [port] "+e"(port), [byte] "+r"(b), [bit] "+r"(bit), - [next] "+r"(next), [count] "+w"(i) - : [hi] "r"(hi), [lo] "r"(lo), [ptr] "e"(ptr)); - } -#endif // NEO_KHZ400 - -// 16 MHz(ish) AVR -------------------------------------------------------- -#elif (F_CPU >= 15400000UL) && (F_CPU <= 19000000L) - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - - // WS2811 and WS2812 have different hi/lo duty cycles; this is - // similar but NOT an exact copy of the prior 400-on-8 code. - - // 20 inst. clocks per bit: HHHHHxxxxxxxxLLLLLLL - // ST instructions: ^ ^ ^ (T=0,5,13) - - volatile uint8_t next, bit; - - hi = *port | pinMask; - lo = *port & ~pinMask; - next = lo; - bit = 8; - - asm volatile("head20:" - "\n\t" // Clk Pseudocode (T = 0) - "st %a[port], %[hi]" - "\n\t" // 2 PORT = hi (T = 2) - "sbrc %[byte], 7" - "\n\t" // 1-2 if(b & 128) - "mov %[next], %[hi]" - "\n\t" // 0-1 next = hi (T = 4) - "dec %[bit]" - "\n\t" // 1 bit-- (T = 5) - "st %a[port], %[next]" - "\n\t" // 2 PORT = next (T = 7) - "mov %[next] , %[lo]" - "\n\t" // 1 next = lo (T = 8) - "breq nextbyte20" - "\n\t" // 1-2 if(bit == 0) (from dec above) - "rol %[byte]" - "\n\t" // 1 b <<= 1 (T = 10) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 12) - "nop" - "\n\t" // 1 nop (T = 13) - "st %a[port], %[lo]" - "\n\t" // 2 PORT = lo (T = 15) - "nop" - "\n\t" // 1 nop (T = 16) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 18) - "rjmp head20" - "\n\t" // 2 -> head20 (next bit out) - "nextbyte20:" - "\n\t" // (T = 10) - "ldi %[bit] , 8" - "\n\t" // 1 bit = 8 (T = 11) - "ld %[byte] , %a[ptr]+" - "\n\t" // 2 b = *ptr++ (T = 13) - "st %a[port], %[lo]" - "\n\t" // 2 PORT = lo (T = 15) - "nop" - "\n\t" // 1 nop (T = 16) - "sbiw %[count], 1" - "\n\t" // 2 i-- (T = 18) - "brne head20" - "\n" // 2 if(i != 0) -> (next byte) - : [port] "+e"(port), [byte] "+r"(b), [bit] "+r"(bit), - [next] "+r"(next), [count] "+w"(i) - : [ptr] "e"(ptr), [hi] "r"(hi), [lo] "r"(lo)); - -#if defined(NEO_KHZ400) - } else { // 400 KHz - - // The 400 KHz clock on 16 MHz MCU is the most 'relaxed' version. - - // 40 inst. clocks per bit: HHHHHHHHxxxxxxxxxxxxLLLLLLLLLLLLLLLLLLLL - // ST instructions: ^ ^ ^ (T=0,8,20) - - volatile uint8_t next, bit; - - hi = *port | pinMask; - lo = *port & ~pinMask; - next = lo; - bit = 8; - - asm volatile("head40:" - "\n\t" // Clk Pseudocode (T = 0) - "st %a[port], %[hi]" - "\n\t" // 2 PORT = hi (T = 2) - "sbrc %[byte] , 7" - "\n\t" // 1-2 if(b & 128) - "mov %[next] , %[hi]" - "\n\t" // 0-1 next = hi (T = 4) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 6) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 8) - "st %a[port], %[next]" - "\n\t" // 2 PORT = next (T = 10) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 12) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 14) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 16) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 18) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 20) - "st %a[port], %[lo]" - "\n\t" // 2 PORT = lo (T = 22) - "nop" - "\n\t" // 1 nop (T = 23) - "mov %[next] , %[lo]" - "\n\t" // 1 next = lo (T = 24) - "dec %[bit]" - "\n\t" // 1 bit-- (T = 25) - "breq nextbyte40" - "\n\t" // 1-2 if(bit == 0) - "rol %[byte]" - "\n\t" // 1 b <<= 1 (T = 27) - "nop" - "\n\t" // 1 nop (T = 28) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 30) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 32) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 34) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 36) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 38) - "rjmp head40" - "\n\t" // 2 -> head40 (next bit out) - "nextbyte40:" - "\n\t" // (T = 27) - "ldi %[bit] , 8" - "\n\t" // 1 bit = 8 (T = 28) - "ld %[byte] , %a[ptr]+" - "\n\t" // 2 b = *ptr++ (T = 30) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 32) - "st %a[port], %[lo]" - "\n\t" // 2 PORT = lo (T = 34) - "rjmp .+0" - "\n\t" // 2 nop nop (T = 36) - "sbiw %[count], 1" - "\n\t" // 2 i-- (T = 38) - "brne head40" - "\n" // 1-2 if(i != 0) -> (next byte) - : [port] "+e"(port), [byte] "+r"(b), [bit] "+r"(bit), - [next] "+r"(next), [count] "+w"(i) - : [ptr] "e"(ptr), [hi] "r"(hi), [lo] "r"(lo)); - } -#endif // NEO_KHZ400 - -#else -#error "CPU SPEED NOT SUPPORTED" -#endif // end F_CPU ifdefs on __AVR__ - - // END AVR ---------------------------------------------------------------- - -#elif defined(__arm__) - - // ARM MCUs -- Teensy 3.0, 3.1, LC, Arduino Due, RP2040 ------------------- - -#if defined(ARDUINO_ARCH_RP2040) - // Use PIO - rp2040Show(pin, pixels, numBytes, is800KHz); - -#elif defined(TEENSYDUINO) && \ - defined(KINETISK) // Teensy 3.0, 3.1, 3.2, 3.5, 3.6 -#define CYCLES_800_T0H (F_CPU / 4000000) -#define CYCLES_800_T1H (F_CPU / 1250000) -#define CYCLES_800 (F_CPU / 800000) -#define CYCLES_400_T0H (F_CPU / 2000000) -#define CYCLES_400_T1H (F_CPU / 833333) -#define CYCLES_400 (F_CPU / 400000) - - uint8_t *p = pixels, *end = p + numBytes, pix, mask; - volatile uint8_t *set = portSetRegister(pin), *clr = portClearRegister(pin); - uint32_t cyc; - - ARM_DEMCR |= ARM_DEMCR_TRCENA; - ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA; - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - cyc = ARM_DWT_CYCCNT + CYCLES_800; - while (p < end) { - pix = *p++; - for (mask = 0x80; mask; mask >>= 1) { - while (ARM_DWT_CYCCNT - cyc < CYCLES_800) - ; - cyc = ARM_DWT_CYCCNT; - *set = 1; - if (pix & mask) { - while (ARM_DWT_CYCCNT - cyc < CYCLES_800_T1H) - ; - } else { - while (ARM_DWT_CYCCNT - cyc < CYCLES_800_T0H) - ; - } - *clr = 1; - } - } - while (ARM_DWT_CYCCNT - cyc < CYCLES_800) - ; -#if defined(NEO_KHZ400) - } else { // 400 kHz bitstream - cyc = ARM_DWT_CYCCNT + CYCLES_400; - while (p < end) { - pix = *p++; - for (mask = 0x80; mask; mask >>= 1) { - while (ARM_DWT_CYCCNT - cyc < CYCLES_400) - ; - cyc = ARM_DWT_CYCCNT; - *set = 1; - if (pix & mask) { - while (ARM_DWT_CYCCNT - cyc < CYCLES_400_T1H) - ; - } else { - while (ARM_DWT_CYCCNT - cyc < CYCLES_400_T0H) - ; - } - *clr = 1; - } - } - while (ARM_DWT_CYCCNT - cyc < CYCLES_400) - ; - } -#endif // NEO_KHZ400 - -#elif defined(TEENSYDUINO) && (defined(__IMXRT1052__) || defined(__IMXRT1062__)) -#define CYCLES_800_T0H (F_CPU_ACTUAL / 4000000) -#define CYCLES_800_T1H (F_CPU_ACTUAL / 1250000) -#define CYCLES_800 (F_CPU_ACTUAL / 800000) -#define CYCLES_400_T0H (F_CPU_ACTUAL / 2000000) -#define CYCLES_400_T1H (F_CPU_ACTUAL / 833333) -#define CYCLES_400 (F_CPU_ACTUAL / 400000) - - uint8_t *p = pixels, *end = p + numBytes, pix, mask; - volatile uint32_t *set = portSetRegister(pin), *clr = portClearRegister(pin); - uint32_t cyc, msk = digitalPinToBitMask(pin); - - ARM_DEMCR |= ARM_DEMCR_TRCENA; - ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA; - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - cyc = ARM_DWT_CYCCNT + CYCLES_800; - while (p < end) { - pix = *p++; - for (mask = 0x80; mask; mask >>= 1) { - while (ARM_DWT_CYCCNT - cyc < CYCLES_800) - ; - cyc = ARM_DWT_CYCCNT; - *set = msk; - if (pix & mask) { - while (ARM_DWT_CYCCNT - cyc < CYCLES_800_T1H) - ; - } else { - while (ARM_DWT_CYCCNT - cyc < CYCLES_800_T0H) - ; - } - *clr = msk; - } - } - while (ARM_DWT_CYCCNT - cyc < CYCLES_800) - ; -#if defined(NEO_KHZ400) - } else { // 400 kHz bitstream - cyc = ARM_DWT_CYCCNT + CYCLES_400; - while (p < end) { - pix = *p++; - for (mask = 0x80; mask; mask >>= 1) { - while (ARM_DWT_CYCCNT - cyc < CYCLES_400) - ; - cyc = ARM_DWT_CYCCNT; - *set = msk; - if (pix & mask) { - while (ARM_DWT_CYCCNT - cyc < CYCLES_400_T1H) - ; - } else { - while (ARM_DWT_CYCCNT - cyc < CYCLES_400_T0H) - ; - } - *clr = msk; - } - } - while (ARM_DWT_CYCCNT - cyc < CYCLES_400) - ; - } -#endif // NEO_KHZ400 - -#elif defined(TEENSYDUINO) && defined(__MKL26Z64__) // Teensy-LC - -#if F_CPU == 48000000 - uint8_t *p = pixels, pix, count, dly, bitmask = digitalPinToBitMask(pin); - volatile uint8_t *reg = portSetRegister(pin); - uint32_t num = numBytes; - asm volatile("L%=_begin:" - "\n\t" - "ldrb %[pix], [%[p], #0]" - "\n\t" - "lsl %[pix], #24" - "\n\t" - "movs %[count], #7" - "\n\t" - "L%=_loop:" - "\n\t" - "lsl %[pix], #1" - "\n\t" - "bcs L%=_loop_one" - "\n\t" - "L%=_loop_zero:" - "\n\t" - "strb %[bitmask], [%[reg], #0]" - "\n\t" - "movs %[dly], #4" - "\n\t" - "L%=_loop_delay_T0H:" - "\n\t" - "sub %[dly], #1" - "\n\t" - "bne L%=_loop_delay_T0H" - "\n\t" - "strb %[bitmask], [%[reg], #4]" - "\n\t" - "movs %[dly], #13" - "\n\t" - "L%=_loop_delay_T0L:" - "\n\t" - "sub %[dly], #1" - "\n\t" - "bne L%=_loop_delay_T0L" - "\n\t" - "b L%=_next" - "\n\t" - "L%=_loop_one:" - "\n\t" - "strb %[bitmask], [%[reg], #0]" - "\n\t" - "movs %[dly], #13" - "\n\t" - "L%=_loop_delay_T1H:" - "\n\t" - "sub %[dly], #1" - "\n\t" - "bne L%=_loop_delay_T1H" - "\n\t" - "strb %[bitmask], [%[reg], #4]" - "\n\t" - "movs %[dly], #4" - "\n\t" - "L%=_loop_delay_T1L:" - "\n\t" - "sub %[dly], #1" - "\n\t" - "bne L%=_loop_delay_T1L" - "\n\t" - "nop" - "\n\t" - "L%=_next:" - "\n\t" - "sub %[count], #1" - "\n\t" - "bne L%=_loop" - "\n\t" - "lsl %[pix], #1" - "\n\t" - "bcs L%=_last_one" - "\n\t" - "L%=_last_zero:" - "\n\t" - "strb %[bitmask], [%[reg], #0]" - "\n\t" - "movs %[dly], #4" - "\n\t" - "L%=_last_delay_T0H:" - "\n\t" - "sub %[dly], #1" - "\n\t" - "bne L%=_last_delay_T0H" - "\n\t" - "strb %[bitmask], [%[reg], #4]" - "\n\t" - "movs %[dly], #10" - "\n\t" - "L%=_last_delay_T0L:" - "\n\t" - "sub %[dly], #1" - "\n\t" - "bne L%=_last_delay_T0L" - "\n\t" - "b L%=_repeat" - "\n\t" - "L%=_last_one:" - "\n\t" - "strb %[bitmask], [%[reg], #0]" - "\n\t" - "movs %[dly], #13" - "\n\t" - "L%=_last_delay_T1H:" - "\n\t" - "sub %[dly], #1" - "\n\t" - "bne L%=_last_delay_T1H" - "\n\t" - "strb %[bitmask], [%[reg], #4]" - "\n\t" - "movs %[dly], #1" - "\n\t" - "L%=_last_delay_T1L:" - "\n\t" - "sub %[dly], #1" - "\n\t" - "bne L%=_last_delay_T1L" - "\n\t" - "nop" - "\n\t" - "L%=_repeat:" - "\n\t" - "add %[p], #1" - "\n\t" - "sub %[num], #1" - "\n\t" - "bne L%=_begin" - "\n\t" - "L%=_done:" - "\n\t" - : [p] "+r"(p), [pix] "=&r"(pix), [count] "=&r"(count), - [dly] "=&r"(dly), [num] "+r"(num) - : [bitmask] "r"(bitmask), [reg] "r"(reg)); -#else -#error "Sorry, only 48 MHz is supported, please set Tools > CPU Speed to 48 MHz" -#endif // F_CPU == 48000000 - - // Begin of support for nRF52 based boards ------------------------- - -#elif defined(NRF52) || defined(NRF52_SERIES) -// [[[Begin of the Neopixel NRF52 EasyDMA implementation -// by the Hackerspace San Salvador]]] -// This technique uses the PWM peripheral on the NRF52. The PWM uses the -// EasyDMA feature included on the chip. This technique loads the duty -// cycle configuration for each cycle when the PWM is enabled. For this -// to work we need to store a 16 bit configuration for each bit of the -// RGB(W) values in the pixel buffer. -// Comparator values for the PWM were hand picked and are guaranteed to -// be 100% organic to preserve freshness and high accuracy. Current -// parameters are: -// * PWM Clock: 16Mhz -// * Minimum step time: 62.5ns -// * Time for zero in high (T0H): 0.31ms -// * Time for one in high (T1H): 0.75ms -// * Cycle time: 1.25us -// * Frequency: 800Khz -// For 400Khz we just double the calculated times. -// ---------- BEGIN Constants for the EasyDMA implementation ----------- -// The PWM starts the duty cycle in LOW. To start with HIGH we -// need to set the 15th bit on each register. - -// WS2812 (rev A) timing is 0.35 and 0.7us -//#define MAGIC_T0H 5UL | (0x8000) // 0.3125us -//#define MAGIC_T1H 12UL | (0x8000) // 0.75us - -// WS2812B (rev B) timing is 0.4 and 0.8 us -#define MAGIC_T0H 6UL | (0x8000) // 0.375us -#define MAGIC_T1H 13UL | (0x8000) // 0.8125us - -// WS2811 (400 khz) timing is 0.5 and 1.2 -#define MAGIC_T0H_400KHz 8UL | (0x8000) // 0.5us -#define MAGIC_T1H_400KHz 19UL | (0x8000) // 1.1875us - -// For 400Khz, we double value of CTOPVAL -#define CTOPVAL 20UL // 1.25us -#define CTOPVAL_400KHz 40UL // 2.5us - -// ---------- END Constants for the EasyDMA implementation ------------- -// -// If there is no device available an alternative cycle-counter -// implementation is tried. -// The nRF52 runs with a fixed clock of 64Mhz. The alternative -// implementation is the same as the one used for the Teensy 3.0/1/2 but -// with the Nordic SDK HAL & registers syntax. -// The number of cycles was hand picked and is guaranteed to be 100% -// organic to preserve freshness and high accuracy. -// ---------- BEGIN Constants for cycle counter implementation --------- -#define CYCLES_800_T0H 18 // ~0.36 uS -#define CYCLES_800_T1H 41 // ~0.76 uS -#define CYCLES_800 71 // ~1.25 uS - -#define CYCLES_400_T0H 26 // ~0.50 uS -#define CYCLES_400_T1H 70 // ~1.26 uS -#define CYCLES_400 156 // ~2.50 uS - // ---------- END of Constants for cycle counter implementation -------- - - // To support both the SoftDevice + Neopixels we use the EasyDMA - // feature from the NRF25. However this technique implies to - // generate a pattern and store it on the memory. The actual - // memory used in bytes corresponds to the following formula: - // totalMem = numBytes*8*2+(2*2) - // The two additional bytes at the end are needed to reset the - // sequence. - // - // If there is not enough memory, we will fall back to cycle counter - // using DWT - uint32_t pattern_size = - numBytes * 8 * sizeof(uint16_t) + 2 * sizeof(uint16_t); - uint16_t *pixels_pattern = NULL; - - NRF_PWM_Type *pwm = NULL; - - // Try to find a free PWM device, which is not enabled - // and has no connected pins - NRF_PWM_Type *PWM[] = { - NRF_PWM0, - NRF_PWM1, - NRF_PWM2 -#if defined(NRF_PWM3) - , - NRF_PWM3 -#endif - }; - - for (unsigned int device = 0; device < (sizeof(PWM) / sizeof(PWM[0])); - device++) { - if ((PWM[device]->ENABLE == 0) && - (PWM[device]->PSEL.OUT[0] & PWM_PSEL_OUT_CONNECT_Msk) && - (PWM[device]->PSEL.OUT[1] & PWM_PSEL_OUT_CONNECT_Msk) && - (PWM[device]->PSEL.OUT[2] & PWM_PSEL_OUT_CONNECT_Msk) && - (PWM[device]->PSEL.OUT[3] & PWM_PSEL_OUT_CONNECT_Msk)) { - pwm = PWM[device]; - break; - } - } - - // only malloc if there is PWM device available - if (pwm != NULL) { -#if defined(ARDUINO_NRF52_ADAFRUIT) // use thread-safe malloc - pixels_pattern = (uint16_t *)rtos_malloc(pattern_size); -#else - pixels_pattern = (uint16_t *)malloc(pattern_size); -#endif - } - - // Use the identified device to choose the implementation - // If a PWM device is available use DMA - if ((pixels_pattern != NULL) && (pwm != NULL)) { - uint16_t pos = 0; // bit position - - for (uint16_t n = 0; n < numBytes; n++) { - uint8_t pix = pixels[n]; - - for (uint8_t mask = 0x80; mask > 0; mask >>= 1) { -#if defined(NEO_KHZ400) - if (!is800KHz) { - pixels_pattern[pos] = - (pix & mask) ? MAGIC_T1H_400KHz : MAGIC_T0H_400KHz; - } else -#endif - { - pixels_pattern[pos] = (pix & mask) ? MAGIC_T1H : MAGIC_T0H; - } - - pos++; - } - } - - // Zero padding to indicate the end of que sequence - pixels_pattern[pos++] = 0 | (0x8000); // Seq end - pixels_pattern[pos++] = 0 | (0x8000); // Seq end - - // Set the wave mode to count UP - pwm->MODE = (PWM_MODE_UPDOWN_Up << PWM_MODE_UPDOWN_Pos); - - // Set the PWM to use the 16MHz clock - pwm->PRESCALER = - (PWM_PRESCALER_PRESCALER_DIV_1 << PWM_PRESCALER_PRESCALER_Pos); - - // Setting of the maximum count - // but keeping it on 16Mhz allows for more granularity just - // in case someone wants to do more fine-tuning of the timing. -#if defined(NEO_KHZ400) - if (!is800KHz) { - pwm->COUNTERTOP = (CTOPVAL_400KHz << PWM_COUNTERTOP_COUNTERTOP_Pos); - } else -#endif - { - pwm->COUNTERTOP = (CTOPVAL << PWM_COUNTERTOP_COUNTERTOP_Pos); - } - - // Disable loops, we want the sequence to repeat only once - pwm->LOOP = (PWM_LOOP_CNT_Disabled << PWM_LOOP_CNT_Pos); - - // On the "Common" setting the PWM uses the same pattern for the - // for supported sequences. The pattern is stored on half-word - // of 16bits - pwm->DECODER = (PWM_DECODER_LOAD_Common << PWM_DECODER_LOAD_Pos) | - (PWM_DECODER_MODE_RefreshCount << PWM_DECODER_MODE_Pos); - - // Pointer to the memory storing the patter - pwm->SEQ[0].PTR = (uint32_t)(pixels_pattern) << PWM_SEQ_PTR_PTR_Pos; - - // Calculation of the number of steps loaded from memory. - pwm->SEQ[0].CNT = (pattern_size / sizeof(uint16_t)) << PWM_SEQ_CNT_CNT_Pos; - - // The following settings are ignored with the current config. - pwm->SEQ[0].REFRESH = 0; - pwm->SEQ[0].ENDDELAY = 0; - - // The Neopixel implementation is a blocking algorithm. DMA - // allows for non-blocking operation. To "simulate" a blocking - // operation we enable the interruption for the end of sequence - // and block the execution thread until the event flag is set by - // the peripheral. - // pwm->INTEN |= (PWM_INTEN_SEQEND0_Enabled<PSEL.OUT[0] = g_APinDescription[pin].name; -#else - pwm->PSEL.OUT[0] = g_ADigitalPinMap[pin]; -#endif - - // Enable the PWM - pwm->ENABLE = 1; - - // After all of this and many hours of reading the documentation - // we are ready to start the sequence... - pwm->EVENTS_SEQEND[0] = 0; - pwm->TASKS_SEQSTART[0] = 1; - - // But we have to wait for the flag to be set. - while (!pwm->EVENTS_SEQEND[0]) { -#if defined(ARDUINO_NRF52_ADAFRUIT) || defined(ARDUINO_ARCH_NRF52840) - yield(); -#endif - } - - // Before leave we clear the flag for the event. - pwm->EVENTS_SEQEND[0] = 0; - - // We need to disable the device and disconnect - // all the outputs before leave or the device will not - // be selected on the next call. - // TODO: Check if disabling the device causes performance issues. - pwm->ENABLE = 0; - - pwm->PSEL.OUT[0] = 0xFFFFFFFFUL; - -#if defined(ARDUINO_NRF52_ADAFRUIT) // use thread-safe free - rtos_free(pixels_pattern); -#else - free(pixels_pattern); -#endif - } // End of DMA implementation - // --------------------------------------------------------------------- - else { -#ifndef ARDUINO_ARCH_NRF52840 -// Fall back to DWT -#if defined(ARDUINO_NRF52_ADAFRUIT) - // Bluefruit Feather 52 uses freeRTOS - // Critical Section is used since it does not block SoftDevice execution - taskENTER_CRITICAL(); -#elif defined(NRF52_DISABLE_INT) - // If you are using the Bluetooth SoftDevice we advise you to not disable - // the interrupts. Disabling the interrupts even for short periods of time - // causes the SoftDevice to stop working. - // Disable the interrupts only in cases where you need high performance for - // the LEDs and if you are not using the EasyDMA feature. - __disable_irq(); -#endif - - NRF_GPIO_Type *nrf_port = (NRF_GPIO_Type *)digitalPinToPort(pin); - uint32_t pinMask = digitalPinToBitMask(pin); - - uint32_t CYCLES_X00 = CYCLES_800; - uint32_t CYCLES_X00_T1H = CYCLES_800_T1H; - uint32_t CYCLES_X00_T0H = CYCLES_800_T0H; - -#if defined(NEO_KHZ400) - if (!is800KHz) { - CYCLES_X00 = CYCLES_400; - CYCLES_X00_T1H = CYCLES_400_T1H; - CYCLES_X00_T0H = CYCLES_400_T0H; - } -#endif - - // Enable DWT in debug core - CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; - DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; - - // Tries to re-send the frame if is interrupted by the SoftDevice. - while (1) { - uint8_t *p = pixels; - - uint32_t cycStart = DWT->CYCCNT; - uint32_t cyc = 0; - - for (uint16_t n = 0; n < numBytes; n++) { - uint8_t pix = *p++; - - for (uint8_t mask = 0x80; mask; mask >>= 1) { - while (DWT->CYCCNT - cyc < CYCLES_X00) - ; - cyc = DWT->CYCCNT; - - nrf_port->OUTSET |= pinMask; - - if (pix & mask) { - while (DWT->CYCCNT - cyc < CYCLES_X00_T1H) - ; - } else { - while (DWT->CYCCNT - cyc < CYCLES_X00_T0H) - ; - } - - nrf_port->OUTCLR |= pinMask; - } - } - while (DWT->CYCCNT - cyc < CYCLES_X00) - ; - - // If total time longer than 25%, resend the whole data. - // Since we are likely to be interrupted by SoftDevice - if ((DWT->CYCCNT - cycStart) < (8 * numBytes * ((CYCLES_X00 * 5) / 4))) { - break; - } - - // re-send need 300us delay - delayMicroseconds(300); - } - -// Enable interrupts again -#if defined(ARDUINO_NRF52_ADAFRUIT) - taskEXIT_CRITICAL(); -#elif defined(NRF52_DISABLE_INT) - __enable_irq(); -#endif -#endif - } - // END of NRF52 implementation - -#elif defined(__SAMD21E17A__) || defined(__SAMD21G18A__) || \ - defined(__SAMD21E18A__) || defined(__SAMD21J18A__) || \ - defined (__SAMD11C14A__) - // Arduino Zero, Gemma/Trinket M0, SODAQ Autonomo - // and others - // Tried this with a timer/counter, couldn't quite get adequate - // resolution. So yay, you get a load of goofball NOPs... - - uint8_t *ptr, *end, p, bitMask, portNum; - uint32_t pinMask; - - portNum = g_APinDescription[pin].ulPort; - pinMask = 1ul << g_APinDescription[pin].ulPin; - ptr = pixels; - end = ptr + numBytes; - p = *ptr++; - bitMask = 0x80; - - volatile uint32_t *set = &(PORT->Group[portNum].OUTSET.reg), - *clr = &(PORT->Group[portNum].OUTCLR.reg); - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - for (;;) { - *set = pinMask; - asm("nop; nop; nop; nop; nop; nop; nop; nop;"); - if (p & bitMask) { - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop;"); - *clr = pinMask; - } else { - *clr = pinMask; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop;"); - } - if (bitMask >>= 1) { - asm("nop; nop; nop; nop; nop; nop; nop; nop; nop;"); - } else { - if (ptr >= end) - break; - p = *ptr++; - bitMask = 0x80; - } - } -#if defined(NEO_KHZ400) - } else { // 400 KHz bitstream - for (;;) { - *set = pinMask; - asm("nop; nop; nop; nop; nop; nop; nop; nop; nop; nop; nop;"); - if (p & bitMask) { - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop;"); - *clr = pinMask; - } else { - *clr = pinMask; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop;"); - } - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;"); - if (bitMask >>= 1) { - asm("nop; nop; nop; nop; nop; nop; nop;"); - } else { - if (ptr >= end) - break; - p = *ptr++; - bitMask = 0x80; - } - } - } -#endif - -//---- -#elif defined(XMC1100_XMC2GO) || defined(XMC1100_H_BRIDGE2GO) || defined(XMC1100_Boot_Kit) || defined(XMC1300_Boot_Kit) - - // XMC1100/1200/1300 with ARM Cortex M0 are running with 32MHz, XMC1400 runs with 48MHz so may not work - // Tried this with a timer/counter, couldn't quite get adequate - // resolution. So yay, you get a load of goofball NOPs... - - uint8_t *ptr, *end, p, bitMask, portNum; - uint32_t pinMask; - - ptr = pixels; - end = ptr + numBytes; - p = *ptr++; - bitMask = 0x80; - - XMC_GPIO_PORT_t* XMC_port = mapping_port_pin[ pin ].port; - uint8_t XMC_pin = mapping_port_pin[ pin ].pin; - - uint32_t omrhigh = (uint32_t)XMC_GPIO_OUTPUT_LEVEL_HIGH << XMC_pin; - uint32_t omrlow = (uint32_t)XMC_GPIO_OUTPUT_LEVEL_LOW << XMC_pin; - -#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled - if(is800KHz) { -#endif - for(;;) { - XMC_port->OMR = omrhigh; - asm("nop; nop; nop; nop;"); - if(p & bitMask) { - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop;"); - XMC_port->OMR = omrlow; - } else { - XMC_port->OMR = omrlow; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop;"); - } - if(bitMask >>= 1) { - asm("nop; nop; nop; nop; nop;"); - } else { - if(ptr >= end) break; - p = *ptr++; - bitMask = 0x80; - } - } -#ifdef NEO_KHZ400 // untested code - } else { // 400 KHz bitstream - for(;;) { - XMC_port->OMR = omrhigh; - asm("nop; nop; nop; nop; nop;"); - if(p & bitMask) { - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop;"); - XMC_port->OMR = omrlow; - } else { - XMC_port->OMR = omrlow; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop;"); - } - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;"); - if(bitMask >>= 1) { - asm("nop; nop; nop;"); - } else { - if(ptr >= end) break; - p = *ptr++; - bitMask = 0x80; - } - } - } - -#endif -//---- - -//---- -#elif defined(XMC4700_Relax_Kit) || defined(XMC4800_Relax_Kit) - -// XMC4700 and XMC4800 with ARM Cortex M4 are running with 144MHz -// Tried this with a timer/counter, couldn't quite get adequate -// resolution. So yay, you get a load of goofball NOPs... - -uint8_t *ptr, *end, p, bitMask, portNum; -uint32_t pinMask; - -ptr = pixels; -end = ptr + numBytes; -p = *ptr++; -bitMask = 0x80; - -XMC_GPIO_PORT_t* XMC_port = mapping_port_pin[ pin ].port; -uint8_t XMC_pin = mapping_port_pin[ pin ].pin; - -uint32_t omrhigh = (uint32_t)XMC_GPIO_OUTPUT_LEVEL_HIGH << XMC_pin; -uint32_t omrlow = (uint32_t)XMC_GPIO_OUTPUT_LEVEL_LOW << XMC_pin; - -#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled -if(is800KHz) { -#endif - - for(;;) { - XMC_port->OMR = omrhigh; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop;"); - if(p & bitMask) { - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;"); - XMC_port->OMR = omrlow; - } else { - XMC_port->OMR = omrlow; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;"); - } - if(bitMask >>= 1) { - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;"); - } else { - if(ptr >= end) break; - p = *ptr++; - bitMask = 0x80; - } - } - - -#ifdef NEO_KHZ400 - } else { // 400 KHz bitstream - // ToDo! - } -#endif -//---- - -#elif defined(__SAMD51__) // M4 - - uint8_t *ptr, *end, p, bitMask, portNum, bit; - uint32_t pinMask; - - portNum = g_APinDescription[pin].ulPort; - pinMask = 1ul << g_APinDescription[pin].ulPin; - ptr = pixels; - end = ptr + numBytes; - p = *ptr++; - bitMask = 0x80; - - volatile uint32_t *set = &(PORT->Group[portNum].OUTSET.reg), - *clr = &(PORT->Group[portNum].OUTCLR.reg); - - // SAMD51 overclock-compatible timing is only a mild abomination. - // It uses SysTick for a consistent clock reference regardless of - // optimization / cache settings. That's the good news. The bad news, - // since SysTick->VAL is a volatile type it's slow to access...and then, - // with the SysTick interval that Arduino sets up (1 ms), this would - // require a subtract and MOD operation for gauging elapsed time, and - // all taken in combination that lacks adequate temporal resolution - // for NeoPixel timing. So a kind of horrible thing is done here... - // since interrupts are turned off anyway and it's generally accepted - // by now that we're gonna lose track of time in the NeoPixel lib, - // the SysTick timer is reconfigured for a period matching the NeoPixel - // bit timing (either 800 or 400 KHz) and we watch SysTick->VAL very - // closely (just a threshold, no subtract or MOD or anything) and that - // seems to work just well enough. When finished, the SysTick - // peripheral is set back to its original state. - - uint32_t t0, t1, top, ticks, saveLoad = SysTick->LOAD, saveVal = SysTick->VAL; - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - top = (uint32_t)(F_CPU * 0.00000125); // Bit hi + lo = 1.25 uS - t0 = top - (uint32_t)(F_CPU * 0.00000040); // 0 = 0.4 uS hi - t1 = top - (uint32_t)(F_CPU * 0.00000080); // 1 = 0.8 uS hi -#if defined(NEO_KHZ400) - } else { // 400 KHz bitstream - top = (uint32_t)(F_CPU * 0.00000250); // Bit hi + lo = 2.5 uS - t0 = top - (uint32_t)(F_CPU * 0.00000050); // 0 = 0.5 uS hi - t1 = top - (uint32_t)(F_CPU * 0.00000120); // 1 = 1.2 uS hi - } -#endif - - SysTick->LOAD = top; // Config SysTick for NeoPixel bit freq - SysTick->VAL = top; // Set to start value (counts down) - (void)SysTick->VAL; // Dummy read helps sync up 1st bit - - for (;;) { - *set = pinMask; // Set output high - ticks = (p & bitMask) ? t1 : t0; // SysTick threshold, - while (SysTick->VAL > ticks) - ; // wait for it - *clr = pinMask; // Set output low - if (!(bitMask >>= 1)) { // Next bit for this byte...done? - if (ptr >= end) - break; // If last byte sent, exit loop - p = *ptr++; // Fetch next byte - bitMask = 0x80; // Reset bitmask - } - while (SysTick->VAL <= ticks) - ; // Wait for rollover to 'top' - } - - SysTick->LOAD = saveLoad; // Restore SysTick rollover to 1 ms - SysTick->VAL = saveVal; // Restore SysTick value - -#elif defined(ARDUINO_STM32_FEATHER) // FEATHER WICED (120MHz) - - // Tried this with a timer/counter, couldn't quite get adequate - // resolution. So yay, you get a load of goofball NOPs... - - uint8_t *ptr, *end, p, bitMask; - uint32_t pinMask; - - pinMask = BIT(PIN_MAP[pin].gpio_bit); - ptr = pixels; - end = ptr + numBytes; - p = *ptr++; - bitMask = 0x80; - - volatile uint16_t *set = &(PIN_MAP[pin].gpio_device->regs->BSRRL); - volatile uint16_t *clr = &(PIN_MAP[pin].gpio_device->regs->BSRRH); - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - for (;;) { - if (p & bitMask) { // ONE - // High 800ns - *set = pinMask; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop;"); - // Low 450ns - *clr = pinMask; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop;"); - } else { // ZERO - // High 400ns - *set = pinMask; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop;"); - // Low 850ns - *clr = pinMask; - asm("nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop; nop; nop; nop; nop;" - "nop; nop; nop; nop;"); - } - if (bitMask >>= 1) { - // Move on to the next pixel - asm("nop;"); - } else { - if (ptr >= end) - break; - p = *ptr++; - bitMask = 0x80; - } - } -#if defined(NEO_KHZ400) - } else { // 400 KHz bitstream - // ToDo! - } -#endif - -#elif defined(TARGET_LPC1768) - uint8_t *ptr, *end, p, bitMask; - ptr = pixels; - end = ptr + numBytes; - p = *ptr++; - bitMask = 0x80; - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - for (;;) { - if (p & bitMask) { - // data ONE high - // min: 550 typ: 700 max: 5,500 - gpio_set(pin); - time::delay_ns(550); - // min: 450 typ: 600 max: 5,000 - gpio_clear(pin); - time::delay_ns(450); - } else { - // data ZERO high - // min: 200 typ: 350 max: 500 - gpio_set(pin); - time::delay_ns(200); - // data low - // min: 450 typ: 600 max: 5,000 - gpio_clear(pin); - time::delay_ns(450); - } - if (bitMask >>= 1) { - // Move on to the next pixel - asm("nop;"); - } else { - if (ptr >= end) - break; - p = *ptr++; - bitMask = 0x80; - } - } -#if defined(NEO_KHZ400) - } else { // 400 KHz bitstream - // ToDo! - } -#endif -#elif defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32) - uint8_t *p = pixels, *end = p + numBytes, pix = *p++, mask = 0x80; - uint32_t cyc; - uint32_t saveLoad = SysTick->LOAD, saveVal = SysTick->VAL; -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - uint32_t top = (F_CPU / 800000); // 1.25µs - uint32_t t0 = top - (F_CPU / 2500000); // 0.4µs - uint32_t t1 = top - (F_CPU / 1250000); // 0.8µs - SysTick->LOAD = top - 1; // Config SysTick for NeoPixel bit freq - SysTick->VAL = 0; // Set to start value - for (;;) { - LL_GPIO_SetOutputPin(gpioPort, gpioPin); - cyc = (pix & mask) ? t1 : t0; - while (SysTick->VAL > cyc) - ; - LL_GPIO_ResetOutputPin(gpioPort, gpioPin); - if (!(mask >>= 1)) { - if (p >= end) - break; - pix = *p++; - mask = 0x80; - } - while (SysTick->VAL <= cyc) - ; - } -#if defined(NEO_KHZ400) - } else { // 400 kHz bitstream - uint32_t top = (F_CPU / 400000); // 2.5µs - uint32_t t0 = top - (F_CPU / 2000000); // 0.5µs - uint32_t t1 = top - (F_CPU / 833333); // 1.2µs - SysTick->LOAD = top - 1; // Config SysTick for NeoPixel bit freq - SysTick->VAL = 0; // Set to start value - for (;;) { - LL_GPIO_SetOutputPin(gpioPort, gpioPin); - cyc = (pix & mask) ? t1 : t0; - while (SysTick->VAL > cyc) - ; - LL_GPIO_ResetOutputPin(gpioPort, gpioPin); - if (!(mask >>= 1)) { - if (p >= end) - break; - pix = *p++; - mask = 0x80; - } - while (SysTick->VAL <= cyc) - ; - } - } -#endif // NEO_KHZ400 - SysTick->LOAD = saveLoad; // Restore SysTick rollover to 1 ms - SysTick->VAL = saveVal; // Restore SysTick value -#elif defined(NRF51) - uint8_t *p = pixels, pix, count, mask; - int32_t num = numBytes; - unsigned int bitmask = (1 << g_ADigitalPinMap[pin]); - // https://github.com/sandeepmistry/arduino-nRF5/blob/dc53980c8bac27898fca90d8ecb268e11111edc1/variants/BBCmicrobit/variant.cpp - - volatile unsigned int *reg = (unsigned int *)(0x50000000UL + 0x508); - - // https://github.com/sandeepmistry/arduino-nRF5/blob/dc53980c8bac27898fca90d8ecb268e11111edc1/cores/nRF5/SDK/components/device/nrf51.h - // http://www.iot-programmer.com/index.php/books/27-micro-bit-iot-in-c/chapters-micro-bit-iot-in-c/47-micro-bit-iot-in-c-fast-memory-mapped-gpio?showall=1 - // https://github.com/Microsoft/pxt-neopixel/blob/master/sendbuffer.asm - - asm volatile( - // "cpsid i" ; disable irq - - // b .start - "b L%=_start" - "\n\t" - // .nextbit: ; C0 - "L%=_nextbit:" - "\n\t" //; C0 - // str r1, [r3, #0] ; pin := hi C2 - "strb %[bitmask], [%[reg], #0]" - "\n\t" //; pin := hi C2 - // tst r6, r0 ; C3 - "tst %[mask], %[pix]" - "\n\t" // ; C3 - // bne .islate ; C4 - "bne L%=_islate" - "\n\t" //; C4 - // str r1, [r2, #0] ; pin := lo C6 - "strb %[bitmask], [%[reg], #4]" - "\n\t" //; pin := lo C6 - // .islate: - "L%=_islate:" - "\n\t" - // lsrs r6, r6, #1 ; r6 >>= 1 C7 - "lsr %[mask], %[mask], #1" - "\n\t" //; r6 >>= 1 C7 - // bne .justbit ; C8 - "bne L%=_justbit" - "\n\t" //; C8 - - // ; not just a bit - need new byte - // adds r4, #1 ; r4++ C9 - "add %[p], #1" - "\n\t" //; r4++ C9 - // subs r5, #1 ; r5-- C10 - "sub %[num], #1" - "\n\t" //; r5-- C10 - // bcc .stop ; if (r5<0) goto .stop C11 - "bcc L%=_stop" - "\n\t" //; if (r5<0) goto .stop C11 - // .start: - "L%=_start:" - // movs r6, #0x80 ; reset mask C12 - "movs %[mask], #0x80" - "\n\t" //; reset mask C12 - // nop ; C13 - "nop" - "\n\t" //; C13 - - // .common: ; C13 - "L%=_common:" - "\n\t" //; C13 - // str r1, [r2, #0] ; pin := lo C15 - "strb %[bitmask], [%[reg], #4]" - "\n\t" //; pin := lo C15 - // ; always re-load byte - it just fits with the cycles better this way - // ldrb r0, [r4, #0] ; r0 := *r4 C17 - "ldrb %[pix], [%[p], #0]" - "\n\t" //; r0 := *r4 C17 - // b .nextbit ; C20 - "b L%=_nextbit" - "\n\t" //; C20 - - // .justbit: ; C10 - "L%=_justbit:" - "\n\t" //; C10 - // ; no nops, branch taken is already 3 cycles - // b .common ; C13 - "b L%=_common" - "\n\t" //; C13 - - // .stop: - "L%=_stop:" - "\n\t" - // str r1, [r2, #0] ; pin := lo - "strb %[bitmask], [%[reg], #4]" - "\n\t" //; pin := lo - // cpsie i ; enable irq - - : [p] "+r"(p), [pix] "=&r"(pix), [count] "=&r"(count), [mask] "=&r"(mask), - [num] "+r"(num) - : [bitmask] "r"(bitmask), [reg] "r"(reg)); - -#elif defined(__SAM3X8E__) // Arduino Due - -#define SCALE VARIANT_MCK / 2UL / 1000000UL -#define INST (2UL * F_CPU / VARIANT_MCK) -#define TIME_800_0 ((int)(0.40 * SCALE + 0.5) - (5 * INST)) -#define TIME_800_1 ((int)(0.80 * SCALE + 0.5) - (5 * INST)) -#define PERIOD_800 ((int)(1.25 * SCALE + 0.5) - (5 * INST)) -#define TIME_400_0 ((int)(0.50 * SCALE + 0.5) - (5 * INST)) -#define TIME_400_1 ((int)(1.20 * SCALE + 0.5) - (5 * INST)) -#define PERIOD_400 ((int)(2.50 * SCALE + 0.5) - (5 * INST)) - - int pinMask, time0, time1, period, t; - Pio *port; - volatile WoReg *portSet, *portClear, *timeValue, *timeReset; - uint8_t *p, *end, pix, mask; - - pmc_set_writeprotect(false); - pmc_enable_periph_clk((uint32_t)TC3_IRQn); - TC_Configure(TC1, 0, - TC_CMR_WAVE | TC_CMR_WAVSEL_UP | TC_CMR_TCCLKS_TIMER_CLOCK1); - TC_Start(TC1, 0); - - pinMask = g_APinDescription[pin].ulPin; // Don't 'optimize' these into - port = g_APinDescription[pin].pPort; // declarations above. Want to - portSet = &(port->PIO_SODR); // burn a few cycles after - portClear = &(port->PIO_CODR); // starting timer to minimize - timeValue = &(TC1->TC_CHANNEL[0].TC_CV); // the initial 'while'. - timeReset = &(TC1->TC_CHANNEL[0].TC_CCR); - p = pixels; - end = p + numBytes; - pix = *p++; - mask = 0x80; - -#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled - if (is800KHz) { -#endif - time0 = TIME_800_0; - time1 = TIME_800_1; - period = PERIOD_800; -#if defined(NEO_KHZ400) - } else { // 400 KHz bitstream - time0 = TIME_400_0; - time1 = TIME_400_1; - period = PERIOD_400; - } -#endif - - for (t = time0;; t = time0) { - if (pix & mask) - t = time1; - while (*timeValue < (unsigned)period) - ; - *portSet = pinMask; - *timeReset = TC_CCR_CLKEN | TC_CCR_SWTRG; - while (*timeValue < (unsigned)t) - ; - *portClear = pinMask; - if (!(mask >>= 1)) { // This 'inside-out' loop logic utilizes - if (p >= end) - break; // idle time to minimize inter-byte delays. - pix = *p++; - mask = 0x80; - } - } - while (*timeValue < (unsigned)period) - ; // Wait for last bit - TC_Stop(TC1, 0); - -#endif // end Due - - // END ARM ---------------------------------------------------------------- - -#elif defined(ESP8266) || defined(ESP32) - - // ESP8266 ---------------------------------------------------------------- - - // ESP8266 show() is external to enforce ICACHE_RAM_ATTR execution - espShow(pin, pixels, numBytes, is800KHz); - -#elif defined(KENDRYTE_K210) - - k210Show(pin, pixels, numBytes, is800KHz); - -#elif defined(__ARDUINO_ARC__) - - // Arduino 101 ----------------------------------------------------------- - -#define NOPx7 \ - { \ - __builtin_arc_nop(); \ - __builtin_arc_nop(); \ - __builtin_arc_nop(); \ - __builtin_arc_nop(); \ - __builtin_arc_nop(); \ - __builtin_arc_nop(); \ - __builtin_arc_nop(); \ - } - - PinDescription *pindesc = &g_APinDescription[pin]; - register uint32_t loop = - 8 * numBytes; // one loop to handle all bytes and all bits - register uint8_t *p = pixels; - register uint32_t currByte = (uint32_t)(*p); - register uint32_t currBit = 0x80 & currByte; - register uint32_t bitCounter = 0; - register uint32_t first = 1; - - // The loop is unusual. Very first iteration puts all the way LOW to the wire - // - constant LOW does not affect NEOPIXEL, so there is no visible effect - // displayed. During that very first iteration CPU caches instructions in the - // loop. Because of the caching process, "CPU slows down". NEOPIXEL pulse is - // very time sensitive that's why we let the CPU cache first and we start - // regular pulse from 2nd iteration - if (pindesc->ulGPIOType == SS_GPIO) { - register uint32_t reg = pindesc->ulGPIOBase + SS_GPIO_SWPORTA_DR; - uint32_t reg_val = __builtin_arc_lr((volatile uint32_t)reg); - register uint32_t reg_bit_high = reg_val | (1 << pindesc->ulGPIOId); - register uint32_t reg_bit_low = reg_val & ~(1 << pindesc->ulGPIOId); - - loop += 1; // include first, special iteration - while (loop--) { - if (!first) { - currByte <<= 1; - bitCounter++; - } - - // 1 is >550ns high and >450ns low; 0 is 200..500ns high and >450ns low - __builtin_arc_sr(first ? reg_bit_low : reg_bit_high, - (volatile uint32_t)reg); - if (currBit) { // ~400ns HIGH (740ns overall) - NOPx7 NOPx7 - } - // ~340ns HIGH - NOPx7 __builtin_arc_nop(); - - // 820ns LOW; per spec, max allowed low here is 5000ns */ - __builtin_arc_sr(reg_bit_low, (volatile uint32_t)reg); - NOPx7 NOPx7 - - if (bitCounter >= 8) { - bitCounter = 0; - currByte = (uint32_t)(*++p); - } - - currBit = 0x80 & currByte; - first = 0; - } - } else if (pindesc->ulGPIOType == SOC_GPIO) { - register uint32_t reg = pindesc->ulGPIOBase + SOC_GPIO_SWPORTA_DR; - uint32_t reg_val = MMIO_REG_VAL(reg); - register uint32_t reg_bit_high = reg_val | (1 << pindesc->ulGPIOId); - register uint32_t reg_bit_low = reg_val & ~(1 << pindesc->ulGPIOId); - - loop += 1; // include first, special iteration - while (loop--) { - if (!first) { - currByte <<= 1; - bitCounter++; - } - MMIO_REG_VAL(reg) = first ? reg_bit_low : reg_bit_high; - if (currBit) { // ~430ns HIGH (740ns overall) - NOPx7 NOPx7 __builtin_arc_nop(); - } - // ~310ns HIGH - NOPx7 - - // 850ns LOW; per spec, max allowed low here is 5000ns */ - MMIO_REG_VAL(reg) = reg_bit_low; - NOPx7 NOPx7 - - if (bitCounter >= 8) { - bitCounter = 0; - currByte = (uint32_t)(*++p); - } - - currBit = 0x80 & currByte; - first = 0; - } - } - -#else -#error Architecture not supported -#endif - - // END ARCHITECTURE SELECT ------------------------------------------------ - -#if !(defined(NRF52) || defined(NRF52_SERIES)) - interrupts(); -#endif - - endTime = micros(); // Save EOD time for latch on next call -} - -/*! - @brief Set/change the NeoPixel output pin number. Previous pin, - if any, is set to INPUT and the new pin is set to OUTPUT. - @param p Arduino pin number (-1 = no pin). -*/ -void Adafruit_NeoPixel::setPin(int16_t p) { - if (begun && (pin >= 0)) - pinMode(pin, INPUT); // Disable existing out pin - pin = p; - if (begun) { - pinMode(p, OUTPUT); - digitalWrite(p, LOW); - } -#if defined(__AVR__) - port = portOutputRegister(digitalPinToPort(p)); - pinMask = digitalPinToBitMask(p); -#endif -#if defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32) - gpioPort = digitalPinToPort(p); - gpioPin = STM_LL_GPIO_PIN(digitalPinToPinName(p)); -#endif -} - -/*! - @brief Set a pixel's color using separate red, green and blue - components. If using RGBW pixels, white will be set to 0. - @param n Pixel index, starting from 0. - @param r Red brightness, 0 = minimum (off), 255 = maximum. - @param g Green brightness, 0 = minimum (off), 255 = maximum. - @param b Blue brightness, 0 = minimum (off), 255 = maximum. -*/ -void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint8_t r, uint8_t g, - uint8_t b) { - - if (n < numLEDs) { - if (brightness) { // See notes in setBrightness() - r = (r * brightness) >> 8; - g = (g * brightness) >> 8; - b = (b * brightness) >> 8; - } - uint8_t *p; - if (wOffset == rOffset) { // Is an RGB-type strip - p = &pixels[n * 3]; // 3 bytes per pixel - } else { // Is a WRGB-type strip - p = &pixels[n * 4]; // 4 bytes per pixel - p[wOffset] = 0; // But only R,G,B passed -- set W to 0 - } - p[rOffset] = r; // R,G,B always stored - p[gOffset] = g; - p[bOffset] = b; - } -} - -/*! - @brief Set a pixel's color using separate red, green, blue and white - components (for RGBW NeoPixels only). - @param n Pixel index, starting from 0. - @param r Red brightness, 0 = minimum (off), 255 = maximum. - @param g Green brightness, 0 = minimum (off), 255 = maximum. - @param b Blue brightness, 0 = minimum (off), 255 = maximum. - @param w White brightness, 0 = minimum (off), 255 = maximum, ignored - if using RGB pixels. -*/ -void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint8_t r, uint8_t g, - uint8_t b, uint8_t w) { - - if (n < numLEDs) { - if (brightness) { // See notes in setBrightness() - r = (r * brightness) >> 8; - g = (g * brightness) >> 8; - b = (b * brightness) >> 8; - w = (w * brightness) >> 8; - } - uint8_t *p; - if (wOffset == rOffset) { // Is an RGB-type strip - p = &pixels[n * 3]; // 3 bytes per pixel (ignore W) - } else { // Is a WRGB-type strip - p = &pixels[n * 4]; // 4 bytes per pixel - p[wOffset] = w; // Store W - } - p[rOffset] = r; // Store R,G,B - p[gOffset] = g; - p[bOffset] = b; - } -} - -/*! - @brief Set a pixel's color using a 32-bit 'packed' RGB or RGBW value. - @param n Pixel index, starting from 0. - @param c 32-bit color value. Most significant byte is white (for RGBW - pixels) or ignored (for RGB pixels), next is red, then green, - and least significant byte is blue. -*/ -void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint32_t c) { - if (n < numLEDs) { - uint8_t *p, r = (uint8_t)(c >> 16), g = (uint8_t)(c >> 8), b = (uint8_t)c; - if (brightness) { // See notes in setBrightness() - r = (r * brightness) >> 8; - g = (g * brightness) >> 8; - b = (b * brightness) >> 8; - } - if (wOffset == rOffset) { - p = &pixels[n * 3]; - } else { - p = &pixels[n * 4]; - uint8_t w = (uint8_t)(c >> 24); - p[wOffset] = brightness ? ((w * brightness) >> 8) : w; - } - p[rOffset] = r; - p[gOffset] = g; - p[bOffset] = b; - } -} - -/*! - @brief Fill all or part of the NeoPixel strip with a color. - @param c 32-bit color value. Most significant byte is white (for - RGBW pixels) or ignored (for RGB pixels), next is red, - then green, and least significant byte is blue. If all - arguments are unspecified, this will be 0 (off). - @param first Index of first pixel to fill, starting from 0. Must be - in-bounds, no clipping is performed. 0 if unspecified. - @param count Number of pixels to fill, as a positive value. Passing - 0 or leaving unspecified will fill to end of strip. -*/ -void Adafruit_NeoPixel::fill(uint32_t c, uint16_t first, uint16_t count) { - uint16_t i, end; - - if (first >= numLEDs) { - return; // If first LED is past end of strip, nothing to do - } - - // Calculate the index ONE AFTER the last pixel to fill - if (count == 0) { - // Fill to end of strip - end = numLEDs; - } else { - // Ensure that the loop won't go past the last pixel - end = first + count; - if (end > numLEDs) - end = numLEDs; - } - - for (i = first; i < end; i++) { - this->setPixelColor(i, c); - } -} - -/*! - @brief Convert hue, saturation and value into a packed 32-bit RGB color - that can be passed to setPixelColor() or other RGB-compatible - functions. - @param hue An unsigned 16-bit value, 0 to 65535, representing one full - loop of the color wheel, which allows 16-bit hues to "roll - over" while still doing the expected thing (and allowing - more precision than the wheel() function that was common to - prior NeoPixel examples). - @param sat Saturation, 8-bit value, 0 (min or pure grayscale) to 255 - (max or pure hue). Default of 255 if unspecified. - @param val Value (brightness), 8-bit value, 0 (min / black / off) to - 255 (max or full brightness). Default of 255 if unspecified. - @return Packed 32-bit RGB with the most significant byte set to 0 -- the - white element of WRGB pixels is NOT utilized. Result is linearly - but not perceptually correct, so you may want to pass the result - through the gamma32() function (or your own gamma-correction - operation) else colors may appear washed out. This is not done - automatically by this function because coders may desire a more - refined gamma-correction function than the simplified - one-size-fits-all operation of gamma32(). Diffusing the LEDs also - really seems to help when using low-saturation colors. -*/ -uint32_t Adafruit_NeoPixel::ColorHSV(uint16_t hue, uint8_t sat, uint8_t val) { - - uint8_t r, g, b; - - // Remap 0-65535 to 0-1529. Pure red is CENTERED on the 64K rollover; - // 0 is not the start of pure red, but the midpoint...a few values above - // zero and a few below 65536 all yield pure red (similarly, 32768 is the - // midpoint, not start, of pure cyan). The 8-bit RGB hexcone (256 values - // each for red, green, blue) really only allows for 1530 distinct hues - // (not 1536, more on that below), but the full unsigned 16-bit type was - // chosen for hue so that one's code can easily handle a contiguous color - // wheel by allowing hue to roll over in either direction. - hue = (hue * 1530L + 32768) / 65536; - // Because red is centered on the rollover point (the +32768 above, - // essentially a fixed-point +0.5), the above actually yields 0 to 1530, - // where 0 and 1530 would yield the same thing. Rather than apply a - // costly modulo operator, 1530 is handled as a special case below. - - // So you'd think that the color "hexcone" (the thing that ramps from - // pure red, to pure yellow, to pure green and so forth back to red, - // yielding six slices), and with each color component having 256 - // possible values (0-255), might have 1536 possible items (6*256), - // but in reality there's 1530. This is because the last element in - // each 256-element slice is equal to the first element of the next - // slice, and keeping those in there this would create small - // discontinuities in the color wheel. So the last element of each - // slice is dropped...we regard only elements 0-254, with item 255 - // being picked up as element 0 of the next slice. Like this: - // Red to not-quite-pure-yellow is: 255, 0, 0 to 255, 254, 0 - // Pure yellow to not-quite-pure-green is: 255, 255, 0 to 1, 255, 0 - // Pure green to not-quite-pure-cyan is: 0, 255, 0 to 0, 255, 254 - // and so forth. Hence, 1530 distinct hues (0 to 1529), and hence why - // the constants below are not the multiples of 256 you might expect. - - // Convert hue to R,G,B (nested ifs faster than divide+mod+switch): - if (hue < 510) { // Red to Green-1 - b = 0; - if (hue < 255) { // Red to Yellow-1 - r = 255; - g = hue; // g = 0 to 254 - } else { // Yellow to Green-1 - r = 510 - hue; // r = 255 to 1 - g = 255; - } - } else if (hue < 1020) { // Green to Blue-1 - r = 0; - if (hue < 765) { // Green to Cyan-1 - g = 255; - b = hue - 510; // b = 0 to 254 - } else { // Cyan to Blue-1 - g = 1020 - hue; // g = 255 to 1 - b = 255; - } - } else if (hue < 1530) { // Blue to Red-1 - g = 0; - if (hue < 1275) { // Blue to Magenta-1 - r = hue - 1020; // r = 0 to 254 - b = 255; - } else { // Magenta to Red-1 - r = 255; - b = 1530 - hue; // b = 255 to 1 - } - } else { // Last 0.5 Red (quicker than % operator) - r = 255; - g = b = 0; - } - - // Apply saturation and value to R,G,B, pack into 32-bit result: - uint32_t v1 = 1 + val; // 1 to 256; allows >>8 instead of /255 - uint16_t s1 = 1 + sat; // 1 to 256; same reason - uint8_t s2 = 255 - sat; // 255 to 0 - return ((((((r * s1) >> 8) + s2) * v1) & 0xff00) << 8) | - (((((g * s1) >> 8) + s2) * v1) & 0xff00) | - (((((b * s1) >> 8) + s2) * v1) >> 8); -} - -/*! - @brief Query the color of a previously-set pixel. - @param n Index of pixel to read (0 = first). - @return 'Packed' 32-bit RGB or WRGB value. Most significant byte is white - (for RGBW pixels) or 0 (for RGB pixels), next is red, then green, - and least significant byte is blue. - @note If the strip brightness has been changed from the default value - of 255, the color read from a pixel may not exactly match what - was previously written with one of the setPixelColor() functions. - This gets more pronounced at lower brightness levels. -*/ -uint32_t Adafruit_NeoPixel::getPixelColor(uint16_t n) const { - if (n >= numLEDs) - return 0; // Out of bounds, return no color. - - uint8_t *p; - - if (wOffset == rOffset) { // Is RGB-type device - p = &pixels[n * 3]; - if (brightness) { - // Stored color was decimated by setBrightness(). Returned value - // attempts to scale back to an approximation of the original 24-bit - // value used when setting the pixel color, but there will always be - // some error -- those bits are simply gone. Issue is most - // pronounced at low brightness levels. - return (((uint32_t)(p[rOffset] << 8) / brightness) << 16) | - (((uint32_t)(p[gOffset] << 8) / brightness) << 8) | - ((uint32_t)(p[bOffset] << 8) / brightness); - } else { - // No brightness adjustment has been made -- return 'raw' color - return ((uint32_t)p[rOffset] << 16) | ((uint32_t)p[gOffset] << 8) | - (uint32_t)p[bOffset]; - } - } else { // Is RGBW-type device - p = &pixels[n * 4]; - if (brightness) { // Return scaled color - return (((uint32_t)(p[wOffset] << 8) / brightness) << 24) | - (((uint32_t)(p[rOffset] << 8) / brightness) << 16) | - (((uint32_t)(p[gOffset] << 8) / brightness) << 8) | - ((uint32_t)(p[bOffset] << 8) / brightness); - } else { // Return raw color - return ((uint32_t)p[wOffset] << 24) | ((uint32_t)p[rOffset] << 16) | - ((uint32_t)p[gOffset] << 8) | (uint32_t)p[bOffset]; - } - } -} - -/*! - @brief Adjust output brightness. Does not immediately affect what's - currently displayed on the LEDs. The next call to show() will - refresh the LEDs at this level. - @param b Brightness setting, 0=minimum (off), 255=brightest. - @note This was intended for one-time use in one's setup() function, - not as an animation effect in itself. Because of the way this - library "pre-multiplies" LED colors in RAM, changing the - brightness is often a "lossy" operation -- what you write to - pixels isn't necessary the same as what you'll read back. - Repeated brightness changes using this function exacerbate the - problem. Smart programs therefore treat the strip as a - write-only resource, maintaining their own state to render each - frame of an animation, not relying on read-modify-write. -*/ -void Adafruit_NeoPixel::setBrightness(uint8_t b) { - // Stored brightness value is different than what's passed. - // This simplifies the actual scaling math later, allowing a fast - // 8x8-bit multiply and taking the MSB. 'brightness' is a uint8_t, - // adding 1 here may (intentionally) roll over...so 0 = max brightness - // (color values are interpreted literally; no scaling), 1 = min - // brightness (off), 255 = just below max brightness. - uint8_t newBrightness = b + 1; - if (newBrightness != brightness) { // Compare against prior value - // Brightness has changed -- re-scale existing data in RAM, - // This process is potentially "lossy," especially when increasing - // brightness. The tight timing in the WS2811/WS2812 code means there - // aren't enough free cycles to perform this scaling on the fly as data - // is issued. So we make a pass through the existing color data in RAM - // and scale it (subsequent graphics commands also work at this - // brightness level). If there's a significant step up in brightness, - // the limited number of steps (quantization) in the old data will be - // quite visible in the re-scaled version. For a non-destructive - // change, you'll need to re-render the full strip data. C'est la vie. - uint8_t c, *ptr = pixels, - oldBrightness = brightness - 1; // De-wrap old brightness value - uint16_t scale; - if (oldBrightness == 0) - scale = 0; // Avoid /0 - else if (b == 255) - scale = 65535 / oldBrightness; - else - scale = (((uint16_t)newBrightness << 8) - 1) / oldBrightness; - for (uint16_t i = 0; i < numBytes; i++) { - c = *ptr; - *ptr++ = (c * scale) >> 8; - } - brightness = newBrightness; - } -} - -/*! - @brief Retrieve the last-set brightness value for the strip. - @return Brightness value: 0 = minimum (off), 255 = maximum. -*/ -uint8_t Adafruit_NeoPixel::getBrightness(void) const { return brightness - 1; } - -/*! - @brief Fill the whole NeoPixel strip with 0 / black / off. -*/ -void Adafruit_NeoPixel::clear(void) { memset(pixels, 0, numBytes); } - -// A 32-bit variant of gamma8() that applies the same function -// to all components of a packed RGB or WRGB value. -uint32_t Adafruit_NeoPixel::gamma32(uint32_t x) { - uint8_t *y = (uint8_t *)&x; - // All four bytes of a 32-bit value are filtered even if RGB (not WRGB), - // to avoid a bunch of shifting and masking that would be necessary for - // properly handling different endianisms (and each byte is a fairly - // trivial operation, so it might not even be wasting cycles vs a check - // and branch for the RGB case). In theory this might cause trouble *if* - // someone's storing information in the unused most significant byte - // of an RGB value, but this seems exceedingly rare and if it's - // encountered in reality they can mask values going in or coming out. - for (uint8_t i = 0; i < 4; i++) - y[i] = gamma8(y[i]); - return x; // Packed 32-bit return -} - -/*! - @brief Fill NeoPixel strip with one or more cycles of hues. - Everyone loves the rainbow swirl so much, now it's canon! - @param first_hue Hue of first pixel, 0-65535, representing one full - cycle of the color wheel. Each subsequent pixel will - be offset to complete one or more cycles over the - length of the strip. - @param reps Number of cycles of the color wheel over the length - of the strip. Default is 1. Negative values can be - used to reverse the hue order. - @param saturation Saturation (optional), 0-255 = gray to pure hue, - default = 255. - @param brightness Brightness/value (optional), 0-255 = off to max, - default = 255. This is distinct and in combination - with any configured global strip brightness. - @param gammify If true (default), apply gamma correction to colors - for better appearance. -*/ -void Adafruit_NeoPixel::rainbow(uint16_t first_hue, int8_t reps, - uint8_t saturation, uint8_t brightness, bool gammify) { - for (uint16_t i=0; i. - * - */ - -#ifndef ADAFRUIT_NEOPIXEL_H -#define ADAFRUIT_NEOPIXEL_H - -#ifdef ARDUINO -#if (ARDUINO >= 100) -#include -#else -#include -#include -#endif - -#ifdef USE_TINYUSB // For Serial when selecting TinyUSB -#include -#endif - -#endif - -#ifdef TARGET_LPC1768 -#include -#endif - -#if defined(ARDUINO_ARCH_RP2040) -#include -#include "hardware/pio.h" -#include "hardware/clocks.h" -#include "rp2040_pio.h" -#endif - -// The order of primary colors in the NeoPixel data stream can vary among -// device types, manufacturers and even different revisions of the same -// item. The third parameter to the Adafruit_NeoPixel constructor encodes -// the per-pixel byte offsets of the red, green and blue primaries (plus -// white, if present) in the data stream -- the following #defines provide -// an easier-to-use named version for each permutation. e.g. NEO_GRB -// indicates a NeoPixel-compatible device expecting three bytes per pixel, -// with the first byte transmitted containing the green value, second -// containing red and third containing blue. The in-memory representation -// of a chain of NeoPixels is the same as the data-stream order; no -// re-ordering of bytes is required when issuing data to the chain. -// Most of these values won't exist in real-world devices, but it's done -// this way so we're ready for it (also, if using the WS2811 driver IC, -// one might have their pixels set up in any weird permutation). - -// Bits 5,4 of this value are the offset (0-3) from the first byte of a -// pixel to the location of the red color byte. Bits 3,2 are the green -// offset and 1,0 are the blue offset. If it is an RGBW-type device -// (supporting a white primary in addition to R,G,B), bits 7,6 are the -// offset to the white byte...otherwise, bits 7,6 are set to the same value -// as 5,4 (red) to indicate an RGB (not RGBW) device. -// i.e. binary representation: -// 0bWWRRGGBB for RGBW devices -// 0bRRRRGGBB for RGB - -// RGB NeoPixel permutations; white and red offsets are always same -// Offset: W R G B -#define NEO_RGB ((0 << 6) | (0 << 4) | (1 << 2) | (2)) ///< Transmit as R,G,B -#define NEO_RBG ((0 << 6) | (0 << 4) | (2 << 2) | (1)) ///< Transmit as R,B,G -#define NEO_GRB ((1 << 6) | (1 << 4) | (0 << 2) | (2)) ///< Transmit as G,R,B -#define NEO_GBR ((2 << 6) | (2 << 4) | (0 << 2) | (1)) ///< Transmit as G,B,R -#define NEO_BRG ((1 << 6) | (1 << 4) | (2 << 2) | (0)) ///< Transmit as B,R,G -#define NEO_BGR ((2 << 6) | (2 << 4) | (1 << 2) | (0)) ///< Transmit as B,G,R - -// RGBW NeoPixel permutations; all 4 offsets are distinct -// Offset: W R G B -#define NEO_WRGB ((0 << 6) | (1 << 4) | (2 << 2) | (3)) ///< Transmit as W,R,G,B -#define NEO_WRBG ((0 << 6) | (1 << 4) | (3 << 2) | (2)) ///< Transmit as W,R,B,G -#define NEO_WGRB ((0 << 6) | (2 << 4) | (1 << 2) | (3)) ///< Transmit as W,G,R,B -#define NEO_WGBR ((0 << 6) | (3 << 4) | (1 << 2) | (2)) ///< Transmit as W,G,B,R -#define NEO_WBRG ((0 << 6) | (2 << 4) | (3 << 2) | (1)) ///< Transmit as W,B,R,G -#define NEO_WBGR ((0 << 6) | (3 << 4) | (2 << 2) | (1)) ///< Transmit as W,B,G,R - -#define NEO_RWGB ((1 << 6) | (0 << 4) | (2 << 2) | (3)) ///< Transmit as R,W,G,B -#define NEO_RWBG ((1 << 6) | (0 << 4) | (3 << 2) | (2)) ///< Transmit as R,W,B,G -#define NEO_RGWB ((2 << 6) | (0 << 4) | (1 << 2) | (3)) ///< Transmit as R,G,W,B -#define NEO_RGBW ((3 << 6) | (0 << 4) | (1 << 2) | (2)) ///< Transmit as R,G,B,W -#define NEO_RBWG ((2 << 6) | (0 << 4) | (3 << 2) | (1)) ///< Transmit as R,B,W,G -#define NEO_RBGW ((3 << 6) | (0 << 4) | (2 << 2) | (1)) ///< Transmit as R,B,G,W - -#define NEO_GWRB ((1 << 6) | (2 << 4) | (0 << 2) | (3)) ///< Transmit as G,W,R,B -#define NEO_GWBR ((1 << 6) | (3 << 4) | (0 << 2) | (2)) ///< Transmit as G,W,B,R -#define NEO_GRWB ((2 << 6) | (1 << 4) | (0 << 2) | (3)) ///< Transmit as G,R,W,B -#define NEO_GRBW ((3 << 6) | (1 << 4) | (0 << 2) | (2)) ///< Transmit as G,R,B,W -#define NEO_GBWR ((2 << 6) | (3 << 4) | (0 << 2) | (1)) ///< Transmit as G,B,W,R -#define NEO_GBRW ((3 << 6) | (2 << 4) | (0 << 2) | (1)) ///< Transmit as G,B,R,W - -#define NEO_BWRG ((1 << 6) | (2 << 4) | (3 << 2) | (0)) ///< Transmit as B,W,R,G -#define NEO_BWGR ((1 << 6) | (3 << 4) | (2 << 2) | (0)) ///< Transmit as B,W,G,R -#define NEO_BRWG ((2 << 6) | (1 << 4) | (3 << 2) | (0)) ///< Transmit as B,R,W,G -#define NEO_BRGW ((3 << 6) | (1 << 4) | (2 << 2) | (0)) ///< Transmit as B,R,G,W -#define NEO_BGWR ((2 << 6) | (3 << 4) | (1 << 2) | (0)) ///< Transmit as B,G,W,R -#define NEO_BGRW ((3 << 6) | (2 << 4) | (1 << 2) | (0)) ///< Transmit as B,G,R,W - -// Add NEO_KHZ400 to the color order value to indicate a 400 KHz device. -// All but the earliest v1 NeoPixels expect an 800 KHz data stream, this is -// the default if unspecified. Because flash space is very limited on ATtiny -// devices (e.g. Trinket, Gemma), v1 NeoPixels aren't handled by default on -// those chips, though it can be enabled by removing the ifndef/endif below, -// but code will be bigger. Conversely, can disable the NEO_KHZ400 line on -// other MCUs to remove v1 support and save a little space. - -#define NEO_KHZ800 0x0000 ///< 800 KHz data transmission -#ifndef __AVR_ATtiny85__ -#define NEO_KHZ400 0x0100 ///< 400 KHz data transmission -#endif - -// If 400 KHz support is enabled, the third parameter to the constructor -// requires a 16-bit value (in order to select 400 vs 800 KHz speed). -// If only 800 KHz is enabled (as is default on ATtiny), an 8-bit value -// is sufficient to encode pixel color order, saving some space. - -#ifdef NEO_KHZ400 -typedef uint16_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor -#else -typedef uint8_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor -#endif - -// These two tables are declared outside the Adafruit_NeoPixel class -// because some boards may require oldschool compilers that don't -// handle the C++11 constexpr keyword. - -/* A PROGMEM (flash mem) table containing 8-bit unsigned sine wave (0-255). - Copy & paste this snippet into a Python REPL to regenerate: -import math -for x in range(256): - print("{:3},".format(int((math.sin(x/128.0*math.pi)+1.0)*127.5+0.5))), - if x&15 == 15: print -*/ -static const uint8_t PROGMEM _NeoPixelSineTable[256] = { - 128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 162, 165, 167, 170, - 173, 176, 179, 182, 185, 188, 190, 193, 196, 198, 201, 203, 206, 208, 211, - 213, 215, 218, 220, 222, 224, 226, 228, 230, 232, 234, 235, 237, 238, 240, - 241, 243, 244, 245, 246, 248, 249, 250, 250, 251, 252, 253, 253, 254, 254, - 254, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 252, 251, - 250, 250, 249, 248, 246, 245, 244, 243, 241, 240, 238, 237, 235, 234, 232, - 230, 228, 226, 224, 222, 220, 218, 215, 213, 211, 208, 206, 203, 201, 198, - 196, 193, 190, 188, 185, 182, 179, 176, 173, 170, 167, 165, 162, 158, 155, - 152, 149, 146, 143, 140, 137, 134, 131, 128, 124, 121, 118, 115, 112, 109, - 106, 103, 100, 97, 93, 90, 88, 85, 82, 79, 76, 73, 70, 67, 65, - 62, 59, 57, 54, 52, 49, 47, 44, 42, 40, 37, 35, 33, 31, 29, - 27, 25, 23, 21, 20, 18, 17, 15, 14, 12, 11, 10, 9, 7, 6, - 5, 5, 4, 3, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 9, 10, 11, - 12, 14, 15, 17, 18, 20, 21, 23, 25, 27, 29, 31, 33, 35, 37, - 40, 42, 44, 47, 49, 52, 54, 57, 59, 62, 65, 67, 70, 73, 76, - 79, 82, 85, 88, 90, 93, 97, 100, 103, 106, 109, 112, 115, 118, 121, - 124}; - -/* Similar to above, but for an 8-bit gamma-correction table. - Copy & paste this snippet into a Python REPL to regenerate: -import math -gamma=2.6 -for x in range(256): - print("{:3},".format(int(math.pow((x)/255.0,gamma)*255.0+0.5))), - if x&15 == 15: print -*/ -static const uint8_t PROGMEM _NeoPixelGammaTable[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, - 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, - 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, - 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, - 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25, - 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 34, 34, 35, - 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 68, 69, 70, 71, 72, 73, 75, 76, 77, 78, 80, 81, - 82, 84, 85, 86, 88, 89, 90, 92, 93, 94, 96, 97, 99, 100, 102, - 103, 105, 106, 108, 109, 111, 112, 114, 115, 117, 119, 120, 122, 124, 125, - 127, 129, 130, 132, 134, 136, 137, 139, 141, 143, 145, 146, 148, 150, 152, - 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, - 184, 186, 188, 191, 193, 195, 197, 199, 202, 204, 206, 209, 211, 213, 215, - 218, 220, 223, 225, 227, 230, 232, 235, 237, 240, 242, 245, 247, 250, 252, - 255}; - -/*! - @brief Class that stores state and functions for interacting with - Adafruit NeoPixels and compatible devices. -*/ -class Adafruit_NeoPixel { - -public: - // Constructor: number of LEDs, pin number, LED type - Adafruit_NeoPixel(uint16_t n, int16_t pin = 6, - neoPixelType type = NEO_GRB + NEO_KHZ800); - Adafruit_NeoPixel(void); - ~Adafruit_NeoPixel(); - - void begin(void); - void show(void); - void setPin(int16_t p); - void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b); - void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w); - void setPixelColor(uint16_t n, uint32_t c); - void fill(uint32_t c = 0, uint16_t first = 0, uint16_t count = 0); - void setBrightness(uint8_t); - void clear(void); - void updateLength(uint16_t n); - void updateType(neoPixelType t); - /*! - @brief Check whether a call to show() will start sending data - immediately or will 'block' for a required interval. NeoPixels - require a short quiet time (about 300 microseconds) after the - last bit is received before the data 'latches' and new data can - start being received. Usually one's sketch is implicitly using - this time to generate a new frame of animation...but if it - finishes very quickly, this function could be used to see if - there's some idle time available for some low-priority - concurrent task. - @return 1 or true if show() will start sending immediately, 0 or false - if show() would block (meaning some idle time is available). - */ - bool canShow(void) { - // It's normal and possible for endTime to exceed micros() if the - // 32-bit clock counter has rolled over (about every 70 minutes). - // Since both are uint32_t, a negative delta correctly maps back to - // positive space, and it would seem like the subtraction below would - // suffice. But a problem arises if code invokes show() very - // infrequently...the micros() counter may roll over MULTIPLE times in - // that interval, the delta calculation is no longer correct and the - // next update may stall for a very long time. The check below resets - // the latch counter if a rollover has occurred. This can cause an - // extra delay of up to 300 microseconds in the rare case where a - // show() call happens precisely around the rollover, but that's - // neither likely nor especially harmful, vs. other code that might - // stall for 30+ minutes, or having to document and frequently remind - // and/or provide tech support explaining an unintuitive need for - // show() calls at least once an hour. - uint32_t now = micros(); - if (endTime > now) { - endTime = now; - } - return (now - endTime) >= 300L; - } - /*! - @brief Get a pointer directly to the NeoPixel data buffer in RAM. - Pixel data is stored in a device-native format (a la the NEO_* - constants) and is not translated here. Applications that access - this buffer will need to be aware of the specific data format - and handle colors appropriately. - @return Pointer to NeoPixel buffer (uint8_t* array). - @note This is for high-performance applications where calling - setPixelColor() on every single pixel would be too slow (e.g. - POV or light-painting projects). There is no bounds checking - on the array, creating tremendous potential for mayhem if one - writes past the ends of the buffer. Great power, great - responsibility and all that. - */ - uint8_t *getPixels(void) const { return pixels; }; - uint8_t getBrightness(void) const; - /*! - @brief Retrieve the pin number used for NeoPixel data output. - @return Arduino pin number (-1 if not set). - */ - int16_t getPin(void) const { return pin; }; - /*! - @brief Return the number of pixels in an Adafruit_NeoPixel strip object. - @return Pixel count (0 if not set). - */ - uint16_t numPixels(void) const { return numLEDs; } - uint32_t getPixelColor(uint16_t n) const; - /*! - @brief An 8-bit integer sine wave function, not directly compatible - with standard trigonometric units like radians or degrees. - @param x Input angle, 0-255; 256 would loop back to zero, completing - the circle (equivalent to 360 degrees or 2 pi radians). - One can therefore use an unsigned 8-bit variable and simply - add or subtract, allowing it to overflow/underflow and it - still does the expected contiguous thing. - @return Sine result, 0 to 255, or -128 to +127 if type-converted to - a signed int8_t, but you'll most likely want unsigned as this - output is often used for pixel brightness in animation effects. - */ - static uint8_t sine8(uint8_t x) { - return pgm_read_byte(&_NeoPixelSineTable[x]); // 0-255 in, 0-255 out - } - /*! - @brief An 8-bit gamma-correction function for basic pixel brightness - adjustment. Makes color transitions appear more perceptially - correct. - @param x Input brightness, 0 (minimum or off/black) to 255 (maximum). - @return Gamma-adjusted brightness, can then be passed to one of the - setPixelColor() functions. This uses a fixed gamma correction - exponent of 2.6, which seems reasonably okay for average - NeoPixels in average tasks. If you need finer control you'll - need to provide your own gamma-correction function instead. - */ - static uint8_t gamma8(uint8_t x) { - return pgm_read_byte(&_NeoPixelGammaTable[x]); // 0-255 in, 0-255 out - } - /*! - @brief Convert separate red, green and blue values into a single - "packed" 32-bit RGB color. - @param r Red brightness, 0 to 255. - @param g Green brightness, 0 to 255. - @param b Blue brightness, 0 to 255. - @return 32-bit packed RGB value, which can then be assigned to a - variable for later use or passed to the setPixelColor() - function. Packed RGB format is predictable, regardless of - LED strand color order. - */ - static uint32_t Color(uint8_t r, uint8_t g, uint8_t b) { - return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; - } - /*! - @brief Convert separate red, green, blue and white values into a - single "packed" 32-bit WRGB color. - @param r Red brightness, 0 to 255. - @param g Green brightness, 0 to 255. - @param b Blue brightness, 0 to 255. - @param w White brightness, 0 to 255. - @return 32-bit packed WRGB value, which can then be assigned to a - variable for later use or passed to the setPixelColor() - function. Packed WRGB format is predictable, regardless of - LED strand color order. - */ - static uint32_t Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w) { - return ((uint32_t)w << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; - } - static uint32_t ColorHSV(uint16_t hue, uint8_t sat = 255, uint8_t val = 255); - /*! - @brief A gamma-correction function for 32-bit packed RGB or WRGB - colors. Makes color transitions appear more perceptially - correct. - @param x 32-bit packed RGB or WRGB color. - @return Gamma-adjusted packed color, can then be passed in one of the - setPixelColor() functions. Like gamma8(), this uses a fixed - gamma correction exponent of 2.6, which seems reasonably okay - for average NeoPixels in average tasks. If you need finer - control you'll need to provide your own gamma-correction - function instead. - */ - static uint32_t gamma32(uint32_t x); - - void rainbow(uint16_t first_hue = 0, int8_t reps = 1, - uint8_t saturation = 255, uint8_t brightness = 255, - bool gammify = true); - -private: -#if defined(ARDUINO_ARCH_RP2040) - void rp2040Init(uint8_t pin, bool is800KHz); - void rp2040Show(uint8_t pin, uint8_t *pixels, uint32_t numBytes, bool is800KHz); -#endif - -protected: -#ifdef NEO_KHZ400 // If 400 KHz NeoPixel support enabled... - bool is800KHz; ///< true if 800 KHz pixels -#endif - bool begun; ///< true if begin() previously called - uint16_t numLEDs; ///< Number of RGB LEDs in strip - uint16_t numBytes; ///< Size of 'pixels' buffer below - int16_t pin; ///< Output pin number (-1 if not yet set) - uint8_t brightness; ///< Strip brightness 0-255 (stored as +1) - uint8_t *pixels; ///< Holds LED color values (3 or 4 bytes each) - uint8_t rOffset; ///< Red index within each 3- or 4-byte pixel - uint8_t gOffset; ///< Index of green byte - uint8_t bOffset; ///< Index of blue byte - uint8_t wOffset; ///< Index of white (==rOffset if no white) - uint32_t endTime; ///< Latch timing reference -#ifdef __AVR__ - volatile uint8_t *port; ///< Output PORT register - uint8_t pinMask; ///< Output PORT bitmask -#endif -#if defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32) - GPIO_TypeDef *gpioPort; ///< Output GPIO PORT - uint32_t gpioPin; ///< Output GPIO PIN -#endif -#if defined(ARDUINO_ARCH_RP2040) - PIO pio = pio0; - int sm = 0; - bool init = true; -#endif -}; - -#endif // ADAFRUIT_NEOPIXEL_H diff --git a/ampel-firmware/src/lib/Adafruit_NeoPixel/CONTRIBUTING.md b/ampel-firmware/src/lib/Adafruit_NeoPixel/CONTRIBUTING.md deleted file mode 100644 index aa753894e5681aecb792f2aad1b7b65aa70ef96e..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/Adafruit_NeoPixel/CONTRIBUTING.md +++ /dev/null @@ -1,13 +0,0 @@ -# Contribution Guidelines - -This library is the culmination of the expertise of many members of the open source community who have dedicated their time and hard work. The best way to ask for help or propose a new idea is to [create a new issue](https://github.com/adafruit/Adafruit_NeoPixel/issues/new) while creating a Pull Request with your code changes allows you to share your own innovations with the rest of the community. - -The following are some guidelines to observe when creating issues or PRs: - -- Be friendly; it is important that we can all enjoy a safe space as we are all working on the same project and it is okay for people to have different ideas - -- [Use code blocks](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code); it helps us help you when we can read your code! On that note also refrain from pasting more than 30 lines of code in a post, instead [create a gist](https://gist.github.com/) if you need to share large snippets - -- Use reasonable titles; refrain from using overly long or capitalized titles as they are usually annoying and do little to encourage others to help :smile: - -- Be detailed; refrain from mentioning code problems without sharing your source code and always give information regarding your board and version of the library diff --git a/ampel-firmware/src/lib/Adafruit_NeoPixel/COPYING b/ampel-firmware/src/lib/Adafruit_NeoPixel/COPYING deleted file mode 100644 index 65c5ca88a67c30becee01c5a8816d964b03862f9..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/Adafruit_NeoPixel/COPYING +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/ampel-firmware/src/lib/Adafruit_NeoPixel/README.md b/ampel-firmware/src/lib/Adafruit_NeoPixel/README.md deleted file mode 100644 index eff1337119a105870cb989b97dd10648066c2e90..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/Adafruit_NeoPixel/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# Adafruit NeoPixel Library [![Build Status](https://github.com/adafruit/Adafruit_NeoPixel/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_NeoPixel/actions)[![Documentation](https://github.com/adafruit/ci-arduino/blob/master/assets/doxygen_badge.svg)](http://adafruit.github.io/Adafruit_NeoPixel/html/index.html) - -Arduino library for controlling single-wire-based LED pixels and strip such as the [Adafruit 60 LED/meter Digital LED strip][strip], the [Adafruit FLORA RGB Smart Pixel][flora], the [Adafruit Breadboard-friendly RGB Smart Pixel][pixel], the [Adafruit NeoPixel Stick][stick], and the [Adafruit NeoPixel Shield][shield]. - -After downloading, rename folder to 'Adafruit_NeoPixel' and install in Arduino Libraries folder. Restart Arduino IDE, then open File->Sketchbook->Library->Adafruit_NeoPixel->strandtest sketch. - -Compatibility notes: Port A is not supported on any AVR processors at this time - -[flora]: http://adafruit.com/products/1060 -[strip]: http://adafruit.com/products/1138 -[pixel]: http://adafruit.com/products/1312 -[stick]: http://adafruit.com/products/1426 -[shield]: http://adafruit.com/products/1430 - ---- - -## Installation - -### First Method - -![image](https://user-images.githubusercontent.com/36513474/68967967-3e37f480-0803-11ea-91d9-601848c306ee.png) - -1. In the Arduino IDE, navigate to Sketch > Include Library > Manage Libraries -1. Then the Library Manager will open and you will find a list of libraries that are already installed or ready for installation. -1. Then search for Neopixel strip using the search bar. -1. Click on the text area and then select the specific version and install it. - -### Second Method - -1. Navigate to the [Releases page](https://github.com/adafruit/Adafruit_NeoPixel/releases). -1. Download the latest release. -1. Extract the zip file -1. In the Arduino IDE, navigate to Sketch > Include Library > Add .ZIP Library - -## Features - -- ### Simple to use - - Controlling NeoPixels “from scratch” is quite a challenge, so we provide a library letting you focus on the fun and interesting bits. - -- ### Give back - - The library is free; you don’t have to pay for anything. Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! - -- ### Supported Chipsets - - We have included code for the following chips - sometimes these break for exciting reasons that we can't control in which case please open an issue! - - - AVR ATmega and ATtiny (any 8-bit) - 8 MHz, 12 MHz and 16 MHz - - Teensy 3.x and LC - - Arduino Due - - Arduino 101 - - ATSAMD21 (Arduino Zero/M0 and other SAMD21 boards) @ 48 MHz - - ATSAMD51 @ 120 MHz - - Adafruit STM32 Feather @ 120 MHz - - ESP8266 any speed - - ESP32 any speed - - Nordic nRF52 (Adafruit Feather nRF52), nRF51 (micro:bit) - - Infineon XMC1100 BootKit @ 32 MHz - - Infineon XMC1100 2Go @ 32 MHz - - Infineon XMC1300 BootKit @ 32 MHz - - Infineon XMC4700 RelaxKit, XMC4800 RelaxKit, XMC4800 IoT Amazon FreeRTOS Kit @ 144 MHz - - Check forks for other architectures not listed here! - -- ### GNU Lesser General Public License - - Adafruit_NeoPixel is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - -## Functions - -- begin() -- updateLength() -- updateType() -- show() -- delay_ns() -- setPin() -- setPixelColor() -- fill() -- ColorHSV() -- getPixelColor() -- setBrightness() -- getBrightness() -- clear() -- gamma32() - -## Examples - -There are many examples implemented in this library. One of the examples is below. You can find other examples [here](https://github.com/adafruit/Adafruit_NeoPixel/tree/master/examples) - -### Simple - -```Cpp -#include -#ifdef __AVR__ - #include -#endif -#define PIN 6 -#define NUMPIXELS 16 - -Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); -#define DELAYVAL 500 - -void setup() { -#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) - clock_prescale_set(clock_div_1); -#endif - - pixels.begin(); -} - -void loop() { - pixels.clear(); - - for(int i=0; i -#include "driver/rmt.h" - -#if defined(ESP_IDF_VERSION) -#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) -#define HAS_ESP_IDF_4 -#endif -#endif - -// This code is adapted from the ESP-IDF v3.4 RMT "led_strip" example, altered -// to work with the Arduino version of the ESP-IDF (3.2) - -#define WS2812_T0H_NS (400) -#define WS2812_T0L_NS (850) -#define WS2812_T1H_NS (800) -#define WS2812_T1L_NS (450) - -#define WS2811_T0H_NS (500) -#define WS2811_T0L_NS (2000) -#define WS2811_T1H_NS (1200) -#define WS2811_T1L_NS (1300) - -static uint32_t t0h_ticks = 0; -static uint32_t t1h_ticks = 0; -static uint32_t t0l_ticks = 0; -static uint32_t t1l_ticks = 0; - -// Limit the number of RMT channels available for the Neopixels. Defaults to all -// channels (8 on ESP32, 4 on ESP32-S2 and S3). Redefining this value will free -// any channels with a higher number for other uses, such as IR send-and-recieve -// libraries. Redefine as 1 to restrict Neopixels to only a single channel. -#define ADAFRUIT_RMT_CHANNEL_MAX RMT_CHANNEL_MAX - -#define RMT_LL_HW_BASE (&RMT) - -bool rmt_reserved_channels[ADAFRUIT_RMT_CHANNEL_MAX]; - -static void IRAM_ATTR ws2812_rmt_adapter(const void *src, rmt_item32_t *dest, size_t src_size, - size_t wanted_num, size_t *translated_size, size_t *item_num) -{ - if (src == NULL || dest == NULL) { - *translated_size = 0; - *item_num = 0; - return; - } - const rmt_item32_t bit0 = {{{ t0h_ticks, 1, t0l_ticks, 0 }}}; //Logical 0 - const rmt_item32_t bit1 = {{{ t1h_ticks, 1, t1l_ticks, 0 }}}; //Logical 1 - size_t size = 0; - size_t num = 0; - uint8_t *psrc = (uint8_t *)src; - rmt_item32_t *pdest = dest; - while (size < src_size && num < wanted_num) { - for (int i = 0; i < 8; i++) { - // MSB first - if (*psrc & (1 << (7 - i))) { - pdest->val = bit1.val; - } else { - pdest->val = bit0.val; - } - num++; - pdest++; - } - size++; - psrc++; - } - *translated_size = size; - *item_num = num; -} - -void espShow(uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) { - // Reserve channel - rmt_channel_t channel = ADAFRUIT_RMT_CHANNEL_MAX; - for (size_t i = 0; i < ADAFRUIT_RMT_CHANNEL_MAX; i++) { - if (!rmt_reserved_channels[i]) { - rmt_reserved_channels[i] = true; - channel = i; - break; - } - } - if (channel == ADAFRUIT_RMT_CHANNEL_MAX) { - // Ran out of channels! - return; - } - -#if defined(HAS_ESP_IDF_4) - rmt_config_t config = RMT_DEFAULT_CONFIG_TX(pin, channel); - config.clk_div = 2; -#else - // Match default TX config from ESP-IDF version 3.4 - rmt_config_t config = { - .rmt_mode = RMT_MODE_TX, - .channel = channel, - .gpio_num = pin, - .clk_div = 2, - .mem_block_num = 1, - .tx_config = { - .carrier_freq_hz = 38000, - .carrier_level = RMT_CARRIER_LEVEL_HIGH, - .idle_level = RMT_IDLE_LEVEL_LOW, - .carrier_duty_percent = 33, - .carrier_en = false, - .loop_en = false, - .idle_output_en = true, - } - }; -#endif - rmt_config(&config); - rmt_driver_install(config.channel, 0, 0); - - // Convert NS timings to ticks - uint32_t counter_clk_hz = 0; - -#if defined(HAS_ESP_IDF_4) - rmt_get_counter_clock(channel, &counter_clk_hz); -#else - // this emulates the rmt_get_counter_clock() function from ESP-IDF 3.4 - if (RMT_LL_HW_BASE->conf_ch[config.channel].conf1.ref_always_on == RMT_BASECLK_REF) { - uint32_t div_cnt = RMT_LL_HW_BASE->conf_ch[config.channel].conf0.div_cnt; - uint32_t div = div_cnt == 0 ? 256 : div_cnt; - counter_clk_hz = REF_CLK_FREQ / (div); - } else { - uint32_t div_cnt = RMT_LL_HW_BASE->conf_ch[config.channel].conf0.div_cnt; - uint32_t div = div_cnt == 0 ? 256 : div_cnt; - counter_clk_hz = APB_CLK_FREQ / (div); - } -#endif - - // NS to tick converter - float ratio = (float)counter_clk_hz / 1e9; - - if (is800KHz) { - t0h_ticks = (uint32_t)(ratio * WS2812_T0H_NS); - t0l_ticks = (uint32_t)(ratio * WS2812_T0L_NS); - t1h_ticks = (uint32_t)(ratio * WS2812_T1H_NS); - t1l_ticks = (uint32_t)(ratio * WS2812_T1L_NS); - } else { - t0h_ticks = (uint32_t)(ratio * WS2811_T0H_NS); - t0l_ticks = (uint32_t)(ratio * WS2811_T0L_NS); - t1h_ticks = (uint32_t)(ratio * WS2811_T1H_NS); - t1l_ticks = (uint32_t)(ratio * WS2811_T1L_NS); - } - - // Initialize automatic timing translator - rmt_translator_init(config.channel, ws2812_rmt_adapter); - - // Write and wait to finish - rmt_write_sample(config.channel, pixels, (size_t)numBytes, true); - rmt_wait_tx_done(config.channel, pdMS_TO_TICKS(100)); - - // Free channel again - rmt_driver_uninstall(config.channel); - rmt_reserved_channels[channel] = false; - - gpio_set_direction(pin, GPIO_MODE_OUTPUT); -} - -#endif diff --git a/ampel-firmware/src/lib/Adafruit_NeoPixel/esp8266.c b/ampel-firmware/src/lib/Adafruit_NeoPixel/esp8266.c deleted file mode 100644 index 51c3f3c8a34f4856f9c2636da364bed5081d2918..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/Adafruit_NeoPixel/esp8266.c +++ /dev/null @@ -1,86 +0,0 @@ -// This is a mash-up of the Due show() code + insights from Michael Miller's -// ESP8266 work for the NeoPixelBus library: github.com/Makuna/NeoPixelBus -// Needs to be a separate .c file to enforce ICACHE_RAM_ATTR execution. - -#if defined(ESP8266) - -#include -#ifdef ESP8266 -#include -#endif - -static uint32_t _getCycleCount(void) __attribute__((always_inline)); -static inline uint32_t _getCycleCount(void) { - uint32_t ccount; - __asm__ __volatile__("rsr %0,ccount":"=a" (ccount)); - return ccount; -} - -#ifdef ESP8266 -IRAM_ATTR void espShow( - uint8_t pin, uint8_t *pixels, uint32_t numBytes, __attribute__((unused)) boolean is800KHz) { -#else -void espShow( - uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) { -#endif - -#define CYCLES_800_T0H (F_CPU / 2500001) // 0.4us -#define CYCLES_800_T1H (F_CPU / 1250001) // 0.8us -#define CYCLES_800 (F_CPU / 800001) // 1.25us per bit -#define CYCLES_400_T0H (F_CPU / 2000000) // 0.5uS -#define CYCLES_400_T1H (F_CPU / 833333) // 1.2us -#define CYCLES_400 (F_CPU / 400000) // 2.5us per bit - - uint8_t *p, *end, pix, mask; - uint32_t t, time0, time1, period, c, startTime; - -#ifdef ESP8266 - uint32_t pinMask; - pinMask = _BV(pin); -#endif - - p = pixels; - end = p + numBytes; - pix = *p++; - mask = 0x80; - startTime = 0; - -#ifdef NEO_KHZ400 - if(is800KHz) { -#endif - time0 = CYCLES_800_T0H; - time1 = CYCLES_800_T1H; - period = CYCLES_800; -#ifdef NEO_KHZ400 - } else { // 400 KHz bitstream - time0 = CYCLES_400_T0H; - time1 = CYCLES_400_T1H; - period = CYCLES_400; - } -#endif - - for(t = time0;; t = time0) { - if(pix & mask) t = time1; // Bit high duration - while(((c = _getCycleCount()) - startTime) < period); // Wait for bit start -#ifdef ESP8266 - GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high -#else - gpio_set_level(pin, HIGH); -#endif - startTime = c; // Save start time - while(((c = _getCycleCount()) - startTime) < t); // Wait high duration -#ifdef ESP8266 - GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low -#else - gpio_set_level(pin, LOW); -#endif - if(!(mask >>= 1)) { // Next bit/byte - if(p >= end) break; - pix = *p++; - mask = 0x80; - } - } - while((_getCycleCount() - startTime) < period); // Wait for last bit -} - -#endif // ESP8266 diff --git a/ampel-firmware/src/lib/Adafruit_NeoPixel/kendyte_k210.c b/ampel-firmware/src/lib/Adafruit_NeoPixel/kendyte_k210.c deleted file mode 100644 index 8033a36e22787634d47cd289216a9b70389b3b31..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/Adafruit_NeoPixel/kendyte_k210.c +++ /dev/null @@ -1,74 +0,0 @@ -// This is a mash-up of the Due show() code + insights from Michael Miller's -// ESP8266 work for the NeoPixelBus library: github.com/Makuna/NeoPixelBus -// Needs to be a separate .c file to enforce ICACHE_RAM_ATTR execution. -#if defined(K210) -#define KENDRYTE_K210 1 -#endif - -#if defined(KENDRYTE_K210) - -#include -#include "sysctl.h" - -void k210Show( - uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) -{ - -#define CYCLES_800_T0H (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 2500000) // 0.4us -#define CYCLES_800_T1H (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 1250000) // 0.8us -#define CYCLES_800 (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 800000) // 1.25us per bit -#define CYCLES_400_T0H (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 2000000) // 0.5uS -#define CYCLES_400_T1H (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 833333) // 1.2us -#define CYCLES_400 (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 400000) // 2.5us per bit - - uint8_t *p, *end, pix, mask; - uint32_t t, time0, time1, period, c, startTime; - - p = pixels; - end = p + numBytes; - pix = *p++; - mask = 0x80; - startTime = 0; - -#ifdef NEO_KHZ400 - if (is800KHz) - { -#endif - time0 = CYCLES_800_T0H; - time1 = CYCLES_800_T1H; - period = CYCLES_800; -#ifdef NEO_KHZ400 - } - else - { // 400 KHz bitstream - time0 = CYCLES_400_T0H; - time1 = CYCLES_400_T1H; - period = CYCLES_400; - } -#endif - - for (t = time0;; t = time0) - { - if (pix & mask) - t = time1; // Bit high duration - while (((c = read_cycle()) - startTime) < period) - ; // Wait for bit start - digitalWrite(pin, HIGH); - startTime = c; // Save start time - while (((c = read_cycle()) - startTime) < t) - ; // Wait high duration - digitalWrite(pin, LOW); - - if (!(mask >>= 1)) - { // Next bit/byte - if (p >= end) - break; - pix = *p++; - mask = 0x80; - } - } - while ((read_cycle() - startTime) < period) - ; // Wait for last bit -} - -#endif // KENDRYTE_K210 diff --git a/ampel-firmware/src/lib/Adafruit_NeoPixel/keywords.txt b/ampel-firmware/src/lib/Adafruit_NeoPixel/keywords.txt deleted file mode 100644 index 4003ede9dc66ed41867b321773ce0bc0e2416476..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/Adafruit_NeoPixel/keywords.txt +++ /dev/null @@ -1,72 +0,0 @@ -####################################### -# Syntax Coloring Map For Adafruit_NeoPixel -####################################### -# Class -####################################### - -Adafruit_NeoPixel KEYWORD1 - -####################################### -# Methods and Functions -####################################### - -begin KEYWORD2 -show KEYWORD2 -setPin KEYWORD2 -setPixelColor KEYWORD2 -fill KEYWORD2 -setBrightness KEYWORD2 -clear KEYWORD2 -updateLength KEYWORD2 -updateType KEYWORD2 -canShow KEYWORD2 -getPixels KEYWORD2 -getBrightness KEYWORD2 -getPin KEYWORD2 -numPixels KEYWORD2 -getPixelColor KEYWORD2 -sine8 KEYWORD2 -gamma8 KEYWORD2 -Color KEYWORD2 -ColorHSV KEYWORD2 -gamma32 KEYWORD2 - -####################################### -# Constants -####################################### - -NEO_COLMASK LITERAL1 -NEO_SPDMASK LITERAL1 -NEO_KHZ800 LITERAL1 -NEO_KHZ400 LITERAL1 -NEO_RGB LITERAL1 -NEO_RBG LITERAL1 -NEO_GRB LITERAL1 -NEO_GBR LITERAL1 -NEO_BRG LITERAL1 -NEO_BGR LITERAL1 -NEO_WRGB LITERAL1 -NEO_WRBG LITERAL1 -NEO_WGRB LITERAL1 -NEO_WGBR LITERAL1 -NEO_WBRG LITERAL1 -NEO_WBGR LITERAL1 -NEO_RWGB LITERAL1 -NEO_RWBG LITERAL1 -NEO_RGWB LITERAL1 -NEO_RGBW LITERAL1 -NEO_RBWG LITERAL1 -NEO_RBGW LITERAL1 -NEO_GWRB LITERAL1 -NEO_GWBR LITERAL1 -NEO_GRWB LITERAL1 -NEO_GRBW LITERAL1 -NEO_GBWR LITERAL1 -NEO_GBRW LITERAL1 -NEO_BWRG LITERAL1 -NEO_BWGR LITERAL1 -NEO_BRWG LITERAL1 -NEO_BRGW LITERAL1 -NEO_BGWR LITERAL1 -NEO_BGRW LITERAL1 - diff --git a/ampel-firmware/src/lib/Adafruit_NeoPixel/library.properties b/ampel-firmware/src/lib/Adafruit_NeoPixel/library.properties deleted file mode 100644 index 4bde4ac077147f65142997598641c5be31669e49..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/Adafruit_NeoPixel/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit NeoPixel -version=1.10.4 -author=Adafruit -maintainer=Adafruit -sentence=Arduino library for controlling single-wire-based LED pixels and strip. -paragraph=Arduino library for controlling single-wire-based LED pixels and strip. -category=Display -url=https://github.com/adafruit/Adafruit_NeoPixel -architectures=* diff --git a/ampel-firmware/src/lib/Adafruit_NeoPixel/rp2040_pio.h b/ampel-firmware/src/lib/Adafruit_NeoPixel/rp2040_pio.h deleted file mode 100644 index f7ccd46de0a5cc8510f86b10069c6417b57fdde4..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/Adafruit_NeoPixel/rp2040_pio.h +++ /dev/null @@ -1,63 +0,0 @@ -// -------------------------------------------------- // -// This file is autogenerated by pioasm; do not edit! // -// -------------------------------------------------- // - -// Unless you know what you are doing... -// Lines 47 and 52 have been edited to set transmit bit count - -#if !PICO_NO_HARDWARE -#include "hardware/pio.h" -#endif - -// ------ // -// ws2812 // -// ------ // - -#define ws2812_wrap_target 0 -#define ws2812_wrap 3 - -#define ws2812_T1 2 -#define ws2812_T2 5 -#define ws2812_T3 3 - -static const uint16_t ws2812_program_instructions[] = { - // .wrap_target - 0x6221, // 0: out x, 1 side 0 [2] - 0x1123, // 1: jmp !x, 3 side 1 [1] - 0x1400, // 2: jmp 0 side 1 [4] - 0xa442, // 3: nop side 0 [4] - // .wrap -}; - -#if !PICO_NO_HARDWARE -static const struct pio_program ws2812_program = { - .instructions = ws2812_program_instructions, - .length = 4, - .origin = -1, -}; - -static inline pio_sm_config ws2812_program_get_default_config(uint offset) { - pio_sm_config c = pio_get_default_sm_config(); - sm_config_set_wrap(&c, offset + ws2812_wrap_target, offset + ws2812_wrap); - sm_config_set_sideset(&c, 1, false, false); - return c; -} - -#include "hardware/clocks.h" -static inline void ws2812_program_init(PIO pio, uint sm, uint offset, uint pin, - float freq, uint bits) { - pio_gpio_init(pio, pin); - pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true); - pio_sm_config c = ws2812_program_get_default_config(offset); - sm_config_set_sideset_pins(&c, pin); - sm_config_set_out_shift(&c, false, true, - bits); // <----<<< Length changed to "bits" - sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); - int cycles_per_bit = ws2812_T1 + ws2812_T2 + ws2812_T3; - float div = clock_get_hz(clk_sys) / (freq * cycles_per_bit); - sm_config_set_clkdiv(&c, div); - pio_sm_init(pio, sm, offset, &c); - pio_sm_set_enabled(pio, sm, true); -} - -#endif diff --git a/ampel-firmware/src/lib/IotWebConf/CMakeLists.txt b/ampel-firmware/src/lib/IotWebConf/CMakeLists.txt deleted file mode 100644 index fe478b127a4c4f38edd0c75d1a879661f5800435..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -set(COMPONENT_SRCS - src/IotWebConf.cpp - src/IotWebConfMultipleWifi.cpp - src/IotWebConfOptionalGroup.cpp - src/IotWebConfParameter.cpp - src/IotWebConfESP32HTTPUpdateServer.cpp - ) - -set(COMPONENT_ADD_INCLUDEDIRS - src/ - ) -list(APPEND COMPONENT_REQUIRES "arduino") -register_component() - -#ADD_DEFINITIONS(-DESP32) - -list(APPEND DEFINITIONS "ESP32") - diff --git a/ampel-firmware/src/lib/IotWebConf/IotWebConf.code-workspace b/ampel-firmware/src/lib/IotWebConf/IotWebConf.code-workspace deleted file mode 100644 index 3cd0ab8c712a881fc224aac0592639cec6ff9540..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/IotWebConf.code-workspace +++ /dev/null @@ -1,64 +0,0 @@ -{ - "folders": [ - { - "path": "." - }, - { - "path": "../IotWebConf-examples/IotWebConf01Minimal" - }, - { - "path": "../IotWebConf-examples/IotWebConf02StatusAndReset" - }, - { - "path": "../IotWebConf-examples/IotWebConf03CustomParameters" - }, - { - "path": "../IotWebConf-examples/IotWebConf03TypedParameters" - }, - { - "path": "../IotWebConf-examples/IotWebConf04UpdateServer" - }, - { - "path": "../IotWebConf-examples/IotWebConf05Callbacks" - }, - { - "path": "../IotWebConf-examples/IotWebConf06MqttApp" - }, - { - "path": "../IotWebConf-examples/IotWebConf07MqttRelay" - }, - { - "path": "../IotWebConf-examples/IotWebConf08WebRelay" - }, - { - "path": "../IotWebConf-examples/IotWebConf09CustomConnection" - }, - { - "path": "../IotWebConf-examples/IotWebConf10CustomHtml" - }, - { - "path": "../IotWebConf-examples/IotWebConf11AdvancedRuntime" - }, - { - "path": "../IotWebConf-examples/IotWebConf12CustomParameterType" - }, - { - "path": "../IotWebConf-examples/IotWebConf13OptionalGroup" - }, - { - "path": "../IotWebConf-examples/IotWebConf14GroupChain" - }, - { - "path": "../IotWebConf-examples/IotWebConf15MultipleWifi" - }, - { - "path": "../IotWebConf-examples/IotWebConf16OffLineMode" - }, - { - "path": "../IotWebConf-examples/IotWebConf17JsonConfig" - } - ], - "settings": { - "workbench.tree.indent": 16 - } -} diff --git a/ampel-firmware/src/lib/IotWebConf/IotWebConf.iml b/ampel-firmware/src/lib/IotWebConf/IotWebConf.iml deleted file mode 100644 index 745f22c74c3bd5e037fb50495f0ae3f99a45a70b..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/IotWebConf.iml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/LICENSE.txt b/ampel-firmware/src/lib/IotWebConf/LICENSE.txt deleted file mode 100644 index e129fc339c39ad1f0c90f29001f104e83b4ca7a2..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/LICENSE.txt +++ /dev/null @@ -1,9 +0,0 @@ -The MIT License (MIT) - -Copyright 2018 Balazs Kelemen - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ampel-firmware/src/lib/IotWebConf/README.md b/ampel-firmware/src/lib/IotWebConf/README.md deleted file mode 100644 index 70ee741052c648f35ca0742e69280cb345c97480..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/README.md +++ /dev/null @@ -1,111 +0,0 @@ -# IotWebConf [![Build Status](https://github.com/prampec/IotWebConf/workflows/PlatformIO%20CI/badge.svg?branch=master)](https://github.com/prampec/IotWebConf/actions/workflows/test.platformio.yml) - -## Upgrading to v3.0.0 -Lately version 3.0.0 is released. This release is not backward compatible with -older versions, and some modification have to be done on existing codes. -**Please visit [Migration Guide](doc/MigrationGuide-v3.0.0.md) for - details!** - -## Summary -IotWebConf is an Arduino library for ESP8266/ESP32 to provide a non-blocking standalone WiFi/AP web configuration portal. -**For ESP8266, IotWebConf requires the esp8266 board package version 2.4.2 or later!** - -Please subscribe to the [discussion forum](https://groups.google.com/forum/#!forum/iotwebconf), if you want to be informed on the latest news. - -Also visit experimental [Discord server](https://discord.gg/GR3uQeD). - -**HELP WANTED!** If you are testing any GIT branches, please give me feedback to provide stable releases for the public. - -## Highlights - - - Manages WiFi connection settings, - - Provides a config portal user interface, - - You can extend the configuration with your own sophisticated propery structure, that is stored automatically, - - Option to configure multiple WiFi connections. (Try next when the - last used one is just not available.) - - HTML customization, - - Validation support for the configuration property items, - - User code will be notified of status changes with callback methods, - - Configuration (including your custom items) stored in the EEPROM, - - Firmware OTA update support, - - Config portal remains available even after WiFi is connected, - - Automatic "Sign in to network" pop up in your browser (captive portal), - - Non-blocking - Your custom code will not be blocked in the whole process. - - Well documented header file, and examples from simple to complex levels. - -![Screenshot](https://sharedinventions.com/wp-content/uploads/2018/11/Screenshot_20181105-191748a.png) -![Screenshot](https://sharedinventions.com/wp-content/uploads/2019/02/Screenshot-from-2019-02-03-22-16-51b.png) - -## How it works -The idea is that the Thing will provide a web interface to allow modifying its configuration. E.g. for connecting to a local WiFi network, it needs the SSID and the password. - -When no WiFi is configured, or the configured network is unavailable it creates its own AP (access point), and lets clients connect to it directly to make the configuration. - -Furthermore there is a button (or let's say a Pin), that when pressed on startup will cause a default password to be used instead of the configured (forgotten) one. -You can find the default password in the sources. :) - -IotWebConf saves configuration in the "EEPROM". You can extend the config portal with your custom configuration items. Those items will be also maintained by IotWebConf. - -Visit [Users Manual](doc/UsersManual.md) for detailed description! - -## Use cases - 1. **You turn on your IoT the first time** - It turns into AP (access point) mode, and waits for you on the 192.168.4.1 address with a web interface to set up your local network (and other configurations). For the first time a default password is used when you connect to the AP. When you connect to the AP, your device will likely automatically pop up the portal page. (We call this a Captive Portal.) When configuration is done, you must leave the AP. The device detects that no one is connected, and continues with normal operation. - 1. **WiFi configuration is changed, e.g. the Thing is moved to another location** - When the Thing cannot connect to the configured WiFi, it falls back to AP mode, and waits for you to change the network configuration. When no configuration was made, then it keeps trying to connect with the already configured settings. The Thing will not switch off the AP while anyone is connected to it, so you must leave the AP when finished with the configuration. - 1. **You want to connect to the AP, but have forgotten the configured AP WiFi password you set up previously** - Connect the appropriate pin on the Arduino to ground with a push button. Holding the button pressed while powering up the device causes the Thing to start the AP mode with the default password. (See Case 1. The pin is configured in the code.) - 1. **You want to change the configuration before the Thing connects to the Internet** - Fine! The Thing always starts up in AP mode and provides you a time frame to connect to it and make any modification to the configuration. Any time one is connected to the AP (provided by the device) the AP will stay on until the connection is closed. So take your time for the changes, the Thing will wait for you while you are connected to it. - 1. **You want to change the configuration at runtime** - No problem. IotWebConf keeps the config portal up and running even after the WiFi connection is finished. In this scenario you must enter username "admin" and password (already configured) to enter the config portal. Note, that the password provided for the authentication is not hidden from devices connected to the same WiFi network. You might want to force rebooting of the Thing to apply your changes. - -## User notes - - In the config portal you can double-tap on a password to reveal what -you have typed in. (Double-tap again to hide revealed text.) - - When accessing the config portal via connected WiFi network a dialog -with user-name and password will pop up. The password is the one you -have configured for "AP password". The user name is "admin". - - Consult [Users Manual](doc/UsersManual.md) for more details! - - -## IotWebConf vs. WiFiManager -tzapu's WiFiManager is a great library. The features of IotWebConf may appear very similar to WiFiManager. However, IotWebConf tries to be different. - - WiFiManager does not allow you to configure **mutiple WiFi** connections. In IotWebConf there is a way to define more connections: if one is not available, the next is tried automatically. - - ~~WiFiManager does not manage your **custom properties**.~~ IotWebConf stores your configuration in "EEPROM". - - WiFiManager does not do **validation**. IotWebConf allow you to validate your property changes made in the config portal. - - ~~WiFiManager does not support ESP32.~~ - - ~~With WiFiManager you cannot use both startup and **on-demand configuration**.~~ With IotWebConf the config portal remains available via the connected local WiFi. - - WiFiManager provides list of available networks, and an information page, while these features are cool, IotWebConf tries to keep the code simple. So these features are not (yet) provided by IotWebConf. - - IotWebConf is fitted for more advanced users. You can keep control of the web server setup, configuration item input field behavior, and validation. - -## Security aspects - - The initial system password must be modified by the user, so there is no build-in password. - - When connecting in AP mode, the WiFi provides an encryption layer (WPA/WPA2), so all your communication here is known to be safe. (The exact wifi encryption depends on the used board/chipset and implementation in the related esp/arduino framework.) - - When connecting through a WiFi router (WiFi mode), the Thing will ask for authentication when someone requests the config portal. This is required as the Thing will be visible for all devices sharing the same network. But be warned by the following note... - - NOTE: **When connecting through a WiFi router (WiFi mode), your communication is not hidden from devices connecting to the same network.** It communicates over unencrypted HTTP. So either: Do not allow ambiguous devices connecting to your WiFi router, or configure your Thing only in AP mode! - - However IotWebConf has a detailed debug output, passwords are not shown in this log by default. You have - to enable password visibility manually in the IotWebConf.h with the IOTWEBCONF_DEBUG_PWD_TO_SERIAL - if it is needed. - -## Compatibility -IotWebConf is primary built for ESP8266. But meanwhile it was discovered, that the code can be adopted -to ESP32. There are two major problems. - - ESP8266 uses specific naming for it's classes (e.g. ESP8266WebServer). However, ESP32 uses a more generic naming (e.g. WebServer). The idea here is to use the generic naming hoping that ESP8266 will adopt these "standards" sooner or later. - - ESP32 does not provide an HTTPUpdateServer implementation. So in this project we have implemented one. Whenever ESP32 provides an official HTTPUpdateServer, this local implementation will be removed. - -## Customizing and extending functionality -IotWebConf is ment to be developer friendly by providing lots -of customization options. See [HackingGuide](doc/HackingGuide.md) for -details. - -## TODO / Feature requests - - We might want to add a "verify password" field. - - Provide an option, where IotWebConf renders HTML-response, -handles HTTP-request for a specific branch of groups. - - Separate WiFi management from the code, so config portal can also -be a standalone solution without any WiFi. - -## Known issues - - It is reported, that there might be unstable working with different lwIP variants. If you experiment serious problems, try to select another lwIP variant for your board in the Tools menu! (Tested with "v2 Lower Memory" version.) - -## Credits -Although IotWebConf started without being influenced by any other solutions, in the final code you can find some segments borrowed from the WiFiManager library. - - https://github.com/tzapu/WiFiManager - -Thanks to [all contributors](https://github.com/prampec/IotWebConf/graphs/contributors) providing patches for the library! diff --git a/ampel-firmware/src/lib/IotWebConf/doc/HackingGuide.md b/ampel-firmware/src/lib/IotWebConf/doc/HackingGuide.md deleted file mode 100644 index 4251dbca1e5030d8314b59135ffe709d8ce1cd08..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/doc/HackingGuide.md +++ /dev/null @@ -1,232 +0,0 @@ -# IotWebConf hacking guide - -IotWebConf comes with a lot of examples. These examples are intended -to be easy to use, with clear goals. While IotWebConf is also ment to be -developer friendly, providing lots of customization options. - -This documentation will try to explain features where you can customize -IotWebConf on your need, or where a feature explanation might be out of the -scope of regular examples. - -Please note, that header files are full of -documentation, so please heavily consult ```IotWebConf.h``` header file -while/beside reading this documentation. - -__Contents__: - - - [PlatformIO](#using-iotwebconf-with-platformio) - - [Compile time configuration](#compile-time-configuration) - - [Groups and Parameters](#groups-and-parameters) - - [Optional and chained groups](#optional-and-chained-groups) - - [Using System parameter-group](#using-system-parameter-group) - - [Alternative WiFi connection](#alternative-wifi-connection) - - [Accessing system properties](#accessing-system-properties) - - [Use custom style](#use-custom-style) - - [Create your property class](#create-your-property-class) - - [Typed parameters](#typed-parameters-experimental) - - [Control on WiFi connection status change](#control-on-wifi-connection-status-change) - - [Use alternative WebServer](#use-alternative-webserver) - -## Using IotWebConf with PlatformIO -It is recommended to use PlatformIO instead of the Arduino environment. - -With v3.0.0, a folder ```pio``` is provided with scripts that transforms -examples to PlatformIO compatible format. You can use these as templates -for your project. (On the other hand, these scripts creating soft-link -loops, and having soft link loops in these folders might cause Arduino -and other environment to fail. Just keep in mind, if something goes -wrong with your IDE, then examples-pio is likely the corporate.) - -## Compile time configuration -IotWebConf includes a configuration file named IotWebConfSettings.h. -This configuration file works on C pre-compiler mechanism. This means -you cannot use it in Arduino environment, so I encourage everyone to -switch to PlatformIO. - -In the PlatformIO you can do configuration changes by adding lines to - platformio.ini like this: -``` -build_flags = - -DIOTWEBCONF_DEFAULT_WIFI_CONNECTION_TIMEOUT_MS="60000" - -DIOTWEBCONF_DEBUG_DISABLED -``` - -**Note:** You must not use ```#define IOTWEBCONF_CONFIG_START 20```, or -similar defines in your .ino file (e.g. before the includes). It will eventually -just not work, as all .cpp files are compiled separately for each other. -Thus, you must use the ```-D``` compiler flag for the job. - -## Groups and Parameters -With version 3.0.0 IotWebConf introduces individual parameter classes for -each type, and you can organize your parameters into groups. -You can also free to add groups into groups to make a tree hierarchy. - -## Optional and chained groups -With ```OptionalParameterGroup```, the group you have defined will have -a special appearance in the config portal, as the fieldset in which the -group items are shown can be hidden (inactive) / shown (active). - -E.g you want to create a group with property items, that are not mandatory, -so you can hide these options in the config portal by default, and -only reveal the contents, when it is strictly requested. -There is a specific example covering this very feature under -```IotWebConf13OptionalGroup```. - -```ChainedParameterGroup```s can be linked. One after another. The -property sets will reveal on after another, when user requests is. The -difference between ```OptionalParameterGroup``` and ```ChainedParameterGroup``` -is that second group item in a chained list can only be added, when -the first item is already visible. -There is a specific example covering this very feature under -```IotWebConf14GroupChain```. - -## Using system parameter-group -By default, you should add your own parameter group, that will appear as -a new field-set on the Config Portal. However, there is a special group -maintained by IotWebConf called the System group, where you are also -allowed to add your own custom properties. - -Example: -``` - iotWebConf.addSystemParameter(&stringParam); -``` - -You can directly access system-parameter group by calling -```getSystemParameterGroup()```. - -Example: -``` - ParameterGroup* systemParameters = iotWebConf.getSystemParameterGroup(); - systemParameters.label = "My Custom Label"; -``` - -There is another group "WiFi parameters" managed by IotWebConf, that -can be retrieved by getWifiParameterGroup(). - -## Alternative WiFi connection -With v3.0.0 you can set up multiple WiFi connection by utilizing the -MultipleWifiAddition class can be found in IotWebConfMultipleWifi.h . - -This class basically set up some handlers in iotWebConf to -1. display optional WiFi settings in admin GUI, -2. use these alternative settings in case previous WiFi connection -attempts fails. - -The maximal number of connection settings are determined compile-time, -as we want to avoid any dynamic memory allocations in Arduino. - -There is a complete example covering this topic, please visit example -```IotWebConf15MultipleWifi```! - -## Accessing system properties -IotWebConf comes with some parameters, that are required for the basic -functionality. You can retrieve these parameter by getters, e.g. -```getThingNameParameter()```. You can directly modify these items as -seen in the code block below. - -There is a dedicated example covering this topic, so please visit -example ```IotWebConf11AdvancedRuntime```! - -``` - // -- Update Thing name - strncpy( - iotWebConf.getThingNameParameter()->valueBuffer, - "My changed name", - iotWebConf.getThingNameParameter()->getLength()); - iotWebConf.saveConfig(); -``` - -Here is list of some of the system parameter-acccessors, please consult -IotWebConf.h for further details. -- getSystemParameterGroup() -- getThingNameParameter() -- getApPasswordParameter() -- getWifiParameterGroup() -- getWifiSsidParameter() -- getWifiPasswordParameter() -- getApTimeoutParameter() - -## Use custom style -You can provide your own custom HTML template by updating default -HTML format provider. For this you should utilize the - ```setHtmlFormatProvider()``` method. - -There is a complete example about this topic, so please visit example -```IotWebConf10CustomHtml```! - -## Create your property class -With version 3.0.0 you are free to create your own property class. -It is done by inheriting the iotwebconf::Parameter C++ class. You can use -other property types e.g. PasswordProperty as a template for this. - -Now, custom properties are mainly handy, when you would like to create -some special HTML form item. But eventually you can change the whole -behaviour of your parameter handling. E.g. by overriding ```storeValue()``` -and ```loadValue()``` you can basically convert your internal data format -to whatever you like. The [Typed parameters](#typed-parameters-experimental) -approach is just an excellent example for this option. - -You can also override ParameterGroup class in case you need some special -group appearance. - -There is a complete example about this topic, so please visit example -```IotWebConf12CustomParameterType```! - -## Typed parameters (experimental) -A new parameter structure is introduced, where the parameters does not -require a "valueBuffer" anymore. Storing the parameter is done in a -native format, e.g. a 8-bit integers are stored in one byte of EEPROM. - -This was achieved by utilizing the ```template``` technology of C++. -While the result is spectacular, the ```template``` makes thing very -complicated under the hood. - -Builder pattern is also introduced for the typed parameters. See example -```IotWebConf03TypedParameters``` for details. Please compare example -IotWebConf03TypedParameters and IotWebConf03TypedParameters for the -difference in the usage of the two different approach. - -**Please note, that Typed Parameters are very experimental, and the -interface might be a subject of change in the future.** - -![UML diagram of the Typed Parameters approach.](TParameter.png) -(This image was created by PlantUML, the source file is generate with command -```hpp2plantuml -i src/IotWebConfTParameter.h -o doc/TParameter.plantuml```) - -## Control on WiFi connection status change -IotWebConf provides a feature to control WiFi connection events by defining -your custom handler event handler. - -With ```setWifiConnectionFailedHandler()``` you can set up a handler, that -will be called, when a connection to a WiFi network failed (most likely -timed out). Now, when you return with a new valid connection-info from -your callback, IotWebConf will not fall back to AP mode, but try the -connection you have just provided. With this method you can theoretically -set up multiple WiFi networks for IotWebConf to try connect to after -one-by-one if the previous one fails. Some days IotWebConf might also -provide this feature out of the box. - -There is a second method, where you can define a specific handler, this -is the ```setWifiConnectionHandler()```. Your method will be called when -IotWebConf trying to establish connection to a WiFi network. - -For details please consult ```IotWebConf.h``` header file! - -## Use alternative WebServer - -There was an expressed need from your side for supporting specific types of -Web servers. (E.g https -web server or async web server.) So, with v3.0.0 there is an option to -use web server of your choice. To achieve this, you will call IotWebConf -constructor, that accepts a ```WebServerWrapper``` pointer. -In the WebServerWrapper you have the implement all expected web server -functionalities (as seen in the header file). You can use -the ```StandardWebServerWrapper``` as a template for that. - -Further more, you also need to provide your custom ```WebRequestWrapper``` -instances when calling ```handleCaptivePortal()```, ```handleConfig()``` and -```handleNotFound()```. - -Unfortunately I currently do not have the time to implement solutions -for Async Web Server os Secure Web Server. If you can do that with the -instruction above, please provide me the pull request! diff --git a/ampel-firmware/src/lib/IotWebConf/doc/MigrationGuide-v3.0.0.md b/ampel-firmware/src/lib/IotWebConf/doc/MigrationGuide-v3.0.0.md deleted file mode 100644 index 51c6c5937ee46dc782c6d504c769c5dc80cdfb89..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/doc/MigrationGuide-v3.0.0.md +++ /dev/null @@ -1,263 +0,0 @@ -# Migration guide to v3.0.0 - -In v3.0.0 some changes were introduced, that are not backward -compatible with v2.x.x versions. -This guide contains all modifications that should be done in existing -codes, to reflect the changes. - -For better understanding some code examples are also shown here, but -I would recommend comparing git changes in the examples. - -## Changes introduced in v3.0.0 - - - [Namespaces](#namespaces) - - [Parameter classes](#parameter-classes) - - [Parameter grouping](#grouping-parameters) - - [Default value handling](#default-value-handling) - - [Hidden parameters](#hidden-parameters) - - [UpdateServer changes](#updateserver-changes) - - [configSave](#configsave) - - [formValidator](#formvalidator) - -## Namespaces - -With v3.0.0, IotWebConf library started to use namespaces. Namespace -is a C++ technique, where to goal is to avoid name collision over -different libraries. - -The namespace for IotWebConf become ```iotwebconf::```. From now on -you should use this prefix for each type defined by the library -except for the IotWebConf class itself. - -There are more ways to update your code. Let's see some variations! - -### Migration steps: easy way -For easy migration IotWebConf has provided a header file prepared -with predefined aliases to hide namespaces, so you can still use -the legacy types. - -Include helper header file as follows. - -Code before: -```C++ -#include -``` - -Code after: -```C++ -#include -#include -``` - -### Migration steps: proper way -Use namespace prefixes before every type name. - -Code before: -```C++ -IotWebConfParameter mqttServerParam = - IotWebConfParameter("MQTT server", "mqttServer", mqttServerValue, STRING_LEN); -``` - -Code after: -```C++ -iotwebconf::Parameter mqttServerParam = - iotwebconf::Parameter("MQTT server", "mqttServer", mqttServerValue, STRING_LEN); -``` - -### Migration steps: optimist way -Define namespaces at the beginning of the code and use simple type name. -Everywhere later on. This works only until name-collision with other -library occur. - -Code after: -```C++ -using namespace iotwebconf; -... -Parameter mqttServerParam = - Parameter("MQTT server", "mqttServer", mqttServerValue, STRING_LEN); -``` - -## Parameter classes - -Previously there was just the ```IotWebConfParameter``` and the -actual type was provided as an argument of this one-and-only type. -Now it turned out, that it is a better idea to use specific classes -for each individual types. So from now on you must specify the type -of the parameter by creating that very type e.g. using -```IotWebConfTextParameter```. - -For compatibility reasons the signature is the same before, except -the type string should not be provided anymore. - -New parameter types are also introduced (e.g. - ```IotWebConfSelectParameter```), -and it is very likely that with newer versions, more and more types will - arrive. -Creating your custom parameter is now become much more easy as well. - -### Migrations steps -Replace IotWebConfParameter types with specific parameter type. - -Code before: -```C++ -IotWebConfParameter mqttServerParam = - IotWebConfParameter("MQTT server", "mqttServer", mqttServerValue , STRING_LEN); -IotWebConfParameter mqttUserPasswordParam = - IotWebConfParameter("MQTT password", "mqttPass", mqttUserPasswordValue , STRING_LEN, "password"); -``` - -Code after: -```C++ -IotWebConfTextParameter mqttServerParam = - IotWebConfTextParameter("MQTT server", "mqttServer", mqttServerValue , STRING_LEN); -IotWebConfPasswordParameter mqttUserPasswordParam = - IotWebConfPasswordParameter("MQTT password", "mqttPass ", mqttUserPasswordValue, STRING_LEN); -``` - -Note, that ```IotWebConfTextParameter``` and -```IotWebConfPasswordParameter``` words are just aliases and eventually you -should use ```iotwebconf::TextParameter```, -```iotwebconf::PasswordParameter```, etc. - -_Note, that with version 3.0.0 a new typed parameter approach is introduced, -you might want to immediately migrate to this parameter types, but -typed-parameters are still in testing phase and might be a subject of -change._ - -## Grouping parameters - -With v3.0.0 "separator" disappears. Separators were used to create -field sets in the rendered HTML. Now you must directly define connected -items by adding them to specific parameter groups. -(It is also possible to add a group within a group.) - -You need to add prepared groups to IotWebConf instead of individual -parameters. (However there is a specific group created by IotWebConf for -storing system parameters, you can also add your -properties into the system group.) - -Code before: -```C++ -IotWebConfSeparator separator1 = - IotWebConfSeparator(); -IotWebConfParameter intParam = - IotWebConfParameter("Int param", "intParam", intParamValue, NUMBER_LEN, "number", - "1..100", nullptr, "min='1' max='100' step='1'"); - -... - -void setup() -{ -... - iotWebConf.addParameter(&separator1); - iotWebConf.addParameter(&intParam); -... -``` - -Code after: -```C++ -IotWebConfParameterGroup group1 = - IotWebConfParameterGroup("group1", ""); -IotWebConfNumberParameter intParam = - IotWebConfNumberParameter("Int param", "intParam", intParamValue, NUMBER_LEN, - "20", "1..100", "min='1' max='100' step='1'"); - -... - -void setup() -{ -... - group1.addItem(&intParam); -... - iotWebConf.addParameterGroup(&group1); -... -``` - -Also note, that ```IotWebConfParameterGroup``` and -```IotWebConfNumberParameter``` words are just aliases and eventually you -should use ```iotwebconf::ParameterGroup```, -```iotwebconf::NumberParameter```, etc. - -## Default value handling - -For the Parameters you could always specify "defaultValue". In v2.x -.x this value was intended to be appeared in the config portal, if no -values are specified. Now with v3.0.0, defaultValue has a different -meaning. Now it is -automatically assigned to the parameter, when this is the **first -time** configuration is loading. - -This means you do not have to set these values manually. - -In the example below, the body of the ```if``` is done by IotWebConf -automatically. -``` - // -- Initializing the configuration. - bool validConfig = iotWebConf.init(); - if (!validConfig) - { - // DO NOT DO THIS! Use default values instead. - strncpy(mqttServerValue, "192.168.1.10", STRING_LEN); - } -``` - -## Hidden parameters - -IotWebConf can save and load parameters, that are not populated to the -web interface. To mark an item as hidden, you should have set the last -parameter of the constructor to visible=false. - -From v3.0.0, you will need to add hidden items to a specific group managed -by IotWebConf. -``` -iotWebConf.addHiddenParameter(&myHiddenParameter); -``` - -## UpdateServer changes - -In prior versions, IotWebConf activated HTTP Update server automatically. -With version 3.0.0, IotWebConf dropped the dependency to UpdateServer. The -activation will still be triggered, but the actual switching action -should be provided externally (at your code). - -A quite complicated code needs to introduced because of this change, and -you need to manually include UpdateServer to your code. See example: - ```IotWebConf04UpdateServer``` for details! - -Changed lines: - -``` -// Include Update server -#ifdef ESP8266 -# include -#elif defined(ESP32) -# include -#endif - -// Create Update Server -#ifdef ESP8266 -ESP8266HTTPUpdateServer httpUpdater; -#elif defined(ESP32) -HTTPUpdateServer httpUpdater; -#endif - - // In setup register callbacks performing Update Server hooks. - iotWebConf.setupUpdateServer( - [](const char* updatePath) { httpUpdater.setup(&server, updatePath); }, - [](const char* userName, char* password) { httpUpdater.updateCredentials(userName, password); }); -``` - -Note, that ESP32 still doesn't provide Update Server solution out of the -box. IotWebConf still provides an implementation for that, but it is now -completely independent of the core codes. - -## configSave -Method configSave is renamed to saveConfig. - -## formValidator -The formValidator() methods from now on will have a -```webRequestWrapper``` parameter. - -``` -bool formValidator(iotwebconf::WebRequestWrapper* webRequestWrapper); -``` \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/doc/TParameter.plantuml b/ampel-firmware/src/lib/IotWebConf/doc/TParameter.plantuml deleted file mode 100644 index f9802f06eeacfeba4f3fcf07aab6ff5100f796a1..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/doc/TParameter.plantuml +++ /dev/null @@ -1,272 +0,0 @@ -@startuml - - - - - -/' Objects '/ - -namespace iotwebconf { - class BoolDataType { - +BoolDataType() - #fromString() : bool - } - - class CharArrayDataType { - +CharArrayDataType() - #update() : bool - #getInputLength() : int - #applyDefaultValue() : void - #loadValue() : void - #storeValue() : void - } - - class CheckboxTParameter { - +CheckboxTParameter() - #renderHtml() : String - +isChecked() : bool - #getInputType() : char* - -_checkedStr : const char* - #update() : void - } - - abstract class ConfigItemBridge { - #ConfigItemBridge() - #{abstract} toString() : String - #{abstract} update() : bool - #getInputLength() : int - +debugTo() : void - +update() : void - } - - abstract class DataType { - +DataType() - #toString() : String - #_value : ValueType - +getValue() : ValueType& - +operator*() : ValueType& - #_defaultValue : _DefaultValueType - #{abstract} update() : bool - #validate() : bool - #getStorageSize() : int - } - - class DoubleDataType { - +DoubleDataType() - #fromString() : double - } - - class FloatDataType { - +FloatDataType() - #fromString() : float - } - - class FloatTParameter { - +FloatTParameter() - +isMaxDefined() : bool - +isMinDefined() : bool - #getInputType() : char* - +getMax() : float - +getMin() : float - } - - abstract class InputParameter { - +InputParameter() - +getCustomHtml() : String - #getHtmlTemplate() : String - #renderHtml() : String - #{abstract} getInputType() : char* - +customHtml : const char* - +errorMessage : const char* - +label : const char* - +placeholder : const char* - #clearErrorMessage() : void - +renderHtml() : void - +setPlaceholder() : void - } - - class IntTParameter { - +IntTParameter() - +getMax() : ValueType - +getMin() : ValueType - +isMaxDefined() : bool - +isMinDefined() : bool - #getInputType() : char* - } - - class IpDataType { - #toString() : String - #update() : bool - } - - class OptionsTParameter { - +OptionsTParameter() - #OptionsTParameter() - #_optionNames : const char* - #_optionValues : const char* - #_nameLength : size_t - #_optionCount : size_t - +setNameLength() : void - +setOptionCount() : void - +setOptionNames() : void - +setOptionValues() : void - } - - class PasswordTParameter { - +PasswordTParameter() - #renderHtml() : String - +update() : bool - #getInputType() : char* - -_customHtmlPwd : const char* - +debugTo() : void - } - - abstract class PrimitiveDataType { - +PrimitiveDataType() - -_max : ValueType - -_min : ValueType - #{abstract} fromString() : ValueType - #getMax() : ValueType - #getMin() : ValueType - #isMaxDefined() : ValueType - #isMinDefined() : ValueType - -_maxDefined : bool - -_minDefined : bool - #update() : bool - #applyDefaultValue() : void - #loadValue() : void - +setMax() : void - +setMin() : void - #storeValue() : void - } - - abstract class PrimitiveInputParameter { - +PrimitiveInputParameter() - +getCustomHtml() : String - +{abstract} getMax() : ValueType - +{abstract} getMin() : ValueType - +step : ValueType - +{abstract} isMaxDefined() : bool - +{abstract} isMinDefined() : bool - +setStep() : void - } - - class SelectTParameter { - +SelectTParameter() - +SelectTParameter() - #renderHtml() : String - } - - class SignedIntDataType { - +SignedIntDataType() - #fromString() : ValueType - } - - class StringDataType { - #toString() : String - #update() : bool - } - - class TextTParameter { - +TextTParameter() - #getInputType() : char* - } - - class UnsignedIntDataType { - +UnsignedIntDataType() - #fromString() : ValueType - } -} - - - - - -/' Inheritance relationships '/ - -iotwebconf.BoolDataType <|-- iotwebconf.CheckboxTParameter - - -iotwebconf.CharArrayDataType <|-- iotwebconf.PasswordTParameter - - -iotwebconf.CharArrayDataType <|-- iotwebconf.TextTParameter - - -iotwebconf.ConfigItemBridge <|-- iotwebconf.DataType - - -iotwebconf.ConfigItemBridge <|-- iotwebconf.InputParameter - - -iotwebconf.DataType <|-- iotwebconf.CharArrayDataType - - -iotwebconf.DataType <|-- iotwebconf.IpDataType - - -iotwebconf.DataType <|-- iotwebconf.PrimitiveDataType - - -iotwebconf.DataType <|-- iotwebconf.StringDataType - - -iotwebconf.FloatDataType <|-- iotwebconf.FloatTParameter - - -iotwebconf.InputParameter <|-- iotwebconf.CheckboxTParameter - - -iotwebconf.InputParameter <|-- iotwebconf.PasswordTParameter - - -iotwebconf.InputParameter <|-- iotwebconf.PrimitiveInputParameter - - -iotwebconf.InputParameter <|-- iotwebconf.TextTParameter - - -iotwebconf.OptionsTParameter <|-- iotwebconf.SelectTParameter - - -iotwebconf.PrimitiveDataType <|-- iotwebconf.BoolDataType - - -iotwebconf.PrimitiveDataType <|-- iotwebconf.DoubleDataType - - -iotwebconf.PrimitiveDataType <|-- iotwebconf.FloatDataType - - -iotwebconf.PrimitiveDataType <|-- iotwebconf.SignedIntDataType - - -iotwebconf.PrimitiveDataType <|-- iotwebconf.UnsignedIntDataType - - -iotwebconf.PrimitiveInputParameter <|-- iotwebconf.FloatTParameter - - -iotwebconf.PrimitiveInputParameter <|-- iotwebconf.IntTParameter - - -iotwebconf.SignedIntDataType <|-- iotwebconf.IntTParameter - - -iotwebconf.TextTParameter <|-- iotwebconf.OptionsTParameter - - - - - -/' Aggregation relationships '/ - - - - - -/' Nested objects '/ - - - -@enduml diff --git a/ampel-firmware/src/lib/IotWebConf/doc/TParameter.png b/ampel-firmware/src/lib/IotWebConf/doc/TParameter.png deleted file mode 100644 index a6b9a3c0661339b692bcc541937581eeeed51e9c..0000000000000000000000000000000000000000 Binary files a/ampel-firmware/src/lib/IotWebConf/doc/TParameter.png and /dev/null differ diff --git a/ampel-firmware/src/lib/IotWebConf/doc/UsersManual.md b/ampel-firmware/src/lib/IotWebConf/doc/UsersManual.md deleted file mode 100644 index 88f7cf2f91dcfcb66fb372e9def8f2686c62a4f9..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/doc/UsersManual.md +++ /dev/null @@ -1,225 +0,0 @@ -# IotWebConf users manual template - -This documentation is mainly for makers are about to came out with their -own product, and prepare for that with a Users manual. -Or for ones who are want to understand the basic functionality of -IotWebConf. - -This document can be used as a template, modify it with the actual -product specific details. We will only cover the basic functionality -(including status and reset), but will __not__ talk about options like: -- Firmware update (OTA), -- Static IP option, -- Multiply WiFi option, -- Offline mode option, -- Skip AP-mode option. - -#### Hardware setup - -The document assumes, that the device is equipped with -the indicator LED and the "reset" button, just as it can be seen -in example `IotWebConf02StatusAndReset`. - -As mentioned above a "default" options-set is assumed as well. - -## Starting up the device at the first time - -When you are starting up the device for the first time, the device -will create its own WiFi Access Point with SSID _testThing_. -The status indicator rapidly flashes (it is mostly on). - -Use your smartphone (or tablet, or computer) to detect the created -WiFi network, and connect to it by using the default password -_smrtThng8266_. After a successful WiFi connection a configuration -page is popped up in your smartphone's web browser. - -Note, that at this point even if the network is not configured, -the device is already ready to use with the factory defaults in -an off-line manner. - -## Configuration page (Config portal) - -After you have connected to the access point created by the -device (as described above), you need to enter the configuration -page on the web-browser of your smartphone. -On the configuration page you will see some fields you can -set. - -Except for the password fields, you will see the item values -previously set. (Or for first time setup, the factory default.) - -For the password fields you will never see any previously set -values, and typed values are also hidden. You can __reveal the -password__ text you have typed by double-clicking (double-tapping) on -the password field. You can then double-click (double-tap) -a second time to hide the text again. It is recommended to -hide the passwords before submitting the configuration form, -as browsers are likely to save non-password form values to -use them as recommendation. - -_TODO: you can provide some more description on specific -fields you are about to use._ - -When you are finished providing all the values of your need, -please press the Apply button. - -Some fields are protected with constraints, and a validation is -performed. In case there is an error in the validation of -any field none of them are saved. You even need to re-type values -for filled-out passwords in this case. - -## Configuration options - -After the first boot, there are some values needs to be set up. -These items are maked with __*__ (star) in the list below. - -You can set up the following values in the configuration page: - -- __Thing name__ - Please change the name of the device to -a name you think describes it the most. It is advised to -incorporate a location here in case you are planning to -set up multiple devices in the same area. You should only use -english letters, and the "_" underscore character. Thus, must not -use Space, dots, etc. E.g. `lamp_livingroom` __*__ -- __AP password__ - This password is used, when you want to -access the device later on. You must provide a password with at least 8, -at most 32 characters. -You are free to use any characters, further more you are -encouraged to pick a password at least 12 characters long containing -at least 3 character classes. __*__ -- __WiFi SSID__ - The name of the WiFi network you want the device -to connect to. __*__ -- __WiFi password__ - The password of the network above. Note, that -unsecured passwords are not supported in your protection. __*__ - -_TODO: add your own configuration here_ - -Note, that in "First boot" mode you are free to save any -partial data, but on-line mode will not enter until you have -provided all mandatory data. - -## Connecting to a WiFi network - -When you have successfully applied the mandatory configurations, -the device will try to connect to the required WiFi network. While -connecting, the indicator LED will alter between On/Off in a moderated -speed. - -If the WiFi connection is successfull, the indicator LED will turn off, -and performes rapid blinks with long delays. - -If the WiFi connection fails, the device will __fall back to Access Point -mode__. This means, that the device will form its own WiFi network, on -what you can connect to, and correct network connection setup. - -This time you will see the `Thing Name` value as the access point name - (SSID), -and you need to use the `AP password` you have configured previously. - -This also means, that if the configured WiFi network is not available, -the device will fall back to Access Point mode, stays there for some -seconds (so that you can perform changes if needed), and after some -seconds it will __retry connecting to the WiFi network__. - -The Access Point mode is indicated with rapid blinks, where the indicator -LED is mostly on. -Access Point mode will kept as long as any connection is alive to it. -Thus, you need to disconnect from the Access Point for the device to -continue its operation. - -## Second startup and rescue mode - -In case you have already set up a WiFi network in the config portal, -the device will automatically tries to (re)connect to it. However, -when the device boots up it will __always starts the Access Point -mode__ as described in previous section. - -In case you have __lost the password__ you have configured, you need to -enter the rescue mode. To __enter the rescue mode__, you need to press -and hold the button on the device while powering it up. This time you -can enter the Access Point provided by the device with the factory-default -password, that is _smrtThng8266_. The rescue mode will not be release -until you have connected to the access point, it will be -released after you have disconnected from it. - -## Configuration in connected mode - -After the device successfully connected to the configured WiFi network -the temporary Access Point is terminated, but you can still connect -to the device using its IP address. To determine the IP address of the -device, you might want to consult with your WiFi router. (Devices -are intented to be access by name as well, but this option is not -reliable, thus, it cannot be recommended.) - -When you want to access the Config Portal of the device __via a WiFi -network__ from your Web Browser, a login page will be displayed, where -you need to enter: -- User name: `admin` -- Password: the password you have set up previously as __AP Password__. - -#### Security notes connecting from WiFi network - -While WiFi networks are known to be relatively safe by hiding its trafic -from the public, it is not safe between parties connected to the network. -And our device does not support secure Web connection. - -This means, when enter the configuration page via WiFi network, other -parties can monitor your traffic. - -Recommendations to avoid compromisation: -- Try to make your configurations in Access Point mode, -- Set up a dedicated WiFi network to your IOT devices, where uncertain -parties are not allowed to connect. - - -## Blinking codes - -Prevoius chapters were mentioned blinking patterns, now here is a -table summarize the menaning of the blink codes. - -- __Rapid blinking__ (mostly on, interrupted by short off periods) - -Entered Access Point mode. This means the device create an own WiFi -network around it. You can connect to the device with your smartphone -(or WiFi capable computer). -- __Alternating on/off blinking__ - Trying to connect the configured -WiFi network. -- __Mostly off with occasional short flash__ - The device is online. - -## Troubleshooting - ->I have turned on my device, but it blinks like crazy. What should I do? - -- Diagnose: Your device is not configured. -- Solution: -You need to turn on your smartphone, search for WiFi networks, and connect -to `testThing`. Follow the instruction at -[Starting up the device at the first time](#starting-up-the-device-at-the-first-time) - ->After I start up the device, the device just blinks as crazy and ->later chills. But while it is blinking I cannot connect to it. Is this ->intended? - -- Diagnose: This is an expected behaviour. At startup time you are able - connect directly -to the device directly via a temporary created access point to perform some -configuration changes. (The idea here, is that you can change WiFi -setting in case it was changed before trying to connect to it.) - ->My device is either blinks like crazy, or with an alternating pattern, ->but eventually it does not stop that. Why is that? - -- Diagnose: Your device cannot connect to the configured WiFi -network. -Your network setup was changed, you have miss-typed the settings, or -the device is out of the network range. -- Solution: At the time the device rapidly blinks, connect to it with -your smartphone and alter the WiFi configuration (SSID and password). -If this doesn't help try to provide stronger WiFi signal for the device. - -> I have forgot the password I have set. What should I do? - -- Solution: Turn off your device. Press and hold the button on the -device while powering it up. The device will start up in Access Pont -mode, you can connect to this temporary WiFi network with your -smartphone using the initial password, that is _smrtThng8266_, and -set up a new password for the device. \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/keywords.txt b/ampel-firmware/src/lib/IotWebConf/keywords.txt deleted file mode 100644 index 12813df32b9e7e5d56475ae13f5aa879d565dd3c..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/keywords.txt +++ /dev/null @@ -1,125 +0,0 @@ -# Datatypes (KEYWORD1) -# Methods and Functions (KEYWORD2) -# Constants (LITERAL1) - -# IotWebConf.h - -WifiAuthInfo KEYWORD1 - -HtmlFormatProvider KEYWORD1 -getHead KEYWORD2 -getStyle KEYWORD2 -getScript KEYWORD2 -getHeadExtension KEYWORD2 -getHeadEnd KEYWORD2 -getFormStart KEYWORD2 -getFormEnd KEYWORD2 -getFormSaved KEYWORD2 -getEnd KEYWORD2 -getUpdate KEYWORD2 -getConfigVer KEYWORD2 - -StandardWebRequestWrapper KEYWORD1 - -StandardWebServerWrapper KEYWORD1 - -WifiParameterGroup KEYWORD1 - -IotWebConf KEYWORD1 -setConfigPin KEYWORD2 -setStatusPin KEYWORD2 -setupUpdateServer KEYWORD2 -init KEYWORD2 -doLoop KEYWORD2 -handleCaptivePortal KEYWORD2 -handleConfig KEYWORD2 -handleNotFound KEYWORD2 -setWifiConnectionCallback KEYWORD2 -setConfigSavingCallback KEYWORD2 -setConfigSavedCallback KEYWORD2 -setFormValidator KEYWORD2 -setApConnectionHandler KEYWORD2 -setWifiConnectionHandler KEYWORD2 -setWifiConnectionFailedHandler KEYWORD2 -addParameterGroup KEYWORD2 -addHiddenParameter KEYWORD2 -addSystemParameter KEYWORD2 -getThingName KEYWORD2 -delay KEYWORD2 -setWifiConnectionTimeoutMs KEYWORD2 -blink KEYWORD2 -fineBlink KEYWORD2 -stopCustomBlink KEYWORD2 -disableBlink KEYWORD2 -enableBlink KEYWORD2 -isBlinkEnabled KEYWORD2 -getState KEYWORD2 -setApTimeoutMs KEYWORD2 -getApTimeoutMs KEYWORD2 -resetWifiAuthInfo KEYWORD2 -skipApStartup KEYWORD2 -forceApMode KEYWORD2 -getSystemParameterGroup KEYWORD2 -getThingNameParameter KEYWORD2 -getApPasswordParameter KEYWORD2 -getWifiParameterGroup KEYWORD2 -getWifiSsidParameter KEYWORD2 -getWifiPasswordParameter KEYWORD2 -getApTimeoutParameter KEYWORD2 -saveConfig KEYWORD2 -setHtmlFormatProvider KEYWORD2 -getHtmlFormatProvider KEYWORD2 - - -#IotWebConfParameter.h - -SerializationData KEYWORD1 - -ConfigItem KEYWORD1 -visible KEYWORD2 -getId KEYWORD2 - -IotWebConfParameterGroup KEYWORD1 -ParameterGroup KEYWORD1 -addItem KEYWORD2 -label KEYWORD2 - -IotWebConfParameter KEYWORD1 -Parameter KEYWORD1 -label KEYWORD2 -valueBuffer KEYWORD2 -defaultValue KEYWORD2 -errorMessage KEYWORD2 -getLength KEYWORD2 - -IotWebConfTextParameter KEYWORD1 -TextParameter KEYWORD1 -placeholder KEYWORD2 -customHtml KEYWORD2 - -IotWebConfPasswordParameter KEYWORD1 -PasswordParameter KEYWORD1 - -IotWebConfNumberParameter KEYWORD1 -NumberParameter KEYWORD1 - -IotWebConfCheckboxParameter KEYWORD1 -CheckboxParameter KEYWORD1 -isChecked KEYWORD2 - -IotWebConfSelectParameter KEYWORD1 -SelectParameter KEYWORD1 - -#IotWebConfOptionalGroup.h - -OptionalGroupHtmlFormatProvider KEYWORD1 -OptionalParameterGroup KEYWORD1 -ChainedParameterGroup KEYWORD1 -setNext KEYWORD2 -getNext KEYWORD2 - -#IotWebConfOptionalGroup.h - -ChainedWifiParameterGroup KEYWORD1 -MultipleWifiAddition KEYWORD1 - diff --git a/ampel-firmware/src/lib/IotWebConf/library.properties b/ampel-firmware/src/lib/IotWebConf/library.properties deleted file mode 100644 index 908fb5dcb31d9e206dadd4a09779a132a2a7e503..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=IotWebConf -version=3.2.0 -author=Balazs Kelemen -maintainer=Balazs Kelemen -sentence=ESP8266/ESP32 non-blocking WiFi/AP web configuration. -paragraph=IotWebConf will start up in AP (access point) mode, and provide a config portal for entering WiFi connection and other user-settings. The configuration is persisted in EEPROM. The config portal will stay available after WiFi connection was made. A WiFiManager alternative. -category=Communication -url=https://github.com/prampec/IotWebConf -architectures=esp8266,esp32 -includes=IotWebConf.h diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConf.cpp b/ampel-firmware/src/lib/IotWebConf/src/IotWebConf.cpp deleted file mode 100644 index b0fca3c9fe73c7781a57ee21d5ad92fe82c90b13..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConf.cpp +++ /dev/null @@ -1,986 +0,0 @@ -/** - * IotWebConf.cpp -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#include - -#include "IotWebConf.h" - -#ifdef IOTWEBCONF_CONFIG_USE_MDNS -# ifdef ESP8266 -# include -# elif defined(ESP32) -# include -# endif -#endif - -#define IOTWEBCONF_STATUS_ENABLED ((this->_statusPin >= 0) && this->_blinkEnabled) - -//////////////////////////////////////////////////////////////// - -namespace iotwebconf -{ - -IotWebConf::IotWebConf( - const char* defaultThingName, DNSServer* dnsServer, WebServerWrapper* webServerWrapper, - const char* initialApPassword, const char* configVersion) -{ - this->_thingNameParameter.defaultValue = defaultThingName; - this->_dnsServer = dnsServer; - this->_webServerWrapper = webServerWrapper; - this->_initialApPassword = initialApPassword; - this->_configVersion = configVersion; - - this->_apTimeoutParameter.visible = false; - this->_systemParameters.addItem(&this->_thingNameParameter); - this->_systemParameters.addItem(&this->_apPasswordParameter); - this->_systemParameters.addItem(&this->_wifiParameters); - this->_systemParameters.addItem(&this->_apTimeoutParameter); - - this->_allParameters.addItem(&this->_systemParameters); - this->_allParameters.addItem(&this->_customParameterGroups); - this->_allParameters.addItem(&this->_hiddenParameters); - - this->_wifiAuthInfo = {this->_wifiParameters._wifiSsid, this->_wifiParameters._wifiPassword}; -} - -char* IotWebConf::getThingName() -{ - return this->_thingName; -} - -void IotWebConf::setConfigPin(int configPin) -{ - this->_configPin = configPin; -} - -void IotWebConf::setStatusPin(int statusPin, int statusOnLevel) -{ - this->_statusPin = statusPin; - this->_statusOnLevel = statusOnLevel; -} - -bool IotWebConf::init() -{ - // -- Setup pins. - if (this->_configPin >= 0) - { - pinMode(this->_configPin, INPUT_PULLUP); - this->_forceDefaultPassword = (digitalRead(this->_configPin) == LOW); - } - if (IOTWEBCONF_STATUS_ENABLED) - { - pinMode(this->_statusPin, OUTPUT); - digitalWrite(this->_statusPin, !this->_statusOnLevel); - } - - // -- Load configuration from EEPROM. - bool validConfig = this->loadConfig(); - this->_apTimeoutMs = atoi(this->_apTimeoutStr) * 1000; - - // -- Setup mdns -#ifdef IOTWEBCONF_CONFIG_USE_MDNS - MDNS.begin(this->_thingName); - MDNS.addService("http", "tcp", IOTWEBCONF_CONFIG_USE_MDNS); -#endif - - return validConfig; -} - -////////////////////////////////////////////////////////////////// - -void IotWebConf::addParameterGroup(ParameterGroup* group) -{ - this->_customParameterGroups.addItem(group); -} - -void IotWebConf::addHiddenParameter(ConfigItem* parameter) -{ - this->_hiddenParameters.addItem(parameter); -} - -void IotWebConf::addSystemParameter(ConfigItem* parameter) -{ - this->_systemParameters.addItem(parameter); -} - -int IotWebConf::initConfig() -{ - int size = this->_allParameters.getStorageSize(); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print("Config version: "); - Serial.println(this->_configVersion); - Serial.print("Config size: "); - Serial.println(size); -#endif - - return size; -} - -/** - * Load the configuration from the eeprom. - */ -bool IotWebConf::loadConfig() -{ - int size = this->initConfig(); - EEPROM.begin( - IOTWEBCONF_CONFIG_START + IOTWEBCONF_CONFIG_VERSION_LENGTH + size); - - bool result; - if (this->testConfigVersion()) - { - int start = IOTWEBCONF_CONFIG_START + IOTWEBCONF_CONFIG_VERSION_LENGTH; - IOTWEBCONF_DEBUG_LINE(F("Loading configurations")); - this->_allParameters.loadValue([&](SerializationData* serializationData) - { - this->readEepromValue(start, serializationData->data, serializationData->length); - start += serializationData->length; - }); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - this->_allParameters.debugTo(&Serial); -#endif - result = true; - } - else - { - IOTWEBCONF_DEBUG_LINE(F("Wrong config version. Applying defaults.")); - this->_allParameters.applyDefaultValue(); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - this->_allParameters.debugTo(&Serial); -#endif - - result = false; - } - - EEPROM.end(); - return result; -} - -void IotWebConf::saveConfig() -{ - int size = this->initConfig(); - if (this->_configSavingCallback != nullptr) - { - this->_configSavingCallback(size); - } - EEPROM.begin( - IOTWEBCONF_CONFIG_START + IOTWEBCONF_CONFIG_VERSION_LENGTH + size); - - this->saveConfigVersion(); - int start = IOTWEBCONF_CONFIG_START + IOTWEBCONF_CONFIG_VERSION_LENGTH; - IOTWEBCONF_DEBUG_LINE(F("Saving configuration")); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - this->_allParameters.debugTo(&Serial); - Serial.println(); -#endif - this->_allParameters.storeValue([&](SerializationData* serializationData) - { - this->writeEepromValue(start, serializationData->data, serializationData->length); - start += serializationData->length; - }); - - EEPROM.end(); - - this->_apTimeoutMs = atoi(this->_apTimeoutStr) * 1000; - - if (this->_configSavedCallback != nullptr) - { - this->_configSavedCallback(); - } -} - -void IotWebConf::readEepromValue(int start, byte* valueBuffer, int length) -{ - for (int t = 0; t < length; t++) - { - *((char*)valueBuffer + t) = EEPROM.read(start + t); - } -} -void IotWebConf::writeEepromValue(int start, byte* valueBuffer, int length) -{ - for (int t = 0; t < length; t++) - { - EEPROM.write(start + t, *((char*)valueBuffer + t)); - } -} - -bool IotWebConf::testConfigVersion() -{ - for (byte t = 0; t < IOTWEBCONF_CONFIG_VERSION_LENGTH; t++) - { - if (EEPROM.read(IOTWEBCONF_CONFIG_START + t) != this->_configVersion[t]) - { - return false; - } - } - return true; -} - -void IotWebConf::saveConfigVersion() -{ - for (byte t = 0; t < IOTWEBCONF_CONFIG_VERSION_LENGTH; t++) - { - EEPROM.write(IOTWEBCONF_CONFIG_START + t, this->_configVersion[t]); - } -} - -void IotWebConf::setWifiConnectionCallback(std::function func) -{ - this->_wifiConnectionCallback = func; -} - -void IotWebConf::setConfigSavingCallback(std::function func) -{ - this->_configSavingCallback = func; -} - -void IotWebConf::setConfigSavedCallback(std::function func) -{ - this->_configSavedCallback = func; -} - -void IotWebConf::setFormValidator( - std::function func) -{ - this->_formValidator = func; -} - -void IotWebConf::setWifiConnectionTimeoutMs(unsigned long millis) -{ - this->_wifiConnectionTimeoutMs = millis; -} - -//////////////////////////////////////////////////////////////////////////////// - -void IotWebConf::handleConfig(WebRequestWrapper* webRequestWrapper) -{ - if (this->_state == OnLine) - { - // -- Authenticate - if (!webRequestWrapper->authenticate( - IOTWEBCONF_ADMIN_USER_NAME, this->_apPassword)) - { - IOTWEBCONF_DEBUG_LINE(F("Requesting authentication.")); - webRequestWrapper->requestAuthentication(); - return; - } - } - - bool dataArrived = webRequestWrapper->hasArg("iotSave"); - if (!dataArrived || !this->validateForm(webRequestWrapper)) - { - // -- Display config portal - IOTWEBCONF_DEBUG_LINE(F("Configuration page requested.")); - - // Send chunked output instead of one String, to avoid - // filling memory if using many parameters. - webRequestWrapper->sendHeader( - "Cache-Control", "no-cache, no-store, must-revalidate"); - webRequestWrapper->sendHeader("Pragma", "no-cache"); - webRequestWrapper->sendHeader("Expires", "-1"); - webRequestWrapper->setContentLength(CONTENT_LENGTH_UNKNOWN); - webRequestWrapper->send(200, "text/html; charset=UTF-8", ""); - - String content = htmlFormatProvider->getHead(); - content.replace("{v}", "Config ESP"); - content += htmlFormatProvider->getScript(); - content += htmlFormatProvider->getStyle(); - content += htmlFormatProvider->getHeadExtension(); - content += htmlFormatProvider->getHeadEnd(); - - content += htmlFormatProvider->getFormStart(); - - webRequestWrapper->sendContent(content); - -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.println("Rendering parameters:"); - this->_systemParameters.debugTo(&Serial); - this->_customParameterGroups.debugTo(&Serial); -#endif - // -- Add parameters to the form - this->_systemParameters.renderHtml(dataArrived, webRequestWrapper); - this->_customParameterGroups.renderHtml(dataArrived, webRequestWrapper); - - content = htmlFormatProvider->getFormEnd(); - - if (this->_updatePath != nullptr) - { - String pitem = htmlFormatProvider->getUpdate(); - pitem.replace("{u}", this->_updatePath); - content += pitem; - } - - // -- Fill config version string; - { - String pitem = htmlFormatProvider->getConfigVer(); - pitem.replace("{v}", this->_configVersion); - content += pitem; - } - - content += htmlFormatProvider->getEnd(); - - webRequestWrapper->sendContent(content); - webRequestWrapper->sendContent(F("")); - webRequestWrapper->stop(); - } - else - { - // -- Save config - IOTWEBCONF_DEBUG_LINE(F("Updating configuration")); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - this->_systemParameters.debugTo(&Serial); - this->_customParameterGroups.debugTo(&Serial); - Serial.println(); -#endif - this->_systemParameters.update(webRequestWrapper); - this->_customParameterGroups.update(webRequestWrapper); - - this->saveConfig(); - - String page = htmlFormatProvider->getHead(); - page.replace("{v}", "Config ESP"); - page += htmlFormatProvider->getScript(); - page += htmlFormatProvider->getStyle(); -// page += _customHeadElement; - page += htmlFormatProvider->getHeadExtension(); - page += htmlFormatProvider->getHeadEnd(); - page += "Configuration saved. "; - if (this->_apPassword[0] == '\0') - { - page += F("You must change the default AP password to continue. Return " - "to configuration page."); - } - else if (this->_wifiParameters._wifiSsid[0] == '\0') - { - page += F("You must provide the local wifi settings to continue. Return " - "to configuration page."); - } - else if (this->_state == NotConfigured) - { - page += F("Please disconnect from WiFi AP to continue!"); - } - else - { - page += F("Return to home page."); - } - page += htmlFormatProvider->getEnd(); - - webRequestWrapper->sendHeader("Content-Length", String(page.length())); - webRequestWrapper->send(200, "text/html; charset=UTF-8", page); - } -} - -bool IotWebConf::validateForm(WebRequestWrapper* webRequestWrapper) -{ - // -- Clean previous error messages. - this->_systemParameters.clearErrorMessage(); - this->_customParameterGroups.clearErrorMessage(); - - // -- Call external validator. - bool valid = true; - if (this->_formValidator != nullptr) - { - valid = this->_formValidator(webRequestWrapper); - } - - // -- Internal validation. - int l = webRequestWrapper->arg(this->_thingNameParameter.getId()).length(); - if (3 > l) - { - this->_thingNameParameter.errorMessage = - "Give a name with at least 3 characters."; - valid = false; - } - l = webRequestWrapper->arg(this->_apPasswordParameter.getId()).length(); - if ((0 < l) && (l < 8)) - { - this->_apPasswordParameter.errorMessage = - "Password length must be at least 8 characters."; - valid = false; - } - l = webRequestWrapper->arg(this->_wifiParameters.wifiPasswordParameter.getId()).length(); - if ((0 < l) && (l < 8)) - { - this->_wifiParameters.wifiPasswordParameter.errorMessage = - "Password length must be at least 8 characters."; - valid = false; - } - -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(F("Form validation result is: ")); - Serial.println(valid ? "positive" : "negative"); -#endif - - return valid; -} - -void IotWebConf::handleNotFound(WebRequestWrapper* webRequestWrapper) -{ - if (this->handleCaptivePortal(webRequestWrapper)) - { - // If captive portal redirect instead of displaying the error page. - return; - } -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(F("Requested a non-existing page '")); - Serial.print(webRequestWrapper->uri()); - Serial.println("'"); -#endif - String message = "Requested a non-existing page\n\n"; - message += "URI: "; - message += webRequestWrapper->uri(); - message += "\n"; - - webRequestWrapper->sendHeader( - "Cache-Control", "no-cache, no-store, must-revalidate"); - webRequestWrapper->sendHeader("Pragma", "no-cache"); - webRequestWrapper->sendHeader("Expires", "-1"); - webRequestWrapper->sendHeader("Content-Length", String(message.length())); - webRequestWrapper->send(404, "text/plain", message); -} - -/** - * Redirect to captive portal if we got a request for another domain. - * Return true in that case so the page handler do not try to handle the request - * again. (Code from WifiManager project.) - */ -bool IotWebConf::handleCaptivePortal(WebRequestWrapper* webRequestWrapper) -{ - String host = webRequestWrapper->hostHeader(); - String thingName = String(this->_thingName); - thingName.toLowerCase(); - if (!isIp(host) && !host.startsWith(thingName)) - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print("Request for "); - Serial.print(host); - Serial.print(" redirected to "); - Serial.print(webRequestWrapper->localIP()); - Serial.print(":"); - Serial.println(webRequestWrapper->localPort()); -#endif - webRequestWrapper->sendHeader( - "Location", String("http://") + toStringIp(webRequestWrapper->localIP()) + ":" + webRequestWrapper->localPort(), true); - webRequestWrapper->send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. - webRequestWrapper->stop(); // Stop is needed because we sent no content length - return true; - } - return false; -} - -/** Is this an IP? */ -bool IotWebConf::isIp(String str) -{ - for (size_t i = 0; i < str.length(); i++) - { - int c = str.charAt(i); - if (c != '.' && c != ':' && (c < '0' || c > '9')) - { - return false; - } - } - return true; -} - -/** IP to String? */ -String IotWebConf::toStringIp(IPAddress ip) -{ - String res = ""; - for (int i = 0; i < 3; i++) - { - res += String((ip >> (8 * i)) & 0xFF) + "."; - } - res += String(((ip >> 8 * 3)) & 0xFF); - return res; -} - -///////////////////////////////////////////////////////////////////////////////// - -void IotWebConf::delay(unsigned long m) -{ - unsigned long delayStart = millis(); - while (m > millis() - delayStart) - { - this->doLoop(); - // -- Note: 1ms might not be enough to perform a full yield. So - // 'yield' in 'doLoop' is eventually a good idea. - delayMicroseconds(1000); - } -} - -void IotWebConf::doLoop() -{ - doBlink(); - yield(); // -- Yield should not be necessary, but cannot hurt either. - if (this->_state == Boot) - { - // -- After boot, fall immediately to AP mode. - NetworkState startupState = ApMode; - if (this->_startupOffLine) - { - startupState = OffLine; - } - else if (this->_skipApStartup) - { - if (mustStayInApMode()) - { - IOTWEBCONF_DEBUG_LINE( - F("SkipApStartup is requested, but either no WiFi was set up, or " - "configButton was pressed.")); - } - else - { - // -- Startup state can be WiFi, if it is requested and also possible. - IOTWEBCONF_DEBUG_LINE(F("SkipApStartup mode was applied")); - startupState = Connecting; - } - } - this->changeState(startupState); - } - else if ( - (this->_state == NotConfigured) || - (this->_state == ApMode)) - { - // -- We must only leave the AP mode, when no slaves are connected. - // -- Other than that AP mode has a timeout. E.g. after boot, or when retry - // connecting to WiFi - checkConnection(); - checkApTimeout(); - this->_dnsServer->processNextRequest(); - this->_webServerWrapper->handleClient(); - } - else if (this->_state == Connecting) - { - if (checkWifiConnection()) - { - this->changeState(OnLine); - return; - } - } - else if (this->_state == OnLine) - { - // -- In server mode we provide web interface. And check whether it is time - // to run the client. - this->_webServerWrapper->handleClient(); - if (WiFi.status() != WL_CONNECTED) - { - IOTWEBCONF_DEBUG_LINE(F("Not connected. Try reconnect...")); - this->changeState(Connecting); - return; - } - } -} - -/** - * What happens, when a state changed... - */ -void IotWebConf::changeState(NetworkState newState) -{ - switch (newState) - { - case ApMode: - { - // -- In AP mode we must override the default AP password. Otherwise we stay - // in STATE_NOT_CONFIGURED. - if (mustUseDefaultPassword()) - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - if (this->_forceDefaultPassword) - { - Serial.println("AP mode forced by reset pin"); - } - else - { - Serial.println("AP password was not set in configuration"); - } -#endif - newState = NotConfigured; - } - break; - } - default: - break; - } -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print("State changing from: "); - Serial.print(this->_state); - Serial.print(" to "); - Serial.println(newState); -#endif - NetworkState oldState = this->_state; - this->_state = newState; - this->stateChanged(oldState, newState); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print("State changed from: "); - Serial.print(oldState); - Serial.print(" to "); - Serial.println(newState); -#endif -} - -/** - * What happens, when a state changed... - */ -void IotWebConf::stateChanged(NetworkState oldState, NetworkState newState) -{ -// updateOutput(); - switch (newState) - { - case OffLine: - WiFi.disconnect(true); - WiFi.mode(WIFI_OFF); - this->blinkInternal(22000, 6); - break; - case ApMode: - case NotConfigured: - if (newState == ApMode) - { - this->blinkInternal(300, 90); - } - else - { - this->blinkInternal(300, 50); - } - if ((oldState == Connecting) || - (oldState == OnLine)) - { - WiFi.disconnect(true); - } - setupAp(); - if (this->_updateServerSetupFunction != nullptr) - { - this->_updateServerSetupFunction(this->_updatePath); - } - this->_webServerWrapper->begin(); - this->_apConnectionState = NoConnections; - this->_apStartTimeMs = millis(); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - if (mustStayInApMode()) - { - if (this->_forceDefaultPassword) - { - Serial.println(F("Default password was forced.")); - } - if (this->_apPassword[0] == '\0') - { - Serial.println(F("AP password was not set.")); - } - if (this->_wifiParameters._wifiSsid[0] == '\0') - { - Serial.println(F("WiFi SSID was not set.")); - } - if (this->_forceApMode) - { - Serial.println(F("AP was forced.")); - } - Serial.println(F("Will stay in AP mode.")); - } - else - { - Serial.print(F("AP timeout (ms): ")); - Serial.println(this->_apTimeoutMs); - } -#endif - break; - case Connecting: - if ((oldState == ApMode) || - (oldState == NotConfigured)) - { - stopAp(); - } - if ((oldState == Boot) && (this->_updateServerSetupFunction != nullptr)) - { - // We've skipped AP mode, so update server needs to be set up now. - this->_updateServerSetupFunction(this->_updatePath); - } - this->blinkInternal(1000, 50); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print("Connecting to ["); - Serial.print(this->_wifiAuthInfo.ssid); -# ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL - Serial.print("] with password ["); - Serial.print(this->_wifiAuthInfo.password); - Serial.println("]"); -# else - Serial.println(F("] (password is hidden)")); -# endif - Serial.print(F("WiFi timeout (ms): ")); - Serial.println(this->_wifiConnectionTimeoutMs); -#endif - this->_wifiConnectionStart = millis(); - WiFi.mode(WIFI_STA); - // Hostname must be set right before WiFi.begin in order to work reliably, - // and will be set only once WiFi.begin has been called. - WiFi.setHostname(this->_thingName); - this->_wifiConnectionHandler( - this->_wifiAuthInfo.ssid, this->_wifiAuthInfo.password); - break; - case OnLine: - this->blinkInternal(8000, 2); - if (this->_updateServerUpdateCredentialsFunction != nullptr) - { - this->_updateServerUpdateCredentialsFunction( - IOTWEBCONF_ADMIN_USER_NAME, this->_apPassword); - } - this->_webServerWrapper->begin(); - IOTWEBCONF_DEBUG_LINE(F("Accepting connection")); - if (this->_wifiConnectionCallback != nullptr) - { - this->_wifiConnectionCallback(); - } - break; - default: - break; - } -} - -void IotWebConf::checkApTimeout() -{ - if ( !mustStayInApMode() ) - { - // -- Only move on, when we have a valid WifF and AP configured. - if ((this->_apConnectionState == Disconnected) || - (((millis() - this->_apStartTimeMs) > this->_apTimeoutMs) && - (this->_apConnectionState != HasConnection))) - { - this->changeState(Connecting); - } - } -} - -void IotWebConf::goOnLine(bool apMode) -{ - if (this->_state != OffLine) - { - IOTWEBCONF_DEBUG_LINE(F("Requested OnLine mode, but was not offline.")); - return; - } - if (apMode || mustStayInApMode()) - { - this->changeState(ApMode); - } - else - { - this->changeState(Connecting); - } -} - -/** - * Checks whether we have anyone joined to our AP. - * If so, we must not change state. But when our guest leaved, we can - * immediately move on. - */ -void IotWebConf::checkConnection() -{ - if ((this->_apConnectionState == NoConnections) && - (WiFi.softAPgetStationNum() > 0)) - { - this->_apConnectionState = HasConnection; - IOTWEBCONF_DEBUG_LINE(F("Connection to AP.")); - } - else if ( - (this->_apConnectionState == HasConnection) && - (WiFi.softAPgetStationNum() == 0)) - { - this->_apConnectionState = Disconnected; - IOTWEBCONF_DEBUG_LINE(F("Disconnected from AP.")); - if (this->_forceDefaultPassword) - { - IOTWEBCONF_DEBUG_LINE(F("Releasing forced AP mode.")); - this->_forceDefaultPassword = false; - } - } -} - -bool IotWebConf::checkWifiConnection() -{ - if (WiFi.status() != WL_CONNECTED) - { - if ((millis() - this->_wifiConnectionStart) > this->_wifiConnectionTimeoutMs) - { - // -- WiFi not available, fall back to AP mode. - IOTWEBCONF_DEBUG_LINE(F("Giving up.")); - WiFi.disconnect(true); - WifiAuthInfo* newWifiAuthInfo = _wifiConnectionFailureHandler(); - if (newWifiAuthInfo != nullptr) - { - // -- Try connecting with another connection info. - this->_wifiAuthInfo.ssid = newWifiAuthInfo->ssid; - this->_wifiAuthInfo.password = newWifiAuthInfo->password; - this->changeState(Connecting); - } - else - { - this->changeState(ApMode); - } - } - return false; - } - - // -- Connected -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.println("WiFi connected"); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); -#endif - - return true; -} - -void IotWebConf::setupAp() -{ - WiFi.mode(WIFI_AP); - -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print("Setting up AP: "); - Serial.println(this->_thingName); -#endif - if (this->_state == NotConfigured) - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print("With default password: "); -# ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL - Serial.println(this->_initialApPassword); -# else - Serial.println(F("")); -# endif -#endif - this->_apConnectionHandler(this->_thingName, this->_initialApPassword); - } - else - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print("Use password: "); -# ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL - Serial.println(this->_apPassword); -# else - Serial.println(F("")); -# endif -#endif - this->_apConnectionHandler(this->_thingName, this->_apPassword); - } - -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(F("AP IP address: ")); - Serial.println(WiFi.softAPIP()); -#endif - // delay(500); // Without delay I've seen the IP address blank - // Serial.print(F("AP IP address: ")); - // Serial.println(WiFi.softAPIP()); - - /* Setup the DNS server redirecting all the domains to the apIP */ - this->_dnsServer->setErrorReplyCode(DNSReplyCode::NoError); - this->_dnsServer->start(IOTWEBCONF_DNS_PORT, "*", WiFi.softAPIP()); -} - -void IotWebConf::stopAp() -{ - WiFi.softAPdisconnect(true); - WiFi.mode(WIFI_OFF); -} - -//////////////////////////////////////////////////////////////////// - -void IotWebConf::blink(unsigned long repeatMs, byte dutyCyclePercent) -{ - if (repeatMs == 0) - { - this->stopCustomBlink(); - } - else - { - this->_blinkOnMs = repeatMs * dutyCyclePercent / 100; - this->_blinkOffMs = repeatMs * (100 - dutyCyclePercent) / 100; - } -} - -void IotWebConf::fineBlink(unsigned long onMs, unsigned long offMs) -{ - this->_blinkOnMs = onMs; - this->_blinkOffMs = offMs; -} - -void IotWebConf::stopCustomBlink() -{ - this->_blinkOnMs = this->_internalBlinkOnMs; - this->_blinkOffMs = this->_internalBlinkOffMs; -} - -void IotWebConf::blinkInternal(unsigned long repeatMs, byte dutyCyclePercent) -{ - this->blink(repeatMs, dutyCyclePercent); - this->_internalBlinkOnMs = this->_blinkOnMs; - this->_internalBlinkOffMs = this->_blinkOffMs; -} - -void IotWebConf::doBlink() -{ - if (IOTWEBCONF_STATUS_ENABLED) - { - unsigned long now = millis(); - unsigned long delayMs = - this->_blinkStateOn ? this->_blinkOnMs : this->_blinkOffMs; - if (delayMs < now - this->_lastBlinkTime) - { - this->_blinkStateOn = !this->_blinkStateOn; - this->_lastBlinkTime = now; - digitalWrite(this->_statusPin, this->_blinkStateOn ? this->_statusOnLevel : !this->_statusOnLevel); - } - } -} - -void IotWebConf::forceApMode(bool doForce) -{ - if (this->_forceApMode == doForce) - { - // Already in the requested mode; - return; - } - - this->_forceApMode = doForce; - if (doForce) - { - if (this->_state != ApMode) - { - IOTWEBCONF_DEBUG_LINE(F("Start forcing AP mode")); - this->changeState(ApMode); - } - } - else - { - if (this->_state == ApMode) - { - if (this->mustStayInApMode()) - { - IOTWEBCONF_DEBUG_LINE(F("Requested stopping to force AP mode, but we cannot leave the AP mode now.")); - } - else - { - IOTWEBCONF_DEBUG_LINE(F("Stopping AP mode force.")); - this->changeState(Connecting); - } - } - } -} - -bool IotWebConf::connectAp(const char* apName, const char* password) -{ - return WiFi.softAP(apName, password); -} -void IotWebConf::connectWifi(const char* ssid, const char* password) -{ - WiFi.begin(ssid, password); -} -WifiAuthInfo* IotWebConf::handleConnectWifiFailure() -{ - return nullptr; -} - -} // end namespace \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConf.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConf.h deleted file mode 100644 index ddf708b4b1b94891e91fc8e62abcc62bf7c2a9e4..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConf.h +++ /dev/null @@ -1,662 +0,0 @@ -/** - * IotWebConf.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef IotWebConf_h -#define IotWebConf_h - -#include -#include "IotWebConfParameter.h" -#include "IotWebConfSettings.h" -#include "IotWebConfWebServerWrapper.h" - -#ifdef ESP8266 -# include -# include -#elif defined(ESP32) -# include -# include -#endif -#include // -- For captive portal - -#ifdef ESP8266 -# ifndef WebServer -# define WebServer ESP8266WebServer -# endif -#endif - -// -- HTML page fragments -const char IOTWEBCONF_HTML_HEAD[] PROGMEM = "{v}\n"; -const char IOTWEBCONF_HTML_STYLE_INNER[] PROGMEM = ".de{background-color:#ffaaaa;} .em{font-size:0.8em;color:#bb0000;padding-bottom:0px;} .c{text-align: center;} div,input,select{padding:5px;font-size:1em;} input{width:95%;} select{width:100%} input[type=checkbox]{width:auto;scale:1.5;margin:10px;} body{text-align: center;font-family:verdana;} button{border:0;border-radius:0.3rem;background-color:#16A1E7;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;} fieldset{border-radius:0.3rem;margin: 0px;}\n"; -const char IOTWEBCONF_HTML_SCRIPT_INNER[] PROGMEM = "function c(l){document.getElementById('s').value=l.innerText||l.textContent;document.getElementById('p').focus();}; function pw(id) { var x=document.getElementById(id); if(x.type==='password') {x.type='text';} else {x.type='password';} };"; -const char IOTWEBCONF_HTML_HEAD_END[] PROGMEM = ""; -const char IOTWEBCONF_HTML_BODY_INNER[] PROGMEM = "
\n"; -const char IOTWEBCONF_HTML_FORM_START[] PROGMEM = "
\n"; -const char IOTWEBCONF_HTML_FORM_END[] PROGMEM = "
\n"; -const char IOTWEBCONF_HTML_SAVED[] PROGMEM = "
Configuration saved
Return to home page.
\n"; -const char IOTWEBCONF_HTML_END[] PROGMEM = "
"; -const char IOTWEBCONF_HTML_UPDATE[] PROGMEM = "\n"; -const char IOTWEBCONF_HTML_CONFIG_VER[] PROGMEM = "
Firmware config version '{v}'
\n"; - -// -- User name on login. -#define IOTWEBCONF_ADMIN_USER_NAME "admin" - -namespace iotwebconf -{ - -// -- AP connection state -enum ApConnectionState -{ - NoConnections, // -- No connection on AP. - HasConnection, // -- Has connection on AP. - Disconnected // -- All previous connection on AP was disconnected. -}; - -enum NetworkState -{ - Boot, - NotConfigured, - ApMode, - Connecting, - OnLine, - OffLine -}; - -class IotWebConf; - -typedef struct WifiAuthInfo -{ - const char* ssid; - const char* password; -} WifiAuthInfo; - -/** - * Class for providing HTML format segments. - */ -class HtmlFormatProvider -{ -public: - virtual String getHead() { return FPSTR(IOTWEBCONF_HTML_HEAD); } - virtual String getStyle() { return ""; } - virtual String getScript() { return ""; } - virtual String getHeadExtension() { return ""; } - virtual String getHeadEnd() { return String(FPSTR(IOTWEBCONF_HTML_HEAD_END)) + getBodyInner(); } - virtual String getFormStart() { return FPSTR(IOTWEBCONF_HTML_FORM_START); } - virtual String getFormEnd() { return FPSTR(IOTWEBCONF_HTML_FORM_END); } - virtual String getFormSaved() { return FPSTR(IOTWEBCONF_HTML_SAVED); } - virtual String getEnd() { return FPSTR(IOTWEBCONF_HTML_END); } - virtual String getUpdate() { return FPSTR(IOTWEBCONF_HTML_UPDATE); } - virtual String getConfigVer() { return FPSTR(IOTWEBCONF_HTML_CONFIG_VER); } -protected: - virtual String getStyleInner() { return FPSTR(IOTWEBCONF_HTML_STYLE_INNER); } - virtual String getScriptInner() { return FPSTR(IOTWEBCONF_HTML_SCRIPT_INNER); } - virtual String getBodyInner() { return FPSTR(IOTWEBCONF_HTML_BODY_INNER); } -}; - -class StandardWebRequestWrapper : public WebRequestWrapper -{ -public: - StandardWebRequestWrapper(WebServer* server) { this->_server = server; }; - - const String hostHeader() const override { return this->_server->hostHeader(); }; - IPAddress localIP() override { return this->_server->client().localIP(); }; - uint16_t localPort() override { return this->_server->client().localPort(); }; - const String uri() const { return this->_server->uri(); }; - bool authenticate(const char * username, const char * password) override - { return this->_server->authenticate(username, password); }; - void requestAuthentication() override - { this->_server->requestAuthentication(); }; - bool hasArg(const String& name) override { return this->_server->hasArg(name); }; - String arg(const String name) override { return this->_server->arg(name); }; - void sendHeader(const String& name, const String& value, bool first = false) override - { this->_server->sendHeader(name, value, first); }; - void setContentLength(const size_t contentLength) override - { this->_server->setContentLength(contentLength); }; - void send(int code, const char* content_type = nullptr, const String& content = String("")) override - { this->_server->send(code, content_type, content); }; - void sendContent(const String& content) override { this->_server->sendContent(content); }; - void stop() override { this->_server->client().stop(); }; - -private: - WebServer* _server; - friend IotWebConf; -}; - -class StandardWebServerWrapper : public WebServerWrapper -{ -public: - StandardWebServerWrapper(WebServer* server) { this->_server = server; }; - - void handleClient() override { this->_server->handleClient(); }; - void begin() override { this->_server->begin(); }; - -private: - StandardWebServerWrapper() { }; - WebServer* _server; - friend IotWebConf; -}; - -class WifiParameterGroup : public ParameterGroup -{ -public: - WifiParameterGroup(const char* id, const char* label = nullptr) : ParameterGroup(id, label) - { - this->addItem(&this->wifiSsidParameter); - this->addItem(&this->wifiPasswordParameter); - } - TextParameter wifiSsidParameter = - TextParameter("WiFi SSID", "iwcWifiSsid", this->_wifiSsid, IOTWEBCONF_WORD_LEN); - PasswordParameter wifiPasswordParameter = - PasswordParameter("WiFi password", "iwcWifiPassword", this->_wifiPassword, IOTWEBCONF_PASSWORD_LEN); - char _wifiSsid[IOTWEBCONF_WORD_LEN]; - char _wifiPassword[IOTWEBCONF_PASSWORD_LEN]; -}; - -/** - * Main class of the module. - */ -class IotWebConf -{ -public: - /** - * Create a new configuration handler. - * @thingName - Initial value for the thing name. Used in many places like AP name, can be changed by the user. - * @dnsServer - A created DNSServer, that can be configured for captive portal. - * @server - A created web server. Will be started upon connection success. - * @initialApPassword - Initial value for AP mode. Can be changed by the user. - * @configVersion - When the software is updated and the configuration is changing, this key should also be changed, - * so that the config portal will force the user to reenter all the configuration values. - */ - IotWebConf( - const char* thingName, DNSServer* dnsServer, WebServer* server, - const char* initialApPassword, const char* configVersion = "init") : - IotWebConf(thingName, dnsServer, &this->_standardWebServerWrapper, initialApPassword, configVersion) - { - this->_standardWebServerWrapper._server = server; - } - - IotWebConf( - const char* thingName, DNSServer* dnsServer, WebServerWrapper* server, - const char* initialApPassword, const char* configVersion = "init"); - - /** - * Provide an Arduino pin here, that has a button connected to it with the other end of the pin is connected to GND. - * The button pin is queried at for input on boot time (init time). - * If the button was pressed, the thing will enter AP mode with the initial password. - * Must be called before init()! - * @configPin - An Arduino pin. Will be configured as INPUT_PULLUP! - */ - void setConfigPin(int configPin); - - /** - * Provide an Arduino pin for status indicator (LOW = on). Blink codes: - * - Rapid blinks - The thing is in AP mode with default password. - * - Rapid blinks, but mostly on - AP mode, waiting for configuration changes. - * - Normal blinks - Connecting to WiFi. - * - Mostly off with rare rapid blinks - WiFi is connected performing normal operation. - * User can also apply custom blinks. See blink() method! - * Must be called before init()! - * @statusPin - An Arduino pin. Will be configured as OUTPUT! - * @statusOnLevel - Logic level of the On state of the status pin. Default is LOW. - */ - void setStatusPin(int statusPin, int statusOnLevel = LOW); - - /** - * Add an UpdateServer instance to the system. The firmware update link will appear on the config portal. - * The UpdateServer will be added to the WebServer with the path provided here (or with "firmware", - * if none was provided). - * Login user will be IOTWEBCONF_ADMIN_USER_NAME, password is the password provided in the config portal. - * Should be called before init()! - * @updateServer - An uninitialized UpdateServer instance. - * @updatePath - (Optional) The path to set up the UpdateServer with. Will be also used in the config portal. - */ - void setupUpdateServer( - std::function setup, - std::function updateCredentials, - const char* updatePath = "/firmware") - { - this->_updateServerSetupFunction = setup; - this->_updateServerUpdateCredentialsFunction = updateCredentials; - this->_updatePath = updatePath; - } - - /** - * Start up the IotWebConf module. - * Loads all configuration from the EEPROM, and initialize the system. - * Will return false, if no configuration (with specified config version) was found in the EEPROM. - */ - bool init(); - - /** - * IotWebConf is a non-blocking, state controlled system. Therefor it should be - * regularly triggered from the user code. - * So call this method any time you can. - */ - void doLoop(); - - /** - * Each WebServer URL handler method should start with calling this method. - * If this method return true, the request was already served by it. - */ - bool handleCaptivePortal(WebRequestWrapper* webRequestWrapper); - bool handleCaptivePortal() - { - StandardWebRequestWrapper webRequestWrapper = StandardWebRequestWrapper(this->_standardWebServerWrapper._server); - return handleCaptivePortal(&webRequestWrapper); - } - - /** - * Config URL web request handler. Call this method to handle config request. - */ - void handleConfig(WebRequestWrapper* webRequestWrapper); - void handleConfig() - { - StandardWebRequestWrapper webRequestWrapper = StandardWebRequestWrapper(this->_standardWebServerWrapper._server); - handleConfig(&webRequestWrapper); - } - - /** - * URL-not-found web request handler. Used for handling captive portal request. - */ - void handleNotFound(WebRequestWrapper* webRequestWrapper); - void handleNotFound() - { - StandardWebRequestWrapper webRequestWrapper = StandardWebRequestWrapper(this->_standardWebServerWrapper._server); - handleNotFound(&webRequestWrapper); - } - - /** - * Specify a callback method, that will be called upon WiFi connection success. - * Should be called before init()! - */ - void setWifiConnectionCallback(std::function func); - - /** - * Specify a callback method, that will be called when settings is being changed. - * This is very handy if you have other routines, that are modifying the "EEPROM" - * parallel to IotWebConf, now this is the time to disable these routines. - * Should be called before init()! - */ - void setConfigSavingCallback(std::function func); - - /** - * Specify a callback method, that will be called when settings have been changed. - * All pending EEPROM manipulations are done by the time this method is called. - * Should be called before init()! - */ - void setConfigSavedCallback(std::function func); - - /** - * Specify a callback method, that will be called when form validation is required. - * If the method will return false, the configuration will not be saved. - * Should be called before init()! - */ - void setFormValidator(std::function func); - - /** - * Specify your custom Access Point connection handler. Please use IotWebConf::connectAp() as - * reference when implementing your custom solution. - */ - void setApConnectionHandler( - std::function func) - { - _apConnectionHandler = func; - } - - /** - * Specify your custom WiFi connection handler. Please use IotWebConf::connectWifi() as - * reference when implementing your custom solution. - * Your method will be called when IotWebConf trying to establish - * connection to a WiFi network. - */ - void setWifiConnectionHandler( - std::function func) - { - _wifiConnectionHandler = func; - } - - /** - * With this method you can specify your custom WiFi timeout handler. - * This handler can manage what should happen, when WiFi connection timed out. - * By default the handler implementation returns with nullptr, as seen on reference implementation - * IotWebConf::handleConnectWifiFailure(). This means we need to fall back to AP mode. - * If it method returns with a (new) WiFi settings, it is used as a next try. - * Note, that in case once you have returned with nullptr, you might also want to - * resetWifiAuthInfo(), that sets the auth info used for the next time to the - * one set up in the admin portal. - * Note, that this feature is provided because of the option of providing multiple - * WiFi settings utilized by the MultipleWifiAddition class. (See IotWebConfMultipleWifi.h) - */ - void setWifiConnectionFailedHandler( std::function func ) - { - _wifiConnectionFailureHandler = func; - } - - /** - * Add a custom parameter group, that will be handled by the IotWebConf module. - * The parameters in this group will be saved to/loaded from EEPROM automatically, - * and will appear on the config portal. - * Must be called before init()! - */ - void addParameterGroup(ParameterGroup* group); - - /** - * Add a custom parameter group, that will be handled by the IotWebConf module. - * The parameters in this group will be saved to/loaded from EEPROM automatically, - * but will NOT appear on the config portal. - * Must be called before init()! - */ - void addHiddenParameter(ConfigItem* parameter); - - /** - * Add a custom parameter group, that will be handled by the IotWebConf module. - * The parameters in this group will be saved to/loaded from EEPROM automatically, - * but will NOT appear on the config portal. - * Must be called before init()! - */ - void addSystemParameter(ConfigItem* parameter); - - /** - * Getter for the actually configured thing name. - */ - char* getThingName(); - - /** - * Use this delay, to prevent blocking IotWebConf. - */ - void delay(unsigned long millis); - - /** - * IotWebConf tries to connect to the local network for an amount of time before falling back to AP mode. - * The default amount can be updated with this setter. - * Should be called before init()! - */ - void setWifiConnectionTimeoutMs(unsigned long millis); - - /** - * Interrupts internal blinking cycle and applies new values for - * blinking the status LED (if one configured with setStatusPin() prior init() - * ). - * @repeatMs - Defines the the period of one on-off cycle in milliseconds. - * @dutyCyclePercent - LED on/off percent. 100 means always on, 0 means - * always off. When called with repeatMs = 0, then internal blink cycle will - * be continued. - */ - void blink(unsigned long repeatMs, byte dutyCyclePercent); - - /** - * Similar to blink, but here we define exact on and off times for more - * precise timings. - * @onMs - Milliseconds for the LED turned on. - * @offMs - Milliseconds for the LED turned off. - */ - void fineBlink(unsigned long onMs, unsigned long offMs); - - /** - * Stop custom blinking defined by blink() or fineBlink() and continues with - * the internal blink cycle. - */ - void stopCustomBlink(); - - /** - * Disables blinking, so allows user code to control same LED. - */ - void disableBlink() { this->_blinkEnabled = false; } - - /** - * Enables blinking if it has been disabled by disableBlink(). - */ - void enableBlink() { this->_blinkEnabled = true; } - - /** - * Returns blink enabled state modified by disableBlink() and enableBlink(). - */ - bool isBlinkEnabled() { return this->_blinkEnabled; } - - /** - * Return the current state. - */ - NetworkState getState() { return this->_state; }; - - /** - * This method can be used to set the AP timeout directly without modifying the apTimeoutParameter. - * Note, that apTimeoutMs value will be reset to the value of apTimeoutParameter on init and on config save. - */ - void setApTimeoutMs(unsigned long apTimeoutMs) - { - this->_apTimeoutMs = apTimeoutMs; - }; - - /** - * Returns the actual value of the AP timeout in use. - */ - unsigned long getApTimeoutMs() { return this->_apTimeoutMs; }; - - /** - * Returns the current WiFi authentication credentials. These are usually the configured ones, - * but might be overwritten by setWifiConnectionFailedHandler(). - */ - WifiAuthInfo getWifiAuthInfo() { return _wifiAuthInfo; }; - - /** - * Resets the authentication credentials for WiFi connection to the configured one. - * With the return value of setWifiConnectionFailedHandler() one can provide alternative connection settings, - * that can be reset with resetWifiAuthInfo(). - */ - void resetWifiAuthInfo() - { - _wifiAuthInfo = {this->_wifiParameters._wifiSsid, this->_wifiParameters._wifiPassword}; - }; - - /** - * - */ - void startupOffLine() { this->_startupOffLine = true; } - - /** - * By default IotWebConf starts up in AP mode. Calling this method before the init will force IotWebConf - * to connect immediately to the configured WiFi network. - * Note, this method only takes effect, when WiFi mode is enabled, thus when a valid WiFi connection is - * set up, and AP mode is not forced by ConfigPin (see setConfigPin() for details). - */ - void skipApStartup() { this->_skipApStartup = true; } - - /** - * By default IotWebConf will continue startup in WiFi mode, when no configuration request arrived - * in AP mode. With this method holding the AP mode can be forced. - * Further more, instant AP mode can forced even when we are currently in WiFi mode. - * @value - When TRUE, AP mode is forced/entered. - * When FALSE, AP mode is released, normal operation will continue. - */ - void forceApMode(bool value); - - /** - * - */ - void goOffLine() { this->changeState(OffLine); } - - /** - * - */ - void goOnLine(bool apMode = true); - - /** - * - */ - unsigned long getApStartTimeMs() { return this->_apStartTimeMs; } - - /** - * Get internal parameters, for manual handling. - * Normally you don't need to access these parameters directly. - * Note, that changing valueBuffer of these parameters should be followed by saveConfig()! - */ - ParameterGroup* getRootParameterGroup() - { - return &this->_allParameters; - }; - ParameterGroup* getSystemParameterGroup() - { - return &this->_systemParameters; - }; - Parameter* getThingNameParameter() - { - return &this->_thingNameParameter; - }; - Parameter* getApPasswordParameter() - { - return &this->_apPasswordParameter; - }; - WifiParameterGroup* getWifiParameterGroup() - { - return &this->_wifiParameters; - }; - Parameter* getWifiSsidParameter() - { - return &this->_wifiParameters.wifiSsidParameter; - }; - Parameter* getWifiPasswordParameter() - { - return &this->_wifiParameters.wifiPasswordParameter; - }; - Parameter* getApTimeoutParameter() - { - return &this->_apTimeoutParameter; - }; - - /** - * If config parameters are modified directly, the new values can be saved by this method. - * Note, that init() must pretend saveConfig()! - * Also note, that saveConfig writes to EEPROM, and EEPROM can be written only some thousand times - * in the lifetime of an ESP8266 module. - */ - void saveConfig(); - - /** - * Loads all configuration from the EEPROM without initializing the system. - * Will return false, if no configuration (with specified config version) was found in the EEPROM. - */ - bool loadConfig(); - - /** - * With this method you can override the default HTML format provider to - * provide custom HTML segments. - */ - void - setHtmlFormatProvider(HtmlFormatProvider* customHtmlFormatProvider) - { - this->htmlFormatProvider = customHtmlFormatProvider; - } - HtmlFormatProvider* getHtmlFormatProvider() - { - return this->htmlFormatProvider; - } - -private: - const char* _initialApPassword = nullptr; - const char* _configVersion; - DNSServer* _dnsServer; - WebServerWrapper* _webServerWrapper; - StandardWebServerWrapper _standardWebServerWrapper = StandardWebServerWrapper(); - std::function - _updateServerSetupFunction = nullptr; - std::function - _updateServerUpdateCredentialsFunction = nullptr; - int _configPin = -1; - int _statusPin = -1; - int _statusOnLevel = LOW; - const char* _updatePath = nullptr; - bool _forceDefaultPassword = false; - bool _startupOffLine = false; - bool _skipApStartup = false; - bool _forceApMode = false; - ParameterGroup _allParameters = ParameterGroup("iwcAll"); - ParameterGroup _systemParameters = ParameterGroup("iwcSys", "System configuration"); - ParameterGroup _customParameterGroups = ParameterGroup("iwcCustom"); - ParameterGroup _hiddenParameters = ParameterGroup("hidden"); - WifiParameterGroup _wifiParameters = WifiParameterGroup("iwcWifi0"); - TextParameter _thingNameParameter = - TextParameter("Thing name", "iwcThingName", this->_thingName, IOTWEBCONF_WORD_LEN); - PasswordParameter _apPasswordParameter = - PasswordParameter("AP password", "iwcApPassword", this->_apPassword, IOTWEBCONF_PASSWORD_LEN); - NumberParameter _apTimeoutParameter = - NumberParameter("Startup delay (seconds)", "iwcApTimeout", this->_apTimeoutStr, IOTWEBCONF_WORD_LEN, IOTWEBCONF_DEFAULT_AP_MODE_TIMEOUT_SECS, nullptr, "min='1' max='600'"); - char _thingName[IOTWEBCONF_WORD_LEN]; - char _apPassword[IOTWEBCONF_PASSWORD_LEN]; - char _apTimeoutStr[IOTWEBCONF_WORD_LEN]; - unsigned long _apTimeoutMs; - // TODO: Add to WifiParameterGroup - unsigned long _wifiConnectionTimeoutMs = - IOTWEBCONF_DEFAULT_WIFI_CONNECTION_TIMEOUT_MS; - NetworkState _state = Boot; - unsigned long _apStartTimeMs = 0; - ApConnectionState _apConnectionState = NoConnections; - std::function _wifiConnectionCallback = nullptr; - std::function _configSavingCallback = nullptr; - std::function _configSavedCallback = nullptr; - std::function _formValidator = nullptr; - std::function _apConnectionHandler = - &(IotWebConf::connectAp); - std::function _wifiConnectionHandler = - &(IotWebConf::connectWifi); - std::function _wifiConnectionFailureHandler = - &(IotWebConf::handleConnectWifiFailure); - unsigned long _internalBlinkOnMs = 500; - unsigned long _internalBlinkOffMs = 500; - unsigned long _blinkOnMs = 500; - unsigned long _blinkOffMs = 500; - bool _blinkEnabled = true; - bool _blinkStateOn = false; - unsigned long _lastBlinkTime = 0; - unsigned long _wifiConnectionStart = 0; - // TODO: authinfo - WifiAuthInfo _wifiAuthInfo; - HtmlFormatProvider htmlFormatProviderInstance; - HtmlFormatProvider* htmlFormatProvider = &htmlFormatProviderInstance; - - int initConfig(); - bool testConfigVersion(); - void saveConfigVersion(); - void readEepromValue(int start, byte* valueBuffer, int length); - void writeEepromValue(int start, byte* valueBuffer, int length); - - bool validateForm(WebRequestWrapper* webRequestWrapper); - - void changeState(NetworkState newState); - void stateChanged(NetworkState oldState, NetworkState newState); - bool mustUseDefaultPassword() - { - return this->_forceDefaultPassword || (this->_apPassword[0] == '\0'); - } - bool mustStayInApMode() - { - return this->_forceDefaultPassword || (this->_apPassword[0] == '\0') || - (this->_wifiParameters._wifiSsid[0] == '\0') || this->_forceApMode; - } - bool isIp(String str); - String toStringIp(IPAddress ip); - void doBlink(); - void blinkInternal(unsigned long repeatMs, byte dutyCyclePercent); - - void checkApTimeout(); - void checkConnection(); - bool checkWifiConnection(); - void setupAp(); - void stopAp(); - - static bool connectAp(const char* apName, const char* password); - static void connectWifi(const char* ssid, const char* password); - static WifiAuthInfo* handleConnectWifiFailure(); -}; - -} // end namespace - -using iotwebconf::IotWebConf; - -#endif diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfESP32HTTPUpdateServer.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfESP32HTTPUpdateServer.h deleted file mode 100644 index b1357bf8c5cc79c74d85d950942b6ac4cd48a033..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfESP32HTTPUpdateServer.h +++ /dev/null @@ -1,169 +0,0 @@ -/** - * IotWebConfESP32HTTPUpdateServer.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - * - * Notes on IotWebConfESP32HTTPUpdateServer: - * ESP32 doesn't implement a HTTPUpdateServer. However it seams, that to code - * from ESP8266 covers nearly all the same functionality. - * So we need to implement our own HTTPUpdateServer for ESP32, and code is - * reused from - * https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPUpdateServer/src/ - * version: 41de43a26381d7c9d29ce879dd5d7c027528371b - */ -#ifdef ESP32 - -#ifndef __HTTP_UPDATE_SERVER_H -#define __HTTP_UPDATE_SERVER_H - -#include -#include -#include -#include -#include - -#define emptyString F("") - -class WebServer; - -class HTTPUpdateServer -{ - public: - HTTPUpdateServer(bool serial_debug=false) - { - _serial_output = serial_debug; - _server = nullptr; - _username = emptyString; - _password = emptyString; - _authenticated = false; - } - - - void setup(WebServer *server) - { - setup(server, emptyString, emptyString); - } - - void setup(WebServer *server, const String& path) - { - setup(server, path, emptyString, emptyString); - } - - void setup(WebServer *server, const String& username, const String& password) - { - setup(server, "/update", username, password); - } - - void setup(WebServer *server, const String& path, const String& username, const String& password) - { - _server = server; - _username = username; - _password = password; - - // handler for the /update form page - _server->on(path.c_str(), HTTP_GET, [&](){ - if(_username != emptyString && _password != emptyString && !_server->authenticate(_username.c_str(), _password.c_str())) - return _server->requestAuthentication(); - _server->send_P(200, PSTR("text/html"), serverIndex); - }); - - // handler for the /update form POST (once file upload finishes) - _server->on(path.c_str(), HTTP_POST, [&](){ - if(!_authenticated) - return _server->requestAuthentication(); - if (Update.hasError()) { - _server->send(200, F("text/html"), String(F("Update error: ")) + _updaterError); - } else { - _server->client().setNoDelay(true); - _server->send_P(200, PSTR("text/html"), successResponse); - delay(100); - _server->client().stop(); - ESP.restart(); - } - },[&](){ - // handler for the file upload, get's the sketch bytes, and writes - // them through the Update object - HTTPUpload& upload = _server->upload(); - - if(upload.status == UPLOAD_FILE_START){ - _updaterError = String(); - if (_serial_output) - Serial.setDebugOutput(true); - - _authenticated = (_username == emptyString || _password == emptyString || _server->authenticate(_username.c_str(), _password.c_str())); - if(!_authenticated){ - if (_serial_output) - Serial.printf("Unauthenticated Update\n"); - return; - } - - /// WiFiUDP::stopAll(); - if (_serial_output) - Serial.printf("Update: %s\n", upload.filename.c_str()); - /// uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; - /// if(!Update.begin(maxSketchSpace)){//start with max available size - if(!Update.begin(UPDATE_SIZE_UNKNOWN)){//start with max available size - _setUpdaterError(); - } - } else if(_authenticated && upload.status == UPLOAD_FILE_WRITE && !_updaterError.length()){ - if (_serial_output) Serial.printf("."); - if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){ - _setUpdaterError(); - } - } else if(_authenticated && upload.status == UPLOAD_FILE_END && !_updaterError.length()){ - if(Update.end(true)){ //true to set the size to the current progress - if (_serial_output) Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); - } else { - _setUpdaterError(); - } - if (_serial_output) Serial.setDebugOutput(false); - } else if(_authenticated && upload.status == UPLOAD_FILE_ABORTED){ - Update.end(); - if (_serial_output) Serial.println("Update was aborted"); - } - delay(0); - }); - } - - void updateCredentials(const String& username, const String& password) - { - _username = username; - _password = password; - } - - protected: - void _setUpdaterError() - { - if (_serial_output) Update.printError(Serial); - StreamString str; - Update.printError(str); - _updaterError = str.c_str(); - } - - private: - bool _serial_output; - WebServer *_server; - String _username; - String _password; - bool _authenticated; - String _updaterError; - const char* serverIndex PROGMEM = -R"(
- - -
- )"; - const char* successResponse PROGMEM = -"Update Success! Rebooting...\n"; -}; - -///////////////////////////////////////////////////////////////////////////////// - -#endif - -#endif diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfMultipleWifi.cpp b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfMultipleWifi.cpp deleted file mode 100644 index 3cc7a9a7b1bb4f78ef9b9cef10207e381dc65529..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfMultipleWifi.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/** - * IotWebConfMultipleWifi.cpp -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2021 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#include "IotWebConfMultipleWifi.h" - -namespace iotwebconf -{ - -MultipleWifiAddition::MultipleWifiAddition( - IotWebConf* iotWebConf, - ChainedWifiParameterGroup sets[], - size_t setsSize) -{ - this->_iotWebConf = iotWebConf; - this->_firstSet = &sets[0]; - this->_currentSet = &sets[0]; - - ChainedWifiParameterGroup* set = &sets[0]; - for(size_t i=1; isetNext(&sets[i]); - set = &sets[i]; - } -} - -void MultipleWifiAddition::init() -{ - // -- Add parameter groups. - ChainedWifiParameterGroup* set = this->_firstSet; - while(set != nullptr) - { - this->_iotWebConf->addSystemParameter(set); - set = (ChainedWifiParameterGroup*)set->getNext(); - } - - // -- Add custom format provider. - this->_iotWebConf->setHtmlFormatProvider( - &this->_optionalGroupHtmlFormatProvider); - - // -- Set up handler, that will selects next connection info to use. - this->_iotWebConf->setFormValidator([&](WebRequestWrapper* webRequestWrapper) - { - return this->formValidator(webRequestWrapper); - }); - - // -- Set up handler, that will selects next connection info to use. - this->_iotWebConf->setWifiConnectionFailedHandler([&]() - { - WifiAuthInfo* result; - while (true) - { - if (this->_currentSet == nullptr) - { - this->_currentSet = this->_firstSet; - this->_iotWebConf->resetWifiAuthInfo(); - result = nullptr; - break; - } - else - { - if (this->_currentSet->isActive()) - { - result = &this->_currentSet->wifiAuthInfo; - this->_currentSet = - (iotwebconf::ChainedWifiParameterGroup*)this->_currentSet->getNext(); - break; - } - else - { - this->_currentSet = - (iotwebconf::ChainedWifiParameterGroup*)this->_currentSet->getNext(); - } - } - } - return result; - }); -}; - -bool MultipleWifiAddition::formValidator( - WebRequestWrapper* webRequestWrapper) -{ - ChainedWifiParameterGroup* set = this->_firstSet; - bool valid = true; - - while(set != nullptr) - { - if (set->isActive()) - { - PasswordParameter* pwdParam = &set->wifiPasswordParameter; - int l = webRequestWrapper->arg(pwdParam->getId()).length(); - if ((0 < l) && (l < 8)) - { - pwdParam->errorMessage = "Password length must be at least 8 characters."; - valid = false; - } - } - - set = (ChainedWifiParameterGroup*)set->getNext(); - } - - return valid; -}; - -} diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfMultipleWifi.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfMultipleWifi.h deleted file mode 100644 index 33a5b48d7e062c9698dc5c6c0baed28e130ae6f2..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfMultipleWifi.h +++ /dev/null @@ -1,74 +0,0 @@ -/** - * IotWebConfMultipleWifi.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2021 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef IotWebConfMultipleWifi_h -#define IotWebConfMultipleWifi_h - -#include "IotWebConfOptionalGroup.h" -#include "IotWebConf.h" // for WebRequestWrapper - -namespace iotwebconf -{ - -class ChainedWifiParameterGroup : public ChainedParameterGroup -{ -public: - ChainedWifiParameterGroup(const char* id) : ChainedParameterGroup(id, "WiFi connection") - { - // -- Update parameter Ids to have unique ID for all parameters within the application. - snprintf(this->_wifiSsidParameterId, IOTWEBCONF_WORD_LEN, "%s-ssid", this->getId()); - snprintf(this->_wifiPasswordParameterId, IOTWEBCONF_WORD_LEN, "%s-pwd", this->getId()); - - this->addItem(&this->wifiSsidParameter); - this->addItem(&this->wifiPasswordParameter); - } - TextParameter wifiSsidParameter = - TextParameter("WiFi SSID", this->_wifiSsidParameterId, this->wifiSsid, IOTWEBCONF_WORD_LEN); - PasswordParameter wifiPasswordParameter = - PasswordParameter("WiFi password", this->_wifiPasswordParameterId, this->wifiPassword, IOTWEBCONF_PASSWORD_LEN); - char wifiSsid[IOTWEBCONF_WORD_LEN]; - char wifiPassword[IOTWEBCONF_PASSWORD_LEN]; - WifiAuthInfo wifiAuthInfo = { wifiSsid, wifiPassword}; -protected: - -private: - char _wifiSsidParameterId[IOTWEBCONF_WORD_LEN]; - char _wifiPasswordParameterId[IOTWEBCONF_WORD_LEN]; -}; - -class MultipleWifiAddition -{ -public: - MultipleWifiAddition( - IotWebConf* iotWebConf, - ChainedWifiParameterGroup sets[], - size_t setsSize); - /** - * Note, that init() calls setFormValidator, that overwrites existing - * formValidator setup. Thus your setFormValidator should be called - * _after_ multipleWifiAddition.init() . - */ - virtual void init(); - - virtual bool formValidator( - WebRequestWrapper* webRequestWrapper); - -protected: - IotWebConf* _iotWebConf; - ChainedWifiParameterGroup* _firstSet; - ChainedWifiParameterGroup* _currentSet; - - iotwebconf::OptionalGroupHtmlFormatProvider _optionalGroupHtmlFormatProvider; -}; - -} - -#endif \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfOptionalGroup.cpp b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfOptionalGroup.cpp deleted file mode 100644 index 9e646490690db722939a97a28c37ac257c6efb1a..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfOptionalGroup.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/** - * IotWebConfOptionalGroup.cpp -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - *s - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#include "IotWebConfOptionalGroup.h" - -namespace iotwebconf -{ - -OptionalParameterGroup::OptionalParameterGroup(const char* id, const char* label, bool defaultVisible) - : ParameterGroup(id, label) -{ - this->_defaultActive = defaultVisible; -} - - -int OptionalParameterGroup::getStorageSize() -{ - return ParameterGroup::getStorageSize() + 1; -} - -void OptionalParameterGroup::applyDefaultValue() -{ - this->_active = this->_defaultActive; - ParameterGroup::applyDefaultValue(); -} - -void OptionalParameterGroup::storeValue( - std::function doStore) -{ - // -- Store active flag. - byte data[1]; - data[0] = (byte)this->_active; - SerializationData serializationData; - serializationData.length = 1; - serializationData.data = data; - doStore(&serializationData); - - // -- Store other items. - ParameterGroup::storeValue(doStore); -} -void OptionalParameterGroup::loadValue( - std::function doLoad) -{ - // -- Load activity. - byte data[1]; - SerializationData serializationData; - serializationData.length = 1; - serializationData.data = data; - doLoad(&serializationData); - this->_active = (bool)data[0]; - - // -- Load other items. - ParameterGroup::loadValue(doLoad); -} - -void OptionalParameterGroup::renderHtml( - bool dataArrived, WebRequestWrapper* webRequestWrapper) -{ - if (this->label != nullptr) - { - String content = getStartTemplate(); - content.replace("{b}", this->label); - content.replace("{i}", this->getId()); - content.replace("{v}", this->_active ? "active" : "inactive"); - if (this->_active) - { - content.replace("{cb}", "hide"); - content.replace("{cf}", ""); - } - else - { - content.replace("{cb}", ""); - content.replace("{cf}", "hide"); - } - webRequestWrapper->sendContent(content); - } - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - if (current->visible) - { - current->renderHtml(dataArrived, webRequestWrapper); - } - current = this->getNextItemOf(current); - } - if (this->label != nullptr) - { - String content = getEndTemplate(); - content.replace("{b}", this->label); - content.replace("{i}", this->getId()); - webRequestWrapper->sendContent(content); - } -} - -void OptionalParameterGroup::update(WebRequestWrapper* webRequestWrapper) -{ - // -- Get active variable - String activeId = String(this->getId()); - activeId += 'v'; - if (webRequestWrapper->hasArg(activeId)) - { - String activeStr = webRequestWrapper->arg(activeId); - this->_active = activeStr.equals("active"); - } - - // Update other items. - ParameterGroup::update(webRequestWrapper); -} - -void OptionalParameterGroup::debugTo(Stream* out) -{ - out->print('('); - out->print(this->_active ? "active" : "inactive"); - out->print(')'); - - // Print rest. - ParameterGroup::debugTo(out); -} - -/////////////////////////////////////////////////////////////////////////////// - -String ChainedParameterGroup::getStartTemplate() -{ - String result = OptionalParameterGroup::getStartTemplate(); - - if ((this->_prevGroup != nullptr) && (!this->_prevGroup->isActive())) - { - result.replace("{cb}", "hide"); - } - return result; -}; - -String ChainedParameterGroup::getEndTemplate() -{ - String result; - if (this->_nextGroup == nullptr) - { - result = OptionalParameterGroup::getEndTemplate(); - } - else - { - result = FPSTR(IOTWEBCONF_HTML_FORM_CHAINED_GROUP_NEXTID); - result.replace("{in}", this->_nextGroup->getId()); - result += OptionalParameterGroup::getEndTemplate(); - } - return result; -}; - - -} \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfOptionalGroup.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfOptionalGroup.h deleted file mode 100644 index 035d0064fad3652242ebf804afe75993411fae47..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfOptionalGroup.h +++ /dev/null @@ -1,116 +0,0 @@ -/** - * IotWebConfOptionalGroup.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef IotWebConfOptionalGroup_h -#define IotWebConfOptionalGroup_h - -#include "IotWebConf.h" // For HtmlFormatProvider ... TODO: should be reorganized -#include "IotWebConfParameter.h" - -const char IOTWEBCONF_HTML_FORM_OPTIONAL_GROUP_JAVASCRIPT[] PROGMEM = - " function show(id) { var x=document.getElementById(id); x.classList.remove('hide'); }\n" - " function hide(id) { var x=document.getElementById(id); x.classList.add('hide'); }\n" - " function val(id) { var x=document.getElementById(id); return x.value; }\n" - " function setVal(id, val) { var x=document.getElementById(id); x.value = val; }\n" - " function showFs(id) {\n" - " show(id); hide(id + 'b'); setVal(id + 'v', 'active'); var n=document.getElementById(id + 'next');\n" - " if (n) { var nId = n.value; if (val(nId + 'v') == 'inactive') { show(nId + 'b'); }}\n" - " }\n" - " function hideFs(id) {\n" - " hide(id); show(id + 'b'); setVal(id + 'v', 'inactive'); var n=document.getElementById(id + 'next');\n" - " if (n) { var nId = n.value; if (val(nId + 'v') == 'inactive') { hide(nId + 'b'); }}\n" - " }\n"; -const char IOTWEBCONF_HTML_FORM_OPTIONAL_GROUP_CSS[] PROGMEM = - ".hide{display: none;}\n"; -const char IOTWEBCONF_HTML_FORM_OPTIONAL_GROUP_START[] PROGMEM = - "\n" - "
{b}\n" - "\n" - "\n" - "\n"; -const char IOTWEBCONF_HTML_FORM_OPTIONAL_GROUP_END[] PROGMEM = - "
\n"; -const char IOTWEBCONF_HTML_FORM_CHAINED_GROUP_NEXTID[] PROGMEM = - "\n"; - -namespace iotwebconf -{ - -class OptionalGroupHtmlFormatProvider : public HtmlFormatProvider -{ -protected: - String getScriptInner() override - { - return - HtmlFormatProvider::getScriptInner() + - String(FPSTR(IOTWEBCONF_HTML_FORM_OPTIONAL_GROUP_JAVASCRIPT)); - } - String getStyleInner() override - { - return - HtmlFormatProvider::getStyleInner() + - String(FPSTR(IOTWEBCONF_HTML_FORM_OPTIONAL_GROUP_CSS)); - } -}; - -/** - * With OptionalParameterGroup buttons will appear in the GUI, - * to show and hide this specific group of parameters. The idea - * behind this feature to add/remove optional parameter set - * in the config portal. - */ -class OptionalParameterGroup : public ParameterGroup -{ -public: - OptionalParameterGroup(const char* id, const char* label, bool defaultActive); - bool isActive() { return this->_active; } - void setActive(bool active) { this->_active = active; } - -protected: - int getStorageSize() override; - void applyDefaultValue() override; - void storeValue(std::function doStore) override; - void loadValue(std::function doLoad) override; - void renderHtml(bool dataArrived, WebRequestWrapper* webRequestWrapper) override; - virtual String getStartTemplate() { return FPSTR(IOTWEBCONF_HTML_FORM_OPTIONAL_GROUP_START); }; - virtual String getEndTemplate() { return FPSTR(IOTWEBCONF_HTML_FORM_OPTIONAL_GROUP_END); }; - void update(WebRequestWrapper* webRequestWrapper) override; - void debugTo(Stream* out) override; - -private: - bool _defaultActive; - bool _active; -}; - -class ChainedParameterGroup; - -class ChainedParameterGroup : public OptionalParameterGroup -{ -public: - ChainedParameterGroup(const char* id, const char* label, bool defaultActive = false) : - OptionalParameterGroup(id, label, defaultActive) { }; - void setNext(ChainedParameterGroup* nextGroup) { this->_nextGroup = nextGroup; nextGroup->_prevGroup = this; }; - ChainedParameterGroup* getNext() { return this->_nextGroup; }; - -protected: - virtual String getStartTemplate() override; - virtual String getEndTemplate() override; - -protected: - ChainedParameterGroup* _prevGroup = nullptr; - ChainedParameterGroup* _nextGroup = nullptr; -}; - -} - -#endif diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfParameter.cpp b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfParameter.cpp deleted file mode 100644 index 269c38e9376e2fcf628d8fe3e615bc56d6bca85d..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfParameter.cpp +++ /dev/null @@ -1,624 +0,0 @@ -/** - * IotWebConfParameter.cpp -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#include "IotWebConfParameter.h" - -namespace iotwebconf -{ - -ParameterGroup::ParameterGroup( - const char* id, const char* label) : - ConfigItem(id) -{ - this->label = label; -} - -void ParameterGroup::addItem(ConfigItem* configItem) -{ - if (configItem->_parentItem != nullptr) - { - return; // Item must not be added two times. - } - if (this->_firstItem == nullptr) - { - this->_firstItem = configItem; - return; - } - ConfigItem* current = this->_firstItem; - while (current->_nextItem != nullptr) - { - current = current->_nextItem; - } - current->_nextItem = configItem; - configItem->_parentItem = this; -} - -int ParameterGroup::getStorageSize() -{ - int size = 0; - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - size += current->getStorageSize(); - current = current->_nextItem; - } - return size; -} -void ParameterGroup::applyDefaultValue() -{ - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - current->applyDefaultValue(); - current = current->_nextItem; - } -} - -void ParameterGroup::storeValue( - std::function doStore) -{ - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - current->storeValue(doStore); - current = current->_nextItem; - } -} -void ParameterGroup::loadValue( - std::function doLoad) -{ - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - current->loadValue(doLoad); - current = current->_nextItem; - } -} - -void ParameterGroup::renderHtml( - bool dataArrived, WebRequestWrapper* webRequestWrapper) -{ - if (this->label != nullptr) - { - String content = getStartTemplate(); - content.replace("{b}", this->label); - content.replace("{i}", this->getId()); - webRequestWrapper->sendContent(content); - } - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - if (current->visible) - { - current->renderHtml(dataArrived, webRequestWrapper); - } - current = current->_nextItem; - } - if (this->label != nullptr) - { - String content = getEndTemplate(); - content.replace("{b}", this->label); - content.replace("{i}", this->getId()); - webRequestWrapper->sendContent(content); - } -} -void ParameterGroup::update(WebRequestWrapper* webRequestWrapper) -{ - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - current->update(webRequestWrapper); - current = current->_nextItem; - } -} -void ParameterGroup::clearErrorMessage() -{ - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - current->clearErrorMessage(); - current = current->_nextItem; - } -} -void ParameterGroup::debugTo(Stream* out) -{ - out->print('['); - out->print(this->getId()); - out->println(']'); - - // -- Here is some overcomplicated logic to have nice debug output. - bool ownItem = false; - bool lastItem = false; - PrefixStreamWrapper stream = - PrefixStreamWrapper( - out, - [&](Stream* out1) - { - if (ownItem) - { - ownItem = false; - return (size_t)0; - } - if (lastItem) - { - return out1->print(" "); - } - else - { - return out1->print("| "); - } - }); - - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - if (current->_nextItem == nullptr) - { - out->print("\\-- "); - } - else - { - out->print("|-- "); - } - ownItem = true; - lastItem = (current->_nextItem == nullptr); - current->debugTo(&stream); - current = current->_nextItem; - } -} - -#ifdef IOTWEBCONF_ENABLE_JSON -void ParameterGroup::loadFromJson(JsonObject jsonObject) -{ - if (jsonObject.containsKey(this->getId())) - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(F("Applying values from JSON for groupId: ")); - Serial.println(this->getId()); -#endif - JsonObject myObject = jsonObject[this->getId()]; - ConfigItem* current = this->_firstItem; - while (current != nullptr) - { - current->loadFromJson(myObject); - current = current->_nextItem; - } - } - else - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(F("Group data not found in JSON. Skipping groupId: ")); - Serial.println(this->getId()); -#endif - } -} -#endif - -/////////////////////////////////////////////////////////////////////////////// - -Parameter::Parameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* defaultValue) : - ConfigItem(id) -{ - this->label = label; - this->valueBuffer = valueBuffer; - this->_length = length; - this->defaultValue = defaultValue; - - this->errorMessage = nullptr; -} -int Parameter::getStorageSize() -{ - return this->_length; -} -void Parameter::applyDefaultValue() -{ - if (defaultValue != nullptr) - { - strncpy(this->valueBuffer, this->defaultValue, this->getLength()); - } - else - { - this->valueBuffer[0] = '\0'; - } -} -void Parameter::storeValue( - std::function doStore) -{ - SerializationData serializationData; - serializationData.length = this->_length; - serializationData.data = (byte*)this->valueBuffer; - doStore(&serializationData); -} -void Parameter::loadValue( - std::function doLoad) -{ - SerializationData serializationData; - serializationData.length = this->_length; - serializationData.data = (byte*)this->valueBuffer; - doLoad(&serializationData); -} -void Parameter::update(WebRequestWrapper* webRequestWrapper) -{ - if (webRequestWrapper->hasArg(this->getId())) - { - String newValue = webRequestWrapper->arg(this->getId()); - this->update(newValue); - } -} -void Parameter::clearErrorMessage() -{ - this->errorMessage = nullptr; -} -#ifdef IOTWEBCONF_ENABLE_JSON -void Parameter::loadFromJson(JsonObject jsonObject) -{ - if (jsonObject.containsKey(this->getId())) - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(F("Applying value from JSON for parameterId: ")); - Serial.println(this->getId()); -#endif - const char* value = jsonObject[this->getId()]; - this->update(String(value)); - } - else - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(F("No value found in JSON for parameterId: ")); - Serial.println(this->getId()); -#endif - } -} -#endif - - -/////////////////////////////////////////////////////////////////////////////// - -TextParameter::TextParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* defaultValue, - const char* placeholder, - const char* customHtml) - : Parameter(label, id, valueBuffer, length, defaultValue) -{ - this->placeholder = placeholder; - this->customHtml = customHtml; -} - -void TextParameter::renderHtml( - bool dataArrived, WebRequestWrapper* webRequestWrapper) -{ - String content = this->renderHtml( - dataArrived, - webRequestWrapper->hasArg(this->getId()), - webRequestWrapper->arg(this->getId())); - webRequestWrapper->sendContent(content); -} -String TextParameter::renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost) -{ - return this->renderHtml("text", hasValueFromPost, valueFromPost); -} -String TextParameter::renderHtml( - const char* type, bool hasValueFromPost, String valueFromPost) -{ - TextParameter* current = this; - char parLength[12]; - - String pitem = getHtmlTemplate(); - - pitem.replace("{b}", current->label); - pitem.replace("{t}", type); - pitem.replace("{i}", current->getId()); - pitem.replace("{p}", current->placeholder == nullptr ? "" : current->placeholder); - snprintf(parLength, 12, "%d", current->getLength()-1); - pitem.replace("{l}", parLength); - if (hasValueFromPost) - { - // -- Value from previous submit - pitem.replace("{v}", valueFromPost); - } - else - { - // -- Value from config - pitem.replace("{v}", current->valueBuffer); - } - pitem.replace( - "{c}", current->customHtml == nullptr ? "" : current->customHtml); - pitem.replace( - "{s}", - current->errorMessage == nullptr ? "" : "de"); // Div style class. - pitem.replace( - "{e}", - current->errorMessage == nullptr ? "" : current->errorMessage); - - return pitem; -} - -void TextParameter::update(String newValue) -{ - newValue.toCharArray(this->valueBuffer, this->getLength()); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(this->getId()); - Serial.print(": "); - Serial.println(this->valueBuffer); -#endif -} - -void TextParameter::debugTo(Stream* out) -{ - Parameter* current = this; - out->print("'"); - out->print(current->getId()); - out->print("' with value: '"); - out->print(current->valueBuffer); - out->println("'"); -} - -/////////////////////////////////////////////////////////////////////////////// - -NumberParameter::NumberParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* defaultValue, - const char* placeholder, - const char* customHtml) - : TextParameter(label, id, valueBuffer, length, defaultValue, - placeholder, customHtml) -{ -} - -String NumberParameter::renderHtml( - bool dataArrived, - bool hasValueFromPost, String valueFromPost) -{ - return TextParameter::renderHtml("number", hasValueFromPost, valueFromPost); -} - -/////////////////////////////////////////////////////////////////////////////// - -PasswordParameter::PasswordParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* defaultValue, - const char* placeholder, - const char* customHtml) - : TextParameter(label, id, valueBuffer, length, defaultValue, - placeholder, customHtml) -{ -} - -String PasswordParameter::renderHtml( - bool dataArrived, - bool hasValueFromPost, String valueFromPost) -{ - return TextParameter::renderHtml("password", true, String(this->valueBuffer)); -} - -void PasswordParameter::debugTo(Stream* out) -{ - Parameter* current = this; - out->print("'"); - out->print(current->getId()); - out->print("' with value: "); -#ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL - out->print("'"); - out->print(current->valueBuffer); - out->println("'"); -#else - out->println(F("")); -#endif -} - -void PasswordParameter::update(String newValue) -{ - Parameter* current = this; -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(this->getId()); - Serial.print(": "); -#endif - if (newValue != current->valueBuffer) - { - // -- Value was set. - newValue.toCharArray(current->valueBuffer, current->getLength()); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL -# ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL - Serial.println(current->valueBuffer); -# else - Serial.println(""); -# endif -#endif - } - else - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.println(""); -#endif - } -} - -/////////////////////////////////////////////////////////////////////////////// - -CheckboxParameter::CheckboxParameter( - const char* label, const char* id, char* valueBuffer, int length, - bool defaultValue) - : TextParameter(label, id, valueBuffer, length, defaultValue ? "selected" : nullptr, - nullptr, nullptr) -{ -} - -String CheckboxParameter::renderHtml( - bool dataArrived, - bool hasValueFromPost, String valueFromPost) -{ - bool checkSelected = false; - if (dataArrived) - { - if (hasValueFromPost && valueFromPost.equals("selected")) - { - checkSelected = true; - } - } - else - { - if (this->isChecked()) - { - checkSelected = true; - } - } - - if (checkSelected) - { - this->customHtml = CheckboxParameter::_checkedStr; - } - else - { - this->customHtml = nullptr; - } - - - return TextParameter::renderHtml("checkbox", true, "selected"); -} - -void CheckboxParameter::update(WebRequestWrapper* webRequestWrapper) -{ - if (webRequestWrapper->hasArg(this->getId())) - { - String newValue = webRequestWrapper->arg(this->getId()); - return TextParameter::update(newValue); - } - else if (this->visible) - { - // HTML will not post back unchecked checkboxes. - return TextParameter::update(""); - } -} - -/////////////////////////////////////////////////////////////////////////////// - -OptionsParameter::OptionsParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* optionValues, const char* optionNames, size_t optionCount, size_t nameLength, - const char* defaultValue) - : TextParameter(label, id, valueBuffer, length, defaultValue, - nullptr, nullptr) -{ - this->_optionValues = optionValues; - this->_optionNames = optionNames; - this->_optionCount = optionCount; - this->_nameLength = nameLength; -} - -/////////////////////////////////////////////////////////////////////////////// - -SelectParameter::SelectParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* optionValues, const char* optionNames, size_t optionCount, size_t nameLength, - const char* defaultValue) - : OptionsParameter(label, id, valueBuffer, length, optionValues, optionNames, - optionCount, nameLength, defaultValue) -{ -} - -String SelectParameter::renderHtml( - bool dataArrived, - bool hasValueFromPost, String valueFromPost) -{ - TextParameter* current = this; - - String options = ""; - - for (size_t i=0; i_optionCount; i++) - { - const char *optionValue = (this->_optionValues + (i*this->getLength()) ); - const char *optionName = (this->_optionNames + (i*this->_nameLength) ); - String oitem = FPSTR(IOTWEBCONF_HTML_FORM_OPTION); - oitem.replace("{v}", optionValue); -// if (sizeof(this->_optionNames) > i) - { - oitem.replace("{n}", optionName); - } -// else -// { -// oitem.replace("{n}", "?"); -// } - if ((hasValueFromPost && (valueFromPost == optionValue)) || - (strncmp(current->valueBuffer, optionValue, this->getLength()) == 0)) - { - // -- Value from previous submit - oitem.replace("{s}", " selected"); - } - else - { - // -- Value from config - oitem.replace("{s}", ""); - } - - options += oitem; - } - - String pitem = FPSTR(IOTWEBCONF_HTML_FORM_SELECT_PARAM); - - pitem.replace("{b}", current->label); - pitem.replace("{i}", current->getId()); - pitem.replace( - "{c}", current->customHtml == nullptr ? "" : current->customHtml); - pitem.replace( - "{s}", - current->errorMessage == nullptr ? "" : "de"); // Div style class. - pitem.replace( - "{e}", - current->errorMessage == nullptr ? "" : current->errorMessage); - pitem.replace("{o}", options); - - return pitem; -} - -/////////////////////////////////////////////////////////////////////////////// - -PrefixStreamWrapper::PrefixStreamWrapper( - Stream* originalStream, - std::function prefixWriter) -{ - this->_originalStream = originalStream; - this->_prefixWriter = prefixWriter; -} -size_t PrefixStreamWrapper::write(uint8_t data) -{ - size_t sizeOut = checkNewLine(); - sizeOut += this->_originalStream->write(data); - if (data == 10) // NewLine - { - this->_newLine = true; - } - return sizeOut; -} -size_t PrefixStreamWrapper::write(const uint8_t *buffer, size_t size) -{ - size_t sizeOut = checkNewLine(); - sizeOut += this->_originalStream->write(buffer, size); - if (*(buffer + size-1) == 10) // Ends with new line - { - this->_newLine = true; - } - return sizeOut; -} -size_t PrefixStreamWrapper::checkNewLine() -{ - if (this->_newLine) - { - this->_newLine = false; - return this->_prefixWriter(this->_originalStream); - } - return 0; -} - -} // end namespace \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfParameter.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfParameter.h deleted file mode 100644 index 4ad7b9516dbe4ea37c4a4dec8cf35b3e47f989f7..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfParameter.h +++ /dev/null @@ -1,462 +0,0 @@ -/** - * IotWebConfParameter.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef IotWebConfParameter_h -#define IotWebConfParameter_h - -#include -#include -#include "IotWebConfSettings.h" -#include "IotWebConfWebServerWrapper.h" - -#ifdef IOTWEBCONF_ENABLE_JSON -# include -#endif - -const char IOTWEBCONF_HTML_FORM_GROUP_START[] PROGMEM = - "
{b}\n"; -const char IOTWEBCONF_HTML_FORM_GROUP_END[] PROGMEM = - "
\n"; - -const char IOTWEBCONF_HTML_FORM_PARAM[] PROGMEM = - "
" - "
{e}
\n"; - -const char IOTWEBCONF_HTML_FORM_SELECT_PARAM[] PROGMEM = - "
{e}
\n"; -const char IOTWEBCONF_HTML_FORM_OPTION[] PROGMEM = - "\n"; - -namespace iotwebconf -{ - -typedef struct SerializationData -{ - byte* data; - int length; -} SerializationData; - -class ConfigItem -{ -public: - bool visible = true; - const char* getId() { return this->_id; } - - /** - * Calculate the size of bytes should be stored in the EEPROM. - */ - virtual int getStorageSize() = 0; - - /** - * On initial startup (when no data was saved), it may be required to apply a default value - * to the parameter. - */ - virtual void applyDefaultValue() = 0; - - /** - * Save data. - * @doStore - A method is passed as a parameter, that will performs the actual EEPROM access. - * The argument 'serializationData' of this referenced method should be pre-filled with - * the size and the serialized data before calling the method. - */ - virtual void storeValue(std::function doStore) = 0; - - /** - * Load data. - * @doLoad - A method is passed as a parameter, that will performs the actual EEPROM access. - * The argument 'serializationData' of this referenced method should be pre-filled with - * the size of the expected data, and the data buffer should be allocated with this size. - * The doLoad will fill the data from the EEPROM. - */ - virtual void loadValue(std::function doLoad) = 0; - - /** - * This method will create the HTML form item for the config portal. - * - * @dataArrived - True if there was a form post, where (some) form - * data arrived from the client. - * @webRequestWrapper - The webRequestWrapper, that will send the rendered content to the client. - * The webRequestWrapper->sendContent() method should be used in the implementations. - */ - virtual void renderHtml(bool dataArrived, WebRequestWrapper* webRequestWrapper) = 0; - - /** - * New value arrived from the form post. The value should be stored in the - * in this config item. - * - * @webRequestWrapper - The webRequestWrapper, that will send the rendered content to the client. - * The webRequestWrapper->hasArg() and webRequestWrapper->arg() methods should be used in the - * implementations. - */ - virtual void update(WebRequestWrapper* webRequestWrapper) = 0; - - /** - * Before validating the form post, it is required to clear previous error messages. - */ - virtual void clearErrorMessage() = 0; - - /** - * This method should display information to Serial containing the parameter - * ID and the current value of the parameter (if it is confidential). - * Will only be called if debug is enabled. - */ - virtual void debugTo(Stream* out) = 0; - -#ifdef IOTWEBCONF_ENABLE_JSON - /** - * - */ - virtual void loadFromJson(JsonObject jsonObject) = 0; -#endif - -protected: - ConfigItem(const char* id) { this->_id = id; }; - -private: - const char* _id = 0; - ConfigItem* _parentItem = nullptr; - ConfigItem* _nextItem = nullptr; - friend class ParameterGroup; // Allow ParameterGroup to access _nextItem. -}; - -class ParameterGroup : public ConfigItem -{ -public: - ParameterGroup(const char* id, const char* label = nullptr); - void addItem(ConfigItem* configItem); - const char *label; - void applyDefaultValue() override; -#ifdef IOTWEBCONF_ENABLE_JSON - virtual void loadFromJson(JsonObject jsonObject) override; -#endif - -protected: - int getStorageSize() override; - void storeValue(std::function doStore) override; - void loadValue(std::function doLoad) override; - void renderHtml(bool dataArrived, WebRequestWrapper* webRequestWrapper) override; - void update(WebRequestWrapper* webRequestWrapper) override; - void clearErrorMessage() override; - void debugTo(Stream* out) override; - /** - * One can override this method in case a specific HTML template is required - * for a group. - */ - virtual String getStartTemplate() { return FPSTR(IOTWEBCONF_HTML_FORM_GROUP_START); }; - /** - * One can override this method in case a specific HTML template is required - * for a group. - */ - virtual String getEndTemplate() { return FPSTR(IOTWEBCONF_HTML_FORM_GROUP_END); }; - - ConfigItem* _firstItem = nullptr; - ConfigItem* getNextItemOf(ConfigItem* parent) { return parent->_nextItem; }; - - friend class IotWebConf; // Allow IotWebConf to access protected members. - -private: -}; - -/** - * Parameters is a configuration item of the config portal. - * The parameter will have its input field on the configuration page, - * and the provided value will be saved to the EEPROM. - */ -class Parameter : public ConfigItem -{ -public: - /** - * Create a parameter for the config portal. - * - * @label - Displayable label at the config portal. - * @id - Identifier used for HTTP queries and as configuration key. Must not - * contain spaces nor other special characters. - * @valueBuffer - Configuration value will be loaded to this buffer from the - * EEPROM. - * @length - The buffer should have a length provided here. - * @defaultValue - Defalt value set on startup, when no configuration ever saved - * with the current config-version. - */ - Parameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* defaultValue = nullptr); - - const char* label; - char* valueBuffer; - const char* defaultValue; - const char* errorMessage; - - int getLength() { return this->_length; } - void applyDefaultValue() override; -#ifdef IOTWEBCONF_ENABLE_JSON - virtual void loadFromJson(JsonObject jsonObject) override; -#endif - -protected: - // Overrides - int getStorageSize() override; - void storeValue(std::function doStore) override; - void loadValue(std::function doLoad) override; - virtual void update(WebRequestWrapper* webRequestWrapper) override; - virtual void update(String newValue) = 0; - void clearErrorMessage() override; - -private: - int _length; -}; - -/////////////////////////////////////////////////////////////////////////////// - -/** - * TexParameters is to store text based parameters. - */ -class TextParameter : public Parameter -{ -public: - /** - * Create a text parameter for the config portal. - * - * @placeholder (optional) - Text appear in an empty input box. - * @customHtml (optional) - The text of this parameter will be added into - * the HTML INPUT field. - * (See Parameter for arguments!) - */ - TextParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* defaultValue = nullptr, - const char* placeholder = nullptr, - const char* customHtml = nullptr); - - /** - * This variable is meant to store a value that is displayed in an empty - * (not filled) field. - */ - const char* placeholder; - - /** - * Usually this variable is used when rendering the form input field - * so one can customize the rendered outcome of this particular item. - */ - const char* customHtml; - -protected: - virtual String renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost); - // Overrides - virtual void renderHtml(bool dataArrived, WebRequestWrapper* webRequestWrapper) override; - virtual void update(String newValue) override; - virtual void debugTo(Stream* out) override; - /** - * One can override this method in case a specific HTML template is required - * for a parameter. - */ - virtual String getHtmlTemplate() { return FPSTR(IOTWEBCONF_HTML_FORM_PARAM); }; - - /** - * Renders a standard HTML form INPUT. - * @type - The type attribute of the html input field. - */ - virtual String renderHtml(const char* type, bool hasValueFromPost, String valueFromPost); - -private: - friend class IotWebConf; - friend class WifiParameterGroup; -}; - -/////////////////////////////////////////////////////////////////////////////// - -/** - * The Password parameter has a special handling, as the value will be - * overwritten in the EEPROM only if value was provided on the config portal. - * Because of this logic, "password" type field with length more then - * IOTWEBCONF_PASSWORD_LEN characters are not supported. - */ -class PasswordParameter : public TextParameter -{ -public: - /** - * Create a password parameter for the config portal. - * - * (See TextParameter for arguments!) - */ - PasswordParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* defaultValue = nullptr, - const char* placeholder = nullptr, - const char* customHtml = "ondblclick=\"pw(this.id)\""); - -protected: - // Overrides - virtual String renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost) override; - virtual void update(String newValue) override; - virtual void debugTo(Stream* out) override; - -private: - friend class IotWebConf; - friend class WifiParameterGroup; -}; - -/////////////////////////////////////////////////////////////////////////////// - -/** - * This is just a text parameter, that is rendered with type 'number'. - */ -class NumberParameter : public TextParameter -{ -public: - /** - * Create a numeric parameter for the config portal. - * - * (See TextParameter for arguments!) - */ - NumberParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* defaultValue = nullptr, - const char* placeholder = nullptr, - const char* customHtml = nullptr); - -protected: - // Overrides - virtual String renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost) override; - -private: - friend class IotWebConf; -}; - -/////////////////////////////////////////////////////////////////////////////// - -/** - * Checkbox parameter is represended as a text parameter but has a special - * handling. As the value is either empty or has the word "selected". - * Note, that form post will not send value if checkbox was not selected. - */ -class CheckboxParameter : public TextParameter -{ -public: - /** - * Create a checkbox parameter for the config portal. - * - * (See TextParameter for arguments!) - */ - CheckboxParameter( - const char* label, const char* id, char* valueBuffer, int length, - bool defaultValue = false); - bool isChecked() { return strncmp(this->valueBuffer, "selected", this->getLength()) == 0; } - -protected: - // Overrides - virtual String renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost) override; - virtual void update(WebRequestWrapper* webRequestWrapper) override; - -private: - friend class IotWebConf; - bool _checked; - const char* _checkedStr = "checked='checked'"; -}; - -/////////////////////////////////////////////////////////////////////////////// - -/** - * Options parameter is a structure, that handles multiple values when redering - * the HTML representation. - */ -class OptionsParameter : public TextParameter -{ -public: - /** - * @optionValues - List of values to choose from with, where each value - * can have a maximal size of 'length'. Contains 'optionCount' items. - * @optionNames - List of names to render for the values, where each - * name can have a maximal size of 'nameLength'. Contains 'optionCount' - * items. - * @optionCount - Size of both 'optionValues' and 'optionNames' lists. - * @nameLength - Size of any item in optionNames list. - * (See TextParameter for arguments!) - */ - OptionsParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* optionValues, const char* optionNames, size_t optionCount, size_t nameLength, - const char* defaultValue = nullptr); - -protected: - const char* _optionValues; - const char* _optionNames; - size_t _optionCount; - size_t _nameLength; - -private: - friend class IotWebConf; -}; - -/////////////////////////////////////////////////////////////////////////////// - -/** - * Select parameter is an option parameter, that rendered as HTML SELECT. - * Basically it is a dropdown combobox. - */ -class SelectParameter : public OptionsParameter -{ -public: - /** - * Create a select parameter for the config portal. - * - * (See OptionsParameter for arguments!) - */ - SelectParameter( - const char* label, const char* id, char* valueBuffer, int length, - const char* optionValues, const char* optionNames, size_t optionCount, size_t namesLenth, - const char* defaultValue = nullptr); - -protected: - // Overrides - virtual String renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost) override; - -private: - friend class IotWebConf; -}; - -/** - * This class is here just to make some nice indents on debug output - * for group tree. - */ -class PrefixStreamWrapper : public Stream -{ -public: - PrefixStreamWrapper( - Stream* originalStream, - std::function prefixWriter); - size_t write(uint8_t) override; - size_t write(const uint8_t *buffer, size_t size) override; - int available() override { return _originalStream->available(); }; - int read() override { return _originalStream->read(); }; - int peek() override { return _originalStream->peek(); }; - void flush() override { return _originalStream->flush(); }; - -private: - Stream* _originalStream; - std::function _prefixWriter; - bool _newLine = true; - - size_t checkNewLine(); -}; - -} // end namespace - -#endif diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfSettings.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfSettings.h deleted file mode 100644 index f4850bf9596a2e1ccafa81cef559f4ab83a466e5..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfSettings.h +++ /dev/null @@ -1,77 +0,0 @@ -/** - * IotWebConfSettings.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef IotWebConfSettings_h -#define IotWebConfSettings_h - -#if __has_include("custom_ampel_iotwebconf.h") - #include "custom_ampel_iotwebconf.h" -#endif - -// -- We might want to place the config in the EEPROM in an offset. -#ifndef IOTWEBCONF_CONFIG_START -# define IOTWEBCONF_CONFIG_START 0 -#endif - -// -- Maximal length of any string used in IotWebConfig configuration (e.g. -// ssid). -#ifndef IOTWEBCONF_WORD_LEN -# define IOTWEBCONF_WORD_LEN 33 -#endif -// -- Maximal length of password used in IotWebConfig configuration. -#ifndef IOTWEBCONF_PASSWORD_LEN -# define IOTWEBCONF_PASSWORD_LEN 33 -#endif - -// -- IotWebConf tries to connect to the local network for an amount of time -// before falling back to AP mode. -#ifndef IOTWEBCONF_DEFAULT_WIFI_CONNECTION_TIMEOUT_MS -# define IOTWEBCONF_DEFAULT_WIFI_CONNECTION_TIMEOUT_MS 30000 -#endif - -// -- Thing will stay in AP mode for an amount of time on boot, before retrying -// to connect to a WiFi network. -#ifndef IOTWEBCONF_DEFAULT_AP_MODE_TIMEOUT_SECS -# define IOTWEBCONF_DEFAULT_AP_MODE_TIMEOUT_SECS "30" -#endif - -// -- mDNS should allow you to connect to this device with a hostname provided -// by the device. E.g. mything.local -// (This is not very likely to work, and MDNS is not very well documented.) -#ifndef IOTWEBCONF_CONFIG_DONT_USE_MDNS -# define IOTWEBCONF_CONFIG_USE_MDNS 80 -#endif - -// -- Logs progress information to Serial if enabled. -#ifndef IOTWEBCONF_DEBUG_DISABLED -# define IOTWEBCONF_DEBUG_TO_SERIAL -#endif - -// -- Logs passwords to Serial if enabled. -//#define IOTWEBCONF_DEBUG_PWD_TO_SERIAL - -// -- Helper define for serial debug -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL -# define IOTWEBCONF_DEBUG_LINE(MSG) Serial.println(MSG) -#else -# define IOTWEBCONF_DEBUG_LINE(MSG) -#endif - -// -- EEPROM config starts with a special prefix of length defined here. -#ifndef IOTWEBCONF_CONFIG_VERSION_LENGTH -# define IOTWEBCONF_CONFIG_VERSION_LENGTH 4 -#endif - -#ifndef IOTWEBCONF_DNS_PORT -# define IOTWEBCONF_DNS_PORT 53 -#endif - -#endif \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfTParameter.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfTParameter.h deleted file mode 100644 index 63934115b4ebe5c5ddbe3230039c40598877c139..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfTParameter.h +++ /dev/null @@ -1,951 +0,0 @@ -/** - * IotWebConfTParameter.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2021 Balazs Kelemen - * rovo89 - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef IotWebConfTParameter_h -#define IotWebConfTParameter_h - -// TODO: This file is a mess. Help wanted to organize thing! - -#include "IotWebConfParameter.h" -#include -#include -#include - -// At least in PlatformIO, strtoimax/strtoumax are defined, but not implemented. -#if 1 -#define strtoimax strtoll -#define strtoumax strtoull -#endif - -namespace iotwebconf -{ - -/** - * This class is to hide web related properties from the - * data manipulation. - */ -class ConfigItemBridge : public ConfigItem -{ -public: - virtual void update(WebRequestWrapper* webRequestWrapper) override - { - if (webRequestWrapper->hasArg(this->getId())) - { - String newValue = webRequestWrapper->arg(this->getId()); - this->update(newValue); - } - } - void debugTo(Stream* out) override - { - out->print("'"); - out->print(this->getId()); - out->print("' with value: '"); - out->print(this->toString()); - out->println("'"); - } - -protected: - ConfigItemBridge(const char* id) : ConfigItem(id) { } - virtual int getInputLength() { return 0; }; - virtual bool update(String newValue, bool validateOnly = false) = 0; - virtual String toString() = 0; -}; - -/////////////////////////////////////////////////////////////////////////// - -/** - * DataType is the data related part of the parameter. - * It does not care about web and visualization, but takes care of the - * data validation and storing. - */ -template -class DataType : virtual public ConfigItemBridge -{ -public: - using DefaultValueType = _DefaultValueType; - - DataType(const char* id, DefaultValueType defaultValue) : - ConfigItemBridge(id), - _defaultValue(defaultValue) - { - } - - /** - * value() can be used to get the value, but it can also - * be used set it like this: p.value() = newValue - */ - ValueType& value() { return this->_value; } - ValueType& operator*() { return this->_value; } - -protected: - int getStorageSize() override - { - return sizeof(ValueType); - } - - virtual bool update(String newValue, bool validateOnly = false) = 0; - bool validate(String newValue) { return update(newValue, true); } - virtual String toString() override { return String(this->_value); } - - ValueType _value; - const DefaultValueType _defaultValue; -}; - -/////////////////////////////////////////////////////////////////////////// - -class StringDataType : public DataType -{ -public: - using DataType::DataType; - -protected: - virtual bool update(String newValue, bool validateOnly) override { - if (!validateOnly) - { - this->_value = newValue; - } - return true; - } - virtual String toString() override { return this->_value; } -}; - -/////////////////////////////////////////////////////////////////////////// - -template -class CharArrayDataType : public DataType -{ -public: -using DataType::DataType; - CharArrayDataType(const char* id, const char* defaultValue) : - ConfigItemBridge::ConfigItemBridge(id), - DataType::DataType(id, defaultValue) { }; - virtual void applyDefaultValue() override - { - strncpy(this->_value, this->_defaultValue, len); - } - -protected: - virtual bool update(String newValue, bool validateOnly) override - { - if (newValue.length() + 1 > len) - { - return false; - } - if (!validateOnly) - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(this->getId()); - Serial.print(": "); - Serial.println(newValue); -#endif - strncpy(this->_value, newValue.c_str(), len); - } - return true; - } - void storeValue(std::function doStore) override - { - SerializationData serializationData; - serializationData.length = len; - serializationData.data = (byte*)this->_value; - doStore(&serializationData); - } - void loadValue(std::function doLoad) override - { - SerializationData serializationData; - serializationData.length = len; - serializationData.data = (byte*)this->_value; - doLoad(&serializationData); - } - virtual int getInputLength() override { return len; }; -}; - -/////////////////////////////////////////////////////////////////////////// - -/** - * All non-complex types should be inherited from this base class. - */ -template -class PrimitiveDataType : public DataType -{ -public: -using DataType::DataType; - PrimitiveDataType(const char* id, ValueType defaultValue) : - ConfigItemBridge::ConfigItemBridge(id), - DataType::DataType(id, defaultValue) { }; - - void setMax(ValueType val) { this->_max = val; this->_maxDefined = true; } - void setMin(ValueType val) { this->_min = val; this->_minDefined = true; } - - virtual void applyDefaultValue() override - { - this->_value = this->_defaultValue; - } - -protected: - virtual bool update(String newValue, bool validateOnly) override - { - errno = 0; - ValueType val = fromString(newValue); - if ((errno == ERANGE) - || (this->_minDefined && (val < this->_min)) - || (this->_maxDefined && (val > this->_max))) - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(this->getId()); - Serial.print(" value not accepted: "); - Serial.println(val); -#endif - return false; - } - if (!validateOnly) - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(this->getId()); - Serial.print(": "); - Serial.println((ValueType)val); -#endif - this->_value = (ValueType) val; - } - return true; - } - void storeValue(std::function doStore) override - { - SerializationData serializationData; - serializationData.length = this->getStorageSize(); - serializationData.data = - reinterpret_cast(&this->_value); - doStore(&serializationData); - } - void loadValue(std::function doLoad) override - { - byte buf[this->getStorageSize()]; - SerializationData serializationData; - serializationData.length = this->getStorageSize(); - serializationData.data = buf; - doLoad(&serializationData); - ValueType* valuePointer = reinterpret_cast(buf); - this->_value = *valuePointer; - } - virtual ValueType fromString(String stringValue) = 0; - - ValueType getMax() { return this->_max; } - ValueType getMin() { return this->_min; } - ValueType isMaxDefined() { return this->_maxDefined; } - ValueType isMinDefined() { return this->_minDefined; } - -private: - ValueType _min; - ValueType _max; - bool _minDefined = false; - bool _maxDefined = false; -}; - -/////////////////////////////////////////////////////////////////////////// - -template -class SignedIntDataType : public PrimitiveDataType -{ -public: - SignedIntDataType(const char* id, ValueType defaultValue) : - ConfigItemBridge::ConfigItemBridge(id), - PrimitiveDataType::PrimitiveDataType(id, defaultValue) { }; - -protected: - virtual ValueType fromString(String stringValue) - { - return (ValueType)strtoimax(stringValue.c_str(), nullptr, base); - } -}; - -template -class UnsignedIntDataType : public PrimitiveDataType -{ -public: - UnsignedIntDataType(const char* id, ValueType defaultValue) : - ConfigItemBridge::ConfigItemBridge(id), - PrimitiveDataType::PrimitiveDataType(id, defaultValue) { }; - -protected: - virtual ValueType fromString(String stringValue) - { - return (ValueType)strtoumax(stringValue.c_str(), nullptr, base); - } -}; - -class BoolDataType : public PrimitiveDataType -{ -public: - BoolDataType(const char* id, bool defaultValue) : - ConfigItemBridge::ConfigItemBridge(id), - PrimitiveDataType::PrimitiveDataType(id, defaultValue) { }; - -protected: - virtual bool fromString(String stringValue) - { - return stringValue.c_str()[0] == 1; - } -}; - -class FloatDataType : public PrimitiveDataType -{ -public: - FloatDataType(const char* id, float defaultValue) : - ConfigItemBridge::ConfigItemBridge(id), - PrimitiveDataType::PrimitiveDataType(id, defaultValue) { }; - -protected: - virtual float fromString(String stringValue) - { - return atof(stringValue.c_str()); - } -}; - -class DoubleDataType : public PrimitiveDataType -{ -public: - DoubleDataType(const char* id, double defaultValue) : - ConfigItemBridge::ConfigItemBridge(id), - PrimitiveDataType::PrimitiveDataType(id, defaultValue) { }; - -protected: - virtual double fromString(String stringValue) - { - return strtod(stringValue.c_str(), nullptr); - } -}; - -///////////////////////////////////////////////////////////////////////// - -class IpDataType : public DataType -{ -using DataType::DataType; - -protected: - virtual bool update(String newValue, bool validateOnly) override - { - if (validateOnly) - { - IPAddress ip; - return ip.fromString(newValue); - } - else - { - return this->_value.fromString(newValue); - } - } - - virtual String toString() override { return this->_value.toString(); } -}; - -/////////////////////////////////////////////////////////////////////////// - -/** - * Input parameter is the part of the parameter that is responsible - * for the appearance of the parameter in HTML. - */ -class InputParameter : virtual public ConfigItemBridge -{ -public: - InputParameter(const char* id, const char* label) : - ConfigItemBridge::ConfigItemBridge(id), - label(label) { } - - virtual void renderHtml( - bool dataArrived, WebRequestWrapper* webRequestWrapper) override - { - String content = this->renderHtml( - dataArrived, - webRequestWrapper->hasArg(this->getId()), - webRequestWrapper->arg(this->getId())); - webRequestWrapper->sendContent(content); - } - - const char* label; - - /** - * This variable is meant to store a value that is displayed in an empty - * (not filled) field. - */ - const char* placeholder = nullptr; - virtual void setPlaceholder(const char* placeholder) { this->placeholder = placeholder; } - - /** - * Usually this variable is used when rendering the form input field - * so one can customize the rendered outcome of this particular item. - */ - const char* customHtml = nullptr; - - /** - * Used when rendering the input field. Is is overridden by different - * implementations. - */ - virtual String getCustomHtml() - { - return String(customHtml == nullptr ? "" : customHtml); - } - - const char* errorMessage = nullptr; - -protected: - void clearErrorMessage() override - { - this->errorMessage = nullptr; - } - - virtual String renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost) - { - String pitem = String(this->getHtmlTemplate()); - - pitem.replace("{b}", this->label); - pitem.replace("{t}", this->getInputType()); - pitem.replace("{i}", this->getId()); - pitem.replace( - "{p}", this->placeholder == nullptr ? "" : this->placeholder); - int length = this->getInputLength(); - if (length > 0) - { - char parLength[11]; - snprintf(parLength, 11, "%d", length - 1); // To allow "\0" at the end of the string. - String maxLength = String("maxlength=") + parLength; - pitem.replace("{l}", maxLength); - } - else - { - pitem.replace("{l}", ""); - } - if (hasValueFromPost) - { - // -- Value from previous submit - pitem.replace("{v}", valueFromPost); - } - else - { - // -- Value from config - pitem.replace("{v}", this->toString()); - } - pitem.replace("{c}", this->getCustomHtml()); - pitem.replace( - "{s}", - this->errorMessage == nullptr ? "" : "de"); // Div style class. - pitem.replace( - "{e}", - this->errorMessage == nullptr ? "" : this->errorMessage); - - return pitem; - } - - /** - * One can override this method in case a specific HTML template is required - * for a parameter. - */ - virtual String getHtmlTemplate() { return FPSTR(IOTWEBCONF_HTML_FORM_PARAM); }; - virtual const char* getInputType() = 0; -}; - -template -class TextTParameter : public CharArrayDataType, public InputParameter -{ -public: -using CharArrayDataType::CharArrayDataType; - TextTParameter(const char* id, const char* label, const char* defaultValue) : - ConfigItemBridge(id), - CharArrayDataType::CharArrayDataType(id, defaultValue), - InputParameter::InputParameter(id, label) { } - -protected: - virtual const char* getInputType() override { return "text"; } -}; - -class CheckboxTParameter : public BoolDataType, public InputParameter -{ -public: - CheckboxTParameter(const char* id, const char* label, const bool defaultValue) : - ConfigItemBridge(id), - BoolDataType::BoolDataType(id, defaultValue), - InputParameter::InputParameter(id, label) { } - bool isChecked() { return this->value(); } - -protected: - virtual const char* getInputType() override { return "checkbox"; } - - virtual void update(WebRequestWrapper* webRequestWrapper) override - { - bool selected = false; - if (webRequestWrapper->hasArg(this->getId())) - { - String valueFromPost = webRequestWrapper->arg(this->getId()); - selected = valueFromPost.equals("selected"); - } -// this->update(String(selected ? "1" : "0")); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(this->getId()); - Serial.print(": "); - Serial.println(selected ? "selected" : "not selected"); -#endif - this->_value = selected; - } - - virtual String renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost) override - { - bool checkSelected = false; - if (dataArrived) - { - if (hasValueFromPost && valueFromPost.equals("selected")) - { - checkSelected = true; - } - } - else - { - if (this->isChecked()) - { - checkSelected = true; - } - } - - if (checkSelected) - { - this->customHtml = CheckboxTParameter::_checkedStr; - } - else - { - this->customHtml = nullptr; - } - - return InputParameter::renderHtml(dataArrived, true, String("selected")); - } -private: - const char* _checkedStr = "checked='checked'"; -}; - -template -class PasswordTParameter : public CharArrayDataType, public InputParameter -{ -public: -using CharArrayDataType::CharArrayDataType; - PasswordTParameter(const char* id, const char* label, const char* defaultValue) : - ConfigItemBridge(id), - CharArrayDataType::CharArrayDataType(id, defaultValue), - InputParameter::InputParameter(id, label) - { - this->customHtml = _customHtmlPwd; - } - - void debugTo(Stream* out) - { - out->print("'"); - out->print(this->getId()); - out->print("' with value: "); -#ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL - out->print("'"); - out->print(this->_value); - out->println("'"); -#else - out->println(F("")); -#endif - } - - virtual bool update(String newValue, bool validateOnly) override - { - if (newValue.length() + 1 > len) - { - return false; - } - if (validateOnly) - { - return true; - } - -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.print(this->getId()); - Serial.print(": "); -#endif - if (newValue != this->_value) - { - // -- Value was set. - strncpy(this->_value, newValue.c_str(), len); -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL -# ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL - Serial.println(this->_value); -# else - Serial.println(""); -# endif -#endif - } - else - { -#ifdef IOTWEBCONF_DEBUG_TO_SERIAL - Serial.println(""); -#endif - } - return true; - } - -protected: - virtual const char* getInputType() override { return "password"; } - virtual String renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost) override - { - return InputParameter::renderHtml(dataArrived, true, String(this->_value)); - } -private: - const char* _customHtmlPwd = "ondblclick=\"pw(this.id)\""; -}; - -/** - * All non-complex type input parameters should be inherited from this - * base class. - */ -template -class PrimitiveInputParameter : - public InputParameter -{ -public: - PrimitiveInputParameter(const char* id, const char* label) : - ConfigItemBridge::ConfigItemBridge(id), - InputParameter::InputParameter(id, label) { } - - virtual String getCustomHtml() override - { - String modifiers = String(this->customHtml); - - if (this->isMinDefined()) - { - modifiers += " min='" ; - modifiers += this->getMin(); - modifiers += "'"; - } - if (this->isMaxDefined()) - { - modifiers += " max='"; - modifiers += this->getMax(); - modifiers += "'"; - } - if (this->step != 0) - { - modifiers += " step='"; - modifiers += this->step; - modifiers += "'"; - } - - return modifiers; - } - - ValueType step = 0; - void setStep(ValueType step) { this->step = step; } - virtual ValueType getMin() = 0; - virtual ValueType getMax() = 0; - virtual bool isMinDefined() = 0; - virtual bool isMaxDefined() = 0; -}; - -template -class IntTParameter : - public virtual SignedIntDataType, - public PrimitiveInputParameter -{ -public: - IntTParameter(const char* id, const char* label, ValueType defaultValue) : - ConfigItemBridge(id), - SignedIntDataType::SignedIntDataType(id, defaultValue), - PrimitiveInputParameter::PrimitiveInputParameter(id, label) { } - - // TODO: somehow organize these methods into common parent. - virtual ValueType getMin() override - { - return PrimitiveDataType::getMin(); - } - virtual ValueType getMax() override - { - return PrimitiveDataType::getMax(); - } - - virtual bool isMinDefined() override - { - return PrimitiveDataType::isMinDefined(); - } - virtual bool isMaxDefined() override - { - return PrimitiveDataType::isMaxDefined(); - } - -protected: - virtual const char* getInputType() override { return "number"; } -}; - -template -class UIntTParameter : - public virtual UnsignedIntDataType, - public PrimitiveInputParameter -{ -public: - UIntTParameter(const char* id, const char* label, ValueType defaultValue) : - ConfigItemBridge(id), - UnsignedIntDataType::UnsignedIntDataType(id, defaultValue), - PrimitiveInputParameter::PrimitiveInputParameter(id, label) { } - - // TODO: somehow organize these methods into common parent. - virtual ValueType getMin() override - { - return PrimitiveDataType::getMin(); - } - virtual ValueType getMax() override - { - return PrimitiveDataType::getMax(); - } - - virtual bool isMinDefined() override - { - return PrimitiveDataType::isMinDefined(); - } - virtual bool isMaxDefined() override - { - return PrimitiveDataType::isMaxDefined(); - } - -protected: - virtual const char* getInputType() override { return "number"; } -}; - -class FloatTParameter : - public FloatDataType, - public PrimitiveInputParameter -{ -public: - FloatTParameter(const char* id, const char* label, float defaultValue) : - ConfigItemBridge(id), - FloatDataType::FloatDataType(id, defaultValue), - PrimitiveInputParameter::PrimitiveInputParameter(id, label) { } - - virtual float getMin() override - { - return PrimitiveDataType::getMin(); - } - virtual float getMax() override - { - return PrimitiveDataType::getMax(); - } - - virtual bool isMinDefined() override - { - return PrimitiveDataType::isMinDefined(); - } - virtual bool isMaxDefined() override - { - return PrimitiveDataType::isMaxDefined(); - } - -protected: - virtual const char* getInputType() override { return "number"; } -}; - -/** - * Options parameter is a structure, that handles multiple values when redering - * the HTML representation. - */ -template -class OptionsTParameter : public TextTParameter -{ -public: - /** - * @optionValues - List of values to choose from with, where each value - * can have a maximal size of 'length'. Contains 'optionCount' items. - * @optionNames - List of names to render for the values, where each - * name can have a maximal size of 'nameLength'. Contains 'optionCount' - * items. - * @optionCount - Size of both 'optionValues' and 'optionNames' lists. - * @nameLength - Size of any item in optionNames list. - * (See TextParameter for arguments!) - */ - OptionsTParameter( - const char* id, const char* label, const char* defaultValue, - const char* optionValues, const char* optionNames, - size_t optionCount, size_t nameLength) : - ConfigItemBridge(id), - TextTParameter(id, label, defaultValue) - { - this->_optionValues = optionValues; - this->_optionNames = optionNames; - this->_optionCount = optionCount; - this->_nameLength = nameLength; - } - - // TODO: make these protected - void setOptionValues(const char* optionValues) { this->_optionValues = optionValues; } - void setOptionNames(const char* optionNames) { this->_optionNames = optionNames; } - void setOptionCount(size_t optionCount) { this->_optionCount = optionCount; } - void setNameLength(size_t nameLength) { this->_nameLength = nameLength; } -protected: - OptionsTParameter( - const char* id, const char* label, const char* defaultValue) : - ConfigItemBridge(id), - TextTParameter(id, label, defaultValue) - { - } - - const char* _optionValues; - const char* _optionNames; - size_t _optionCount; - size_t _nameLength; -}; - -/////////////////////////////////////////////////////////////////////////////// - -/** - * Select parameter is an option parameter, that rendered as HTML SELECT. - * Basically it is a dropdown combobox. - */ -template -class SelectTParameter : public OptionsTParameter -{ -public: - /** - * Create a select parameter for the config portal. - * - * (See OptionsParameter for arguments!) - */ - SelectTParameter( - const char* id, const char* label, const char* defaultValue, - const char* optionValues, const char* optionNames, - size_t optionCount, size_t nameLength) : - ConfigItemBridge(id), - OptionsTParameter( - id, label, defaultValue, optionValues, optionNames, optionCount, nameLength) - { } - // TODO: make this protected - SelectTParameter( - const char* id, const char* label, const char* defaultValue) : - ConfigItemBridge(id), - OptionsTParameter(id, label, defaultValue) { } - -protected: - // Overrides - virtual String renderHtml( - bool dataArrived, bool hasValueFromPost, String valueFromPost) override - { - String options = ""; - - for (size_t i=0; i_optionCount; i++) - { - const char *optionValue = (this->_optionValues + (i*len) ); - const char *optionName = (this->_optionNames + (i*this->_nameLength) ); - String oitem = FPSTR(IOTWEBCONF_HTML_FORM_OPTION); - oitem.replace("{v}", optionValue); -// if (sizeof(this->_optionNames) > i) - { - oitem.replace("{n}", optionName); - } -// else -// { -// oitem.replace("{n}", "?"); -// } - if ((hasValueFromPost && (valueFromPost == optionValue)) || - (strncmp(this->value(), optionValue, len) == 0)) - { - // -- Value from previous submit - oitem.replace("{s}", " selected"); - } - else - { - // -- Value from config - oitem.replace("{s}", ""); - } - - options += oitem; - } - - String pitem = FPSTR(IOTWEBCONF_HTML_FORM_SELECT_PARAM); - - pitem.replace("{b}", this->label); - pitem.replace("{i}", this->getId()); - pitem.replace( - "{c}", this->customHtml == nullptr ? "" : this->customHtml); - pitem.replace( - "{s}", - this->errorMessage == nullptr ? "" : "de"); // Div style class. - pitem.replace( - "{e}", - this->errorMessage == nullptr ? "" : this->errorMessage); - pitem.replace("{o}", options); - - return pitem; - } - -private: -}; - - -/////////////////////////////////////////////////////////////////////////////// - -/** - * Color chooser. - */ -class ColorTParameter : public CharArrayDataType<8>, public InputParameter -{ -public: -using CharArrayDataType<8>::CharArrayDataType; - ColorTParameter(const char* id, const char* label, const char* defaultValue) : - ConfigItemBridge(id), - CharArrayDataType<8>::CharArrayDataType(id, defaultValue), - InputParameter::InputParameter(id, label) { } - -protected: - virtual const char* getInputType() override { return "color"; } -}; - -/////////////////////////////////////////////////////////////////////////////// - -/** - * Date chooser. - */ -class DateTParameter : public CharArrayDataType<11>, public InputParameter -{ -public: -using CharArrayDataType<11>::CharArrayDataType; - DateTParameter(const char* id, const char* label, const char* defaultValue) : - ConfigItemBridge(id), - CharArrayDataType<11>::CharArrayDataType(id, defaultValue), - InputParameter::InputParameter(id, label) { } - -protected: - virtual const char* getInputType() override { return "date"; } -}; - -/////////////////////////////////////////////////////////////////////////////// - -/** - * Time chooser. - */ -class TimeTParameter : public CharArrayDataType<6>, public InputParameter -{ -public: -using CharArrayDataType<6>::CharArrayDataType; - TimeTParameter(const char* id, const char* label, const char* defaultValue) : - ConfigItemBridge(id), - CharArrayDataType<6>::CharArrayDataType(id, defaultValue), - InputParameter::InputParameter(id, label) { } - -protected: - virtual const char* getInputType() override { return "time"; } -}; - -} // end namespace - -#include "IotWebConfTParameterBuilder.h" - -#endif diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfTParameterBuilder.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfTParameterBuilder.h deleted file mode 100644 index 68ff77a6d764f91520e5cbb7c660c51fba2b591a..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfTParameterBuilder.h +++ /dev/null @@ -1,170 +0,0 @@ -/** - * IotWebConfTParameter.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2021 Balazs Kelemen - * rovo89 - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef IotWebConfTParameterBuilder_h -#define IotWebConfTParameterBuilder_h - -#include "IotWebConfTParameter.h" - -namespace iotwebconf -{ - -template class Builder; - -template -class AbstractBuilder -{ -public: - AbstractBuilder(const char* id) : _id(id) { }; - virtual ParamType build() const - { - ParamType instance = std::move( - ParamType(this->_id, this->_label, this->_defaultValue)); - this->apply(&instance); - return instance; - } - - Builder& label(const char* label) - { this->_label = label; return static_cast&>(*this); } - Builder& defaultValue(typename ParamType::DefaultValueType defaultValue) - { this->_defaultValue = defaultValue; return static_cast&>(*this); } - -protected: - virtual ParamType* apply(ParamType* instance) const - { - return instance; - } - const char* _label; - const char* _id; - typename ParamType::DefaultValueType _defaultValue; -}; - -template -class Builder : public AbstractBuilder -{ -public: - Builder(const char* id) : AbstractBuilder(id) { }; -}; - -/////////////////////////////////////////////////////////////////////////// - -template -class PrimitiveBuilder : - public AbstractBuilder -{ -public: - PrimitiveBuilder(const char* id) : - AbstractBuilder(id) { }; - Builder& min(ValueType min) { this->_minDefined = true; this->_min = min; return static_cast&>(*this); } - Builder& max(ValueType max) { this->_maxDefined = true; this->_max = max; return static_cast&>(*this); } - Builder& step(ValueType step) { this->_step = step; return static_cast&>(*this); } - Builder& placeholder(const char* placeholder) { this->_placeholder = placeholder; return static_cast&>(*this); } - -protected: - virtual ParamType* apply( - ParamType* instance) const override - { - if (this->_minDefined) - { - instance->setMin(this->_min); - } - if (this->_maxDefined) - { - instance->setMax(this->_max); - } - instance->setStep(this->_step); - instance->setPlaceholder(this->_placeholder); - return instance; - } - - bool _minDefined = false; - bool _maxDefined = false; - ValueType _min; - ValueType _max; - ValueType _step = 0; - const char* _placeholder = nullptr; -}; - -template -class Builder> : - public PrimitiveBuilder> -{ -public: - Builder>(const char* id) : - PrimitiveBuilder>(id) { }; -}; - -template -class Builder> : - public PrimitiveBuilder> -{ -public: - Builder>(const char* id) : - PrimitiveBuilder>(id) { }; -}; - -template <> -class Builder : - public PrimitiveBuilder -{ -public: - Builder(const char* id) : - PrimitiveBuilder(id) { }; -}; - - -template -class Builder> : - public AbstractBuilder> -{ -public: - Builder>(const char* id) : - AbstractBuilder>(id) { }; - - virtual SelectTParameter build() const override - { - return SelectTParameter( - this->_id, this->_label, this->_defaultValue, - this->_optionValues, this->_optionNames, - this->_optionCount, this->_nameLength); - } - - Builder>& optionValues(const char* optionValues) - { this->_optionValues = optionValues; return *this; } - Builder>& optionNames(const char* optionNames) - { this->_optionNames = optionNames; return *this; } - Builder>& optionCount(size_t optionCount) - { this->_optionCount = optionCount; return *this; } - Builder>& nameLength(size_t nameLength) - { this->_nameLength = nameLength; return *this; } - -protected: - virtual SelectTParameter* apply( - SelectTParameter* instance) const override - { - instance->setOptionValues(this->_optionValues); - instance->setOptionNames(this->_optionNames); - instance->setOptionCount(this->_optionCount); - instance->setNameLength(this->_nameLength); - return instance; - } - -private: - const char* _optionValues; - const char* _optionNames; - size_t _optionCount; - size_t _nameLength; -}; - -} // End namespace - -#endif diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfUsing.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfUsing.h deleted file mode 100644 index c8e121a8e513b04c0a4fafbccebcbf2ad8ff66b6..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfUsing.h +++ /dev/null @@ -1,24 +0,0 @@ -/** - * IotWebConfUsing.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef IotWebConfUsing_h -#define IotWebConfUsing_h - -// This "using" lines are just aliases, and should avoided. - -using IotWebConfParameterGroup = iotwebconf::ParameterGroup; -using IotWebConfTextParameter = iotwebconf::TextParameter; -using IotWebConfPasswordParameter = iotwebconf::PasswordParameter; -using IotWebConfNumberParameter = iotwebconf::NumberParameter; -using IotWebConfCheckboxParameter = iotwebconf::CheckboxParameter; -using IotWebConfSelectParameter = iotwebconf::SelectParameter; - -#endif \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfWebServerWrapper.h b/ampel-firmware/src/lib/IotWebConf/src/IotWebConfWebServerWrapper.h deleted file mode 100644 index 6d9a3b755fc9a5bd49d00a00496709f61e9c9524..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/IotWebConfWebServerWrapper.h +++ /dev/null @@ -1,47 +0,0 @@ -/** - * IotWebConfWebServerWrapper.h -- IotWebConf is an ESP8266/ESP32 - * non blocking WiFi/AP web configuration library for Arduino. - * https://github.com/prampec/IotWebConf - * - * Copyright (C) 2020 Balazs Kelemen - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef WebServerWrapper_h -#define WebServerWrapper_h - -#include -#include - -namespace iotwebconf -{ - -class WebRequestWrapper -{ -public: - virtual const String hostHeader() const; - virtual IPAddress localIP(); - virtual uint16_t localPort(); - virtual const String uri() const; - virtual bool authenticate(const char * username, const char * password); - virtual void requestAuthentication(); - virtual bool hasArg(const String& name); - virtual String arg(const String name); - virtual void sendHeader(const String& name, const String& value, bool first = false); - virtual void setContentLength(const size_t contentLength); - virtual void send(int code, const char* content_type = nullptr, const String& content = String("")); - virtual void sendContent(const String& content); - virtual void stop(); -}; - -class WebServerWrapper -{ -public: - virtual void handleClient(); - virtual void begin(); -}; - -} // end namespace -#endif \ No newline at end of file diff --git a/ampel-firmware/src/lib/IotWebConf/src/custom_ampel_iotwebconf.h b/ampel-firmware/src/lib/IotWebConf/src/custom_ampel_iotwebconf.h deleted file mode 100644 index c79b4e92d18cca85e9e4f5e0434a2b702791647b..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/IotWebConf/src/custom_ampel_iotwebconf.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef CustomAmpelIotWebConfSettings_h -#define CustomAmpelIotWebConfSettings_h -/***************************************/ -/**** CUSTOM AMPEL CODE ****************/ - -// Disable DEBUG, in order to save some space, at least on ESP8266 - -#if defined(ESP8266) -#define IOTWEBCONF_DEBUG_DISABLED -#endif - -// Change this value (between 0 & 3000) in order to force the config to be reloaded. -#define IOTWEBCONF_CONFIG_START 512 - -#endif \ No newline at end of file diff --git a/ampel-firmware/src/lib/NTPClient/CHANGELOG b/ampel-firmware/src/lib/NTPClient/CHANGELOG deleted file mode 100644 index 6a082d59b48d49c1e67495ad2c745108f4375aad..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/NTPClient/CHANGELOG +++ /dev/null @@ -1,15 +0,0 @@ -NTPClient 3.1.0 - 2016.05.31 - -* Added functions for changing the timeOffset and updateInterval later. Thanks @SirUli - -NTPClient 3.0.0 - 2016.04.19 - -* Constructors now require UDP instance argument, to add support for non-ESP8266 boards -* Added optional begin API to override default local port -* Added end API to close UDP socket -* Changed return type of update and forceUpdate APIs to bool, and return success or failure -* Change return type of getDay, getHours, getMinutes, and getSeconds to int - -Older - -* Changes not recorded diff --git a/ampel-firmware/src/lib/NTPClient/NTPClient.cpp b/ampel-firmware/src/lib/NTPClient/NTPClient.cpp deleted file mode 100755 index 45b72dab35804f2f7a9e8c6a7e169ab533751baa..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/NTPClient/NTPClient.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/** - * The MIT License (MIT) - * Copyright (c) 2015 by Fabrice Weinberg - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -#include "NTPClient.h" - -NTPClient::NTPClient(UDP& udp) { - this->_udp = &udp; -} - -NTPClient::NTPClient(UDP& udp, long timeOffset) { - this->_udp = &udp; - this->_timeOffset = timeOffset; -} - -NTPClient::NTPClient(UDP& udp, const char* poolServerName) { - this->_udp = &udp; - this->_poolServerName = poolServerName; -} - -NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP) { - this->_udp = &udp; - this->_poolServerIP = poolServerIP; - this->_poolServerName = NULL; -} - -NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset) { - this->_udp = &udp; - this->_timeOffset = timeOffset; - this->_poolServerName = poolServerName; -} - -NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset){ - this->_udp = &udp; - this->_timeOffset = timeOffset; - this->_poolServerIP = poolServerIP; - this->_poolServerName = NULL; -} - -NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval) { - this->_udp = &udp; - this->_timeOffset = timeOffset; - this->_poolServerName = poolServerName; - this->_updateInterval = updateInterval; -} - -NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset, unsigned long updateInterval) { - this->_udp = &udp; - this->_timeOffset = timeOffset; - this->_poolServerIP = poolServerIP; - this->_poolServerName = NULL; - this->_updateInterval = updateInterval; -} - -void NTPClient::begin() { - this->begin(NTP_DEFAULT_LOCAL_PORT); -} - -void NTPClient::begin(unsigned int port) { - this->_port = port; - - this->_udp->begin(this->_port); - - this->_udpSetup = true; -} - -bool NTPClient::forceUpdate() { - #ifdef DEBUG_NTPClient - Serial.println("Update from NTP Server"); - #endif - - // flush any existing packets - while(this->_udp->parsePacket() != 0) - this->_udp->flush(); - - this->sendNTPPacket(); - - // Wait till data is there or timeout... - byte timeout = 0; - int cb = 0; - do { - delay ( 10 ); - cb = this->_udp->parsePacket(); - if (timeout > 100) return false; // timeout after 1000 ms - timeout++; - } while (cb == 0); - - this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time - - this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE); - - unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]); - unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]); - // combine the four bytes (two words) into a long integer - // this is NTP time (seconds since Jan 1 1900): - unsigned long secsSince1900 = highWord << 16 | lowWord; - - this->_currentEpoc = secsSince1900 - SEVENZYYEARS; - - return true; // return true after successful update -} - -bool NTPClient::update() { - if ((millis() - this->_lastUpdate >= this->_updateInterval) // Update after _updateInterval - || this->_lastUpdate == 0) { // Update if there was no update yet. - if (!this->_udpSetup || this->_port != NTP_DEFAULT_LOCAL_PORT) this->begin(this->_port); // setup the UDP client if needed - return this->forceUpdate(); - } - return false; // return false if update does not occur -} - -bool NTPClient::isTimeSet() const { - return (this->_lastUpdate != 0); // returns true if the time has been set, else false -} - -unsigned long NTPClient::getEpochTime() const { - return this->_timeOffset + // User offset - this->_currentEpoc + // Epoch returned by the NTP server - ((millis() - this->_lastUpdate) / 1000); // Time since last update -} - -int NTPClient::getDay() const { - return (((this->getEpochTime() / 86400L) + 4 ) % 7); //0 is Sunday -} -int NTPClient::getHours() const { - return ((this->getEpochTime() % 86400L) / 3600); -} -int NTPClient::getMinutes() const { - return ((this->getEpochTime() % 3600) / 60); -} -int NTPClient::getSeconds() const { - return (this->getEpochTime() % 60); -} - -void NTPClient::end() { - this->_udp->stop(); - - this->_udpSetup = false; -} - -void NTPClient::setTimeOffset(int timeOffset) { - this->_timeOffset = timeOffset; -} - -void NTPClient::setUpdateInterval(unsigned long updateInterval) { - this->_updateInterval = updateInterval; -} - -void NTPClient::setPoolServerName(const char* poolServerName) { - this->_poolServerName = poolServerName; -} - -void NTPClient::sendNTPPacket() { - // set all bytes in the buffer to 0 - memset(this->_packetBuffer, 0, NTP_PACKET_SIZE); - // Initialize values needed to form NTP request - this->_packetBuffer[0] = 0b11100011; // LI, Version, Mode - this->_packetBuffer[1] = 0; // Stratum, or type of clock - this->_packetBuffer[2] = 6; // Polling Interval - this->_packetBuffer[3] = 0xEC; // Peer Clock Precision - // 8 bytes of zero for Root Delay & Root Dispersion - this->_packetBuffer[12] = 49; - this->_packetBuffer[13] = 0x4E; - this->_packetBuffer[14] = 49; - this->_packetBuffer[15] = 52; - - // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: - if (this->_poolServerName) { - this->_udp->beginPacket(this->_poolServerName, 123); - } else { - this->_udp->beginPacket(this->_poolServerIP, 123); - } - this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE); - this->_udp->endPacket(); -} - -void NTPClient::setRandomPort(unsigned int minValue, unsigned int maxValue) { - randomSeed(analogRead(0)); - this->_port = random(minValue, maxValue); -} - - -/*** Custom code for ampel-firmware ***/ -void NTPClient::getFormattedTime(char *formatted_time, unsigned long secs) { - unsigned long rawTime = secs ? secs : this->getEpochTime(); - unsigned int hours = (rawTime % 86400L) / 3600; - unsigned int minutes = (rawTime % 3600) / 60; - unsigned int seconds = rawTime % 60; - - snprintf(formatted_time, 9, "%02d:%02d:%02d", hours, minutes, seconds); -} - -#define LEAP_YEAR(Y) ( (Y>0) && !(Y%4) && ( (Y%100) || !(Y%400) ) ) - -// Based on https://github.com/PaulStoffregen/Time/blob/master/Time.cpp -void NTPClient::getFormattedDate(char *formatted_date, unsigned long secs) { - unsigned long rawTime = (secs ? secs : this->getEpochTime()) / 86400L; // in days - unsigned long days = 0; - unsigned int year = 1970; - uint8_t month; - static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; - - while((days += (LEAP_YEAR(year) ? 366 : 365)) <= rawTime) - year++; - rawTime -= days - (LEAP_YEAR(year) ? 366 : 365); // now it is days in this year, starting at 0 - days=0; - for (month=0; month<12; month++) { - uint8_t monthLength; - if (month==1) { // february - monthLength = LEAP_YEAR(year) ? 29 : 28; - } else { - monthLength = monthDays[month]; - } - if (rawTime < monthLength) break; - rawTime -= monthLength; - } - month++; // jan is month 1 - rawTime++; // first day is day 1 - - char formatted_time[9]; - this->getFormattedTime(formatted_time, secs); - snprintf(formatted_date, 23, "%4d-%02d-%02lu %s%+03ld", year, month, rawTime, formatted_time, (this->_timeOffset / 3600) % 100); -} - -void NTPClient::setEpochTime(unsigned long secs) { - this->_currentEpoc = secs; -} -/**************************************************************/ \ No newline at end of file diff --git a/ampel-firmware/src/lib/NTPClient/NTPClient.h b/ampel-firmware/src/lib/NTPClient/NTPClient.h deleted file mode 100755 index 9cd0311300db6c5d2667f7a99b98253cce366538..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/NTPClient/NTPClient.h +++ /dev/null @@ -1,129 +0,0 @@ -#pragma once - -#include "Arduino.h" - -#include - -#define SEVENZYYEARS 2208988800UL -#define NTP_PACKET_SIZE 48 -#define NTP_DEFAULT_LOCAL_PORT 1337 - -class NTPClient { - private: - UDP* _udp; - bool _udpSetup = false; - - const char* _poolServerName = "pool.ntp.org"; // Default time server - IPAddress _poolServerIP; - unsigned int _port = NTP_DEFAULT_LOCAL_PORT; - long _timeOffset = 0; - - unsigned long _updateInterval = 60000; // In ms - - unsigned long _currentEpoc = 0; // In ms - unsigned long _lastUpdate = 0; // In ms - - byte _packetBuffer[NTP_PACKET_SIZE]; - - void sendNTPPacket(); - - public: - NTPClient(UDP& udp); - NTPClient(UDP& udp, long timeOffset); - NTPClient(UDP& udp, const char* poolServerName); - NTPClient(UDP& udp, const char* poolServerName, long timeOffset); - NTPClient(UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval); - NTPClient(UDP& udp, IPAddress poolServerIP); - NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset); - NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset, unsigned long updateInterval); - - /** - * Set time server name - * - * @param poolServerName - */ - void setPoolServerName(const char* poolServerName); - - /** - * Set random local port - */ - void setRandomPort(unsigned int minValue = 49152, unsigned int maxValue = 65535); - - /** - * Starts the underlying UDP client with the default local port - */ - void begin(); - - /** - * Starts the underlying UDP client with the specified local port - */ - void begin(unsigned int port); - - /** - * This should be called in the main loop of your application. By default an update from the NTP Server is only - * made every 60 seconds. This can be configured in the NTPClient constructor. - * - * @return true on success, false on failure - */ - bool update(); - - /** - * This will force the update from the NTP Server. - * - * @return true on success, false on failure - */ - bool forceUpdate(); - - /** - * This allows to check if the NTPClient successfully received a NTP packet and set the time. - * - * @return true if time has been set, else false - */ - bool isTimeSet() const; - - int getDay() const; - int getHours() const; - int getMinutes() const; - int getSeconds() const; - - /** - * Changes the time offset. Useful for changing timezones dynamically - */ - void setTimeOffset(int timeOffset); - - /** - * Set the update interval to another frequency. E.g. useful when the - * timeOffset should not be set in the constructor - */ - void setUpdateInterval(unsigned long updateInterval); - - /** - * @return time in seconds since Jan. 1, 1970 - */ - unsigned long getEpochTime() const; - - /** - * Stops the underlying UDP client - */ - void end(); - -/*** Custom code for ampel-firmware ***/ - - /** - * @return secs argument (or 0 for current time) formatted like `hh:mm:ss` - */ - void getFormattedTime(char *formatted_time, unsigned long secs = 0); - - /** - * @return secs argument (or 0 for current date) formatted to ISO 8601 - * like `2004-02-12T15:19:21+00:00` - */ - void getFormattedDate(char *formatted_date, unsigned long secs = 0); - - /** - * Replace the NTP-fetched time with seconds since Jan. 1, 1970 - */ - void setEpochTime(unsigned long secs); - -/**************************************************************/ -}; diff --git a/ampel-firmware/src/lib/NTPClient/README.md b/ampel-firmware/src/lib/NTPClient/README.md deleted file mode 100644 index f83882ce092fc33bc110fc48e72404fb5bc51f3d..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/NTPClient/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# NTPClient - -[![Check Arduino status](https://github.com/arduino-libraries/NTPClient/actions/workflows/check-arduino.yml/badge.svg)](https://github.com/arduino-libraries/NTPClient/actions/workflows/check-arduino.yml) -[![Compile Examples status](https://github.com/arduino-libraries/NTPClient/actions/workflows/compile-examples.yml/badge.svg)](https://github.com/arduino-libraries/NTPClient/actions/workflows/compile-examples.yml) -[![Spell Check status](https://github.com/arduino-libraries/NTPClient/actions/workflows/spell-check.yml/badge.svg)](https://github.com/arduino-libraries/NTPClient/actions/workflows/spell-check.yml) - -Connect to a NTP server, here is how: - -```cpp -#include -// change next line to use with another board/shield -#include -//#include // for WiFi shield -//#include // for WiFi 101 shield or MKR1000 -#include - -const char *ssid = ""; -const char *password = ""; - -WiFiUDP ntpUDP; - -// By default 'pool.ntp.org' is used with 60 seconds update interval and -// no offset -NTPClient timeClient(ntpUDP); - -// You can specify the time server pool and the offset, (in seconds) -// additionally you can specify the update interval (in milliseconds). -// NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000); - -void setup(){ - Serial.begin(115200); - WiFi.begin(ssid, password); - - while ( WiFi.status() != WL_CONNECTED ) { - delay ( 500 ); - Serial.print ( "." ); - } - - timeClient.begin(); -} - -void loop() { - timeClient.update(); - - Serial.println(timeClient.getFormattedTime()); - - delay(1000); -} -``` - -## Function documentation -`getEpochTime` returns the Unix epoch, which are the seconds elapsed since 00:00:00 UTC on 1 January 1970 (leap seconds are ignored, every day is treated as having 86400 seconds). **Attention**: If you have set a time offset this time offset will be added to your epoch timestamp. diff --git a/ampel-firmware/src/lib/NTPClient/keywords.txt b/ampel-firmware/src/lib/NTPClient/keywords.txt deleted file mode 100644 index edce98923ec56a7d11a9f20de8c0557b559e6b35..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/NTPClient/keywords.txt +++ /dev/null @@ -1,24 +0,0 @@ -####################################### -# Datatypes (KEYWORD1) -####################################### - -NTPClient KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -end KEYWORD2 -update KEYWORD2 -forceUpdate KEYWORD2 -isTimeSet KEYWORD2 -getDay KEYWORD2 -getHours KEYWORD2 -getMinutes KEYWORD2 -getSeconds KEYWORD2 -getFormattedTime KEYWORD2 -getEpochTime KEYWORD2 -setTimeOffset KEYWORD2 -setUpdateInterval KEYWORD2 -setPoolServerName KEYWORD2 diff --git a/ampel-firmware/src/lib/NTPClient/library.json b/ampel-firmware/src/lib/NTPClient/library.json deleted file mode 100644 index d6249c1ca4ba708c895048d13bd1e228c33c9047..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/NTPClient/library.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "NTPClient", - "keywords": "ntp, client, time", - "description": "A NTPClient to connect to a time server", - "authors": - [ - { - "name": "Fabrice Weinberg", - "email": "fabrice@weinberg.me" - }, - { - "name": "Sandeep Mistry", - "email": "s.mistry@arduino.cc" - } - ], - "repository": - { - "type": "git", - "url": "https://github.com/arduino-libraries/NTPClient.git" - }, - "version": "3.1.0", - "frameworks": "arduino", - "platforms": "espressif" -} diff --git a/ampel-firmware/src/lib/NTPClient/library.properties b/ampel-firmware/src/lib/NTPClient/library.properties deleted file mode 100644 index 309b75d7dc129f42bc7fc871108410f9b3e1fbea..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/NTPClient/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=NTPClient -version=3.2.0 -author=Fabrice Weinberg -maintainer=Fabrice Weinberg -sentence=An NTPClient to connect to a time server -paragraph=Get time from a NTP server and keep it in sync. -category=Timing -url=https://github.com/arduino-libraries/NTPClient -architectures=* diff --git a/ampel-firmware/src/lib/PubSubClient/CHANGES.txt b/ampel-firmware/src/lib/PubSubClient/CHANGES.txt deleted file mode 100644 index e23d5315f2f2981159a64704f509aa5e9d752832..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/PubSubClient/CHANGES.txt +++ /dev/null @@ -1,85 +0,0 @@ -2.8 - * Add setBufferSize() to override MQTT_MAX_PACKET_SIZE - * Add setKeepAlive() to override MQTT_KEEPALIVE - * Add setSocketTimeout() to overide MQTT_SOCKET_TIMEOUT - * Added check to prevent subscribe/unsubscribe to empty topics - * Declare wifi mode prior to connect in ESP example - * Use `strnlen` to avoid overruns - * Support pre-connected Client objects - -2.7 - * Fix remaining-length handling to prevent buffer overrun - * Add large-payload API - beginPublish/write/publish/endPublish - * Add yield call to improve reliability on ESP - * Add Clean Session flag to connect options - * Add ESP32 support for functional callback signature - * Various other fixes - -2.4 - * Add MQTT_SOCKET_TIMEOUT to prevent it blocking indefinitely - whilst waiting for inbound data - * Fixed return code when publishing >256 bytes - -2.3 - * Add publish(topic,payload,retained) function - -2.2 - * Change code layout to match Arduino Library reqs - -2.1 - * Add MAX_TRANSFER_SIZE def to chunk messages if needed - * Reject topic/payloads that exceed MQTT_MAX_PACKET_SIZE - -2.0 - * Add (and default to) MQTT 3.1.1 support - * Fix PROGMEM handling for Intel Galileo/ESP8266 - * Add overloaded constructors for convenience - * Add chainable setters for server/callback/client/stream - * Add state function to return connack return code - -1.9 - * Do not split MQTT packets over multiple calls to _client->write() - * API change: All constructors now require an instance of Client - to be passed in. - * Fixed example to match 1.8 api changes - dpslwk - * Added username/password support - WilHall - * Added publish_P - publishes messages from PROGMEM - jobytaffey - -1.8 - * KeepAlive interval is configurable in PubSubClient.h - * Maximum packet size is configurable in PubSubClient.h - * API change: Return boolean rather than int from various functions - * API change: Length parameter in message callback changed - from int to unsigned int - * Various internal tidy-ups around types -1.7 - * Improved keepalive handling - * Updated to the Arduino-1.0 API -1.6 - * Added the ability to publish a retained message - -1.5 - * Added default constructor - * Fixed compile error when used with arduino-0021 or later - -1.4 - * Fixed connection lost handling - -1.3 - * Fixed packet reading bug in PubSubClient.readPacket - -1.2 - * Fixed compile error when used with arduino-0016 or later - - -1.1 - * Reduced size of library - * Added support for Will messages - * Clarified licensing - see LICENSE.txt - - -1.0 - * Only Quality of Service (QOS) 0 messaging is supported - * The maximum message size, including header, is 128 bytes - * The keepalive interval is set to 30 seconds - * No support for Will messages diff --git a/ampel-firmware/src/lib/PubSubClient/LICENSE.txt b/ampel-firmware/src/lib/PubSubClient/LICENSE.txt deleted file mode 100644 index 12c1689e6e0de5d0779ee46d1f596531db9ff2dc..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/PubSubClient/LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008-2020 Nicholas O'Leary - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ampel-firmware/src/lib/PubSubClient/README.md b/ampel-firmware/src/lib/PubSubClient/README.md deleted file mode 100644 index 2e131718505fdf80be2588597f743c67e770b794..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/PubSubClient/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# Arduino Client for MQTT - -This library provides a client for doing simple publish/subscribe messaging with -a server that supports MQTT. - -## Examples - -The library comes with a number of example sketches. See File > Examples > PubSubClient -within the Arduino application. - -Full API documentation is available here: https://pubsubclient.knolleary.net - -## Limitations - - - It can only publish QoS 0 messages. It can subscribe at QoS 0 or QoS 1. - - The maximum message size, including header, is **256 bytes** by default. This - is configurable via `MQTT_MAX_PACKET_SIZE` in `PubSubClient.h` or can be changed - by calling `PubSubClient::setBufferSize(size)`. - - The keepalive interval is set to 15 seconds by default. This is configurable - via `MQTT_KEEPALIVE` in `PubSubClient.h` or can be changed by calling - `PubSubClient::setKeepAlive(keepAlive)`. - - The client uses MQTT 3.1.1 by default. It can be changed to use MQTT 3.1 by - changing value of `MQTT_VERSION` in `PubSubClient.h`. - - -## Compatible Hardware - -The library uses the Arduino Ethernet Client api for interacting with the -underlying network hardware. This means it Just Works with a growing number of -boards and shields, including: - - - Arduino Ethernet - - Arduino Ethernet Shield - - Arduino YUN – use the included `YunClient` in place of `EthernetClient`, and - be sure to do a `Bridge.begin()` first - - Arduino WiFi Shield - if you want to send packets > 90 bytes with this shield, - enable the `MQTT_MAX_TRANSFER_SIZE` define in `PubSubClient.h`. - - Sparkfun WiFly Shield – [library](https://github.com/dpslwk/WiFly) - - TI CC3000 WiFi - [library](https://github.com/sparkfun/SFE_CC3000_Library) - - Intel Galileo/Edison - - ESP8266 - - ESP32 - -The library cannot currently be used with hardware based on the ENC28J60 chip – -such as the Nanode or the Nuelectronics Ethernet Shield. For those, there is an -[alternative library](https://github.com/njh/NanodeMQTT) available. - -## License - -This code is released under the MIT License. diff --git a/ampel-firmware/src/lib/PubSubClient/keywords.txt b/ampel-firmware/src/lib/PubSubClient/keywords.txt deleted file mode 100644 index 960a033f93686f447e9ffe91b8da34d16c12e13d..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/PubSubClient/keywords.txt +++ /dev/null @@ -1,36 +0,0 @@ -####################################### -# Syntax Coloring Map For PubSubClient -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -PubSubClient KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -connect KEYWORD2 -disconnect KEYWORD2 -publish KEYWORD2 -publish_P KEYWORD2 -beginPublish KEYWORD2 -endPublish KEYWORD2 -write KEYWORD2 -subscribe KEYWORD2 -unsubscribe KEYWORD2 -loop KEYWORD2 -connected KEYWORD2 -setServer KEYWORD2 -setCallback KEYWORD2 -setClient KEYWORD2 -setStream KEYWORD2 -setKeepAlive KEYWORD2 -setBufferSize KEYWORD2 -setSocketTimeout KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### diff --git a/ampel-firmware/src/lib/PubSubClient/library.json b/ampel-firmware/src/lib/PubSubClient/library.json deleted file mode 100644 index c0d7bae2d01cea07f14cb431f38b2c8ef4eefec2..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/PubSubClient/library.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "PubSubClient", - "keywords": "ethernet, mqtt, m2m, iot", - "description": "A client library for MQTT messaging. MQTT is a lightweight messaging protocol ideal for small devices. This library allows you to send and receive MQTT messages. It supports the latest MQTT 3.1.1 protocol and can be configured to use the older MQTT 3.1 if needed. It supports all Arduino Ethernet Client compatible hardware, including the Intel Galileo/Edison, ESP8266 and TI CC3000.", - "repository": { - "type": "git", - "url": "https://github.com/knolleary/pubsubclient.git" - }, - "version": "2.8", - "exclude": "tests", - "examples": "examples/*/*.ino", - "frameworks": "arduino", - "platforms": [ - "atmelavr", - "espressif8266", - "espressif32" - ] -} diff --git a/ampel-firmware/src/lib/PubSubClient/library.properties b/ampel-firmware/src/lib/PubSubClient/library.properties deleted file mode 100644 index e47ffe9280d65213489832b7baa7567ad409b6e6..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/PubSubClient/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=PubSubClient -version=2.8 -author=Nick O'Leary -maintainer=Nick O'Leary -sentence=A client library for MQTT messaging. -paragraph=MQTT is a lightweight messaging protocol ideal for small devices. This library allows you to send and receive MQTT messages. It supports the latest MQTT 3.1.1 protocol and can be configured to use the older MQTT 3.1 if needed. It supports all Arduino Ethernet Client compatible hardware, including the Intel Galileo/Edison, ESP8266 and TI CC3000. -category=Communication -url=http://pubsubclient.knolleary.net -architectures=* diff --git a/ampel-firmware/src/lib/PubSubClient/src/PubSubClient.cpp b/ampel-firmware/src/lib/PubSubClient/src/PubSubClient.cpp deleted file mode 100644 index 2619e58e8c0b32c2f2051223140c3d40459e9bc2..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/PubSubClient/src/PubSubClient.cpp +++ /dev/null @@ -1,775 +0,0 @@ -/* - - PubSubClient.cpp - A simple client for MQTT. - Nick O'Leary - http://knolleary.net - */ - -#include "PubSubClient.h" -#include "Arduino.h" - -PubSubClient::PubSubClient() { - this->_state = MQTT_DISCONNECTED; - this->_client = NULL; - this->stream = NULL; - setCallback(NULL); - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} - -PubSubClient::PubSubClient(Client &client) { - this->_state = MQTT_DISCONNECTED; - setClient(client); - this->stream = NULL; - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} - -PubSubClient::PubSubClient(IPAddress addr, uint16_t port, Client &client) { - this->_state = MQTT_DISCONNECTED; - setServer(addr, port); - setClient(client); - this->stream = NULL; - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} -PubSubClient::PubSubClient(IPAddress addr, uint16_t port, Client &client, Stream &stream) { - this->_state = MQTT_DISCONNECTED; - setServer(addr, port); - setClient(client); - setStream(stream); - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} -PubSubClient::PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client) { - this->_state = MQTT_DISCONNECTED; - setServer(addr, port); - setCallback(callback); - setClient(client); - this->stream = NULL; - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} -PubSubClient::PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client, Stream &stream) { - this->_state = MQTT_DISCONNECTED; - setServer(addr, port); - setCallback(callback); - setClient(client); - setStream(stream); - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} - -PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, Client &client) { - this->_state = MQTT_DISCONNECTED; - setServer(ip, port); - setClient(client); - this->stream = NULL; - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} -PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, Client &client, Stream &stream) { - this->_state = MQTT_DISCONNECTED; - setServer(ip, port); - setClient(client); - setStream(stream); - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} -PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client) { - this->_state = MQTT_DISCONNECTED; - setServer(ip, port); - setCallback(callback); - setClient(client); - this->stream = NULL; - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} -PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client, Stream &stream) { - this->_state = MQTT_DISCONNECTED; - setServer(ip, port); - setCallback(callback); - setClient(client); - setStream(stream); - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} - -PubSubClient::PubSubClient(const char *domain, uint16_t port, Client &client) { - this->_state = MQTT_DISCONNECTED; - setServer(domain, port); - setClient(client); - this->stream = NULL; - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} -PubSubClient::PubSubClient(const char *domain, uint16_t port, Client &client, Stream &stream) { - this->_state = MQTT_DISCONNECTED; - setServer(domain, port); - setClient(client); - setStream(stream); - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} -PubSubClient::PubSubClient(const char *domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client) { - this->_state = MQTT_DISCONNECTED; - setServer(domain, port); - setCallback(callback); - setClient(client); - this->stream = NULL; - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} -PubSubClient::PubSubClient(const char *domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client, Stream &stream) { - this->_state = MQTT_DISCONNECTED; - setServer(domain, port); - setCallback(callback); - setClient(client); - setStream(stream); - this->bufferSize = 0; - setBufferSize(MQTT_MAX_PACKET_SIZE); - setKeepAlive(MQTT_KEEPALIVE); - setSocketTimeout(MQTT_SOCKET_TIMEOUT); -} - -PubSubClient::~PubSubClient() { - free(this->buffer); -} - -boolean PubSubClient::connect(const char *id) { - return connect(id, NULL, NULL, 0, 0, 0, 0, 1); -} - -boolean PubSubClient::connect(const char *id, const char *user, const char *pass) { - return connect(id, user, pass, 0, 0, 0, 0, 1); -} - -boolean PubSubClient::connect(const char *id, const char *willTopic, uint8_t willQos, boolean willRetain, - const char *willMessage) { - return connect(id, NULL, NULL, willTopic, willQos, willRetain, willMessage, 1); -} - -boolean PubSubClient::connect(const char *id, const char *user, const char *pass, const char *willTopic, - uint8_t willQos, boolean willRetain, const char *willMessage) { - return connect(id, user, pass, willTopic, willQos, willRetain, willMessage, 1); -} - -boolean PubSubClient::connect(const char *id, const char *user, const char *pass, const char *willTopic, - uint8_t willQos, boolean willRetain, const char *willMessage, boolean cleanSession) { - if (!connected()) { - int result = 0; - - if (_client->connected()) { - result = 1; - } else { - if (domain != NULL) { - result = _client->connect(this->domain, this->port); - } else { - result = _client->connect(this->ip, this->port); - } - } - - if (result == 1) { - nextMsgId = 1; - // Leave room in the buffer for header and variable length field - uint16_t length = MQTT_MAX_HEADER_SIZE; - unsigned int j; - -#if MQTT_VERSION == MQTT_VERSION_3_1 - uint8_t d[9] = {0x00,0x06,'M','Q','I','s','d','p', MQTT_VERSION}; -#define MQTT_HEADER_VERSION_LENGTH 9 -#elif MQTT_VERSION == MQTT_VERSION_3_1_1 - uint8_t d[7] = { 0x00, 0x04, 'M', 'Q', 'T', 'T', MQTT_VERSION }; -#define MQTT_HEADER_VERSION_LENGTH 7 -#endif - for (j = 0; j < MQTT_HEADER_VERSION_LENGTH; j++) { - this->buffer[length++] = d[j]; - } - - uint8_t v; - if (willTopic) { - v = 0x04 | (willQos << 3) | (willRetain << 5); - } else { - v = 0x00; - } - if (cleanSession) { - v = v | 0x02; - } - - if (user != NULL) { - v = v | 0x80; - - if (pass != NULL) { - v = v | (0x80 >> 1); - } - } - this->buffer[length++] = v; - - this->buffer[length++] = ((this->keepAlive) >> 8); - this->buffer[length++] = ((this->keepAlive) & 0xFF); - - CHECK_STRING_LENGTH(length, id) - length = writeString(id, this->buffer, length); - if (willTopic) { - CHECK_STRING_LENGTH(length, willTopic) - length = writeString(willTopic, this->buffer, length); - CHECK_STRING_LENGTH(length, willMessage) - length = writeString(willMessage, this->buffer, length); - } - - if (user != NULL) { - CHECK_STRING_LENGTH(length, user) - length = writeString(user, this->buffer, length); - if (pass != NULL) { - CHECK_STRING_LENGTH(length, pass) - length = writeString(pass, this->buffer, length); - } - } - - write(MQTTCONNECT, this->buffer, length - MQTT_MAX_HEADER_SIZE); - - lastInActivity = lastOutActivity = millis(); - - while (!_client->available()) { - unsigned long t = millis(); - if (t - lastInActivity >= ((int32_t) this->socketTimeout * 1000UL)) { - _state = MQTT_CONNECTION_TIMEOUT; - _client->stop(); - return false; - } - } - uint8_t llen; - uint32_t len = readPacket(&llen); - - if (len == 4) { - if (buffer[3] == 0) { - lastInActivity = millis(); - pingOutstanding = false; - _state = MQTT_CONNECTED; - return true; - } else { - _state = buffer[3]; - } - } - _client->stop(); - } else { - _state = MQTT_CONNECT_FAILED; - } - return false; - } - return true; -} - -// reads a byte into result -boolean PubSubClient::readByte(uint8_t *result) { - uint32_t previousMillis = millis(); - while (!_client->available()) { - yield(); - uint32_t currentMillis = millis(); - if (currentMillis - previousMillis >= ((int32_t) this->socketTimeout * 1000)) { - return false; - } - } - *result = _client->read(); - return true; -} - -// reads a byte into result[*index] and increments index -boolean PubSubClient::readByte(uint8_t *result, uint16_t *index) { - uint16_t current_index = *index; - uint8_t *write_address = &(result[current_index]); - if (readByte(write_address)) { - *index = current_index + 1; - return true; - } - return false; -} - -uint32_t PubSubClient::readPacket(uint8_t *lengthLength) { - uint16_t len = 0; - if (!readByte(this->buffer, &len)) - return 0; - bool isPublish = (this->buffer[0] & 0xF0) == MQTTPUBLISH; - uint32_t multiplier = 1; - uint32_t length = 0; - uint8_t digit = 0; - uint16_t skip = 0; - uint32_t start = 0; - - do { - if (len == 5) { - // Invalid remaining length encoding - kill the connection - _state = MQTT_DISCONNECTED; - _client->stop(); - return 0; - } - if (!readByte(&digit)) - return 0; - this->buffer[len++] = digit; - length += (digit & 127) * multiplier; - multiplier <<= 7; //multiplier *= 128 - } while ((digit & 128) != 0); - *lengthLength = len - 1; - - if (isPublish) { - // Read in topic length to calculate bytes to skip over for Stream writing - if (!readByte(this->buffer, &len)) - return 0; - if (!readByte(this->buffer, &len)) - return 0; - skip = (this->buffer[*lengthLength + 1] << 8) + this->buffer[*lengthLength + 2]; - start = 2; - if (this->buffer[0] & MQTTQOS1) { - // skip message id - skip += 2; - } - } - uint32_t idx = len; - - for (uint32_t i = start; i < length; i++) { - if (!readByte(&digit)) - return 0; - if (this->stream) { - if (isPublish && idx - *lengthLength - 2 > skip) { - this->stream->write(digit); - } - } - - if (len < this->bufferSize) { - this->buffer[len] = digit; - len++; - } - idx++; - } - - if (!this->stream && idx > this->bufferSize) { - len = 0; // This will cause the packet to be ignored. - } - return len; -} - -boolean PubSubClient::loop() { - if (connected()) { - unsigned long t = millis(); - if ((t - lastInActivity > this->keepAlive * 1000UL) || (t - lastOutActivity > this->keepAlive * 1000UL)) { - if (pingOutstanding) { - this->_state = MQTT_CONNECTION_TIMEOUT; - _client->stop(); - return false; - } else { - this->buffer[0] = MQTTPINGREQ; - this->buffer[1] = 0; - _client->write(this->buffer, 2); - lastOutActivity = t; - lastInActivity = t; - pingOutstanding = true; - } - } - if (_client->available()) { - uint8_t llen; - uint16_t len = readPacket(&llen); - uint16_t msgId = 0; - uint8_t *payload; - if (len > 0) { - lastInActivity = t; - uint8_t type = this->buffer[0] & 0xF0; - if (type == MQTTPUBLISH) { - if (callback) { - uint16_t tl = (this->buffer[llen + 1] << 8) + this->buffer[llen + 2]; /* topic length in bytes */ - memmove(this->buffer + llen + 2, this->buffer + llen + 3, tl); /* move topic inside buffer 1 byte to front */ - this->buffer[llen + 2 + tl] = 0; /* end the topic as a 'C' string with \x00 */ - char *topic = (char*) this->buffer + llen + 2; - // msgId only present for QOS>0 - if ((this->buffer[0] & 0x06) == MQTTQOS1) { - msgId = (this->buffer[llen + 3 + tl] << 8) + this->buffer[llen + 3 + tl + 1]; - payload = this->buffer + llen + 3 + tl + 2; - callback(topic, payload, len - llen - 3 - tl - 2); - - this->buffer[0] = MQTTPUBACK; - this->buffer[1] = 2; - this->buffer[2] = (msgId >> 8); - this->buffer[3] = (msgId & 0xFF); - _client->write(this->buffer, 4); - lastOutActivity = t; - - } else { - payload = this->buffer + llen + 3 + tl; - callback(topic, payload, len - llen - 3 - tl); - } - } - } else if (type == MQTTPINGREQ) { - this->buffer[0] = MQTTPINGRESP; - this->buffer[1] = 0; - _client->write(this->buffer, 2); - } else if (type == MQTTPINGRESP) { - pingOutstanding = false; - } - } else if (!connected()) { - // readPacket has closed the connection - return false; - } - } - return true; - } - return false; -} - -boolean PubSubClient::publish(const char *topic, const char *payload) { - return publish(topic, (const uint8_t*) payload, payload ? strnlen(payload, this->bufferSize) : 0, false); -} - -boolean PubSubClient::publish(const char *topic, const char *payload, boolean retained) { - return publish(topic, (const uint8_t*) payload, payload ? strnlen(payload, this->bufferSize) : 0, retained); -} - -boolean PubSubClient::publish(const char *topic, const uint8_t *payload, unsigned int plength) { - return publish(topic, payload, plength, false); -} - -boolean PubSubClient::publish(const char *topic, const uint8_t *payload, unsigned int plength, boolean retained) { - if (connected()) { - if (this->bufferSize < MQTT_MAX_HEADER_SIZE + 2 + strnlen(topic, this->bufferSize) + plength) { - // Too long - return false; - } - // Leave room in the buffer for header and variable length field - uint16_t length = MQTT_MAX_HEADER_SIZE; - length = writeString(topic, this->buffer, length); - - // Add payload - uint16_t i; - for (i = 0; i < plength; i++) { - this->buffer[length++] = payload[i]; - } - - // Write the header - uint8_t header = MQTTPUBLISH; - if (retained) { - header |= 1; - } - return write(header, this->buffer, length - MQTT_MAX_HEADER_SIZE); - } - return false; -} - -boolean PubSubClient::publish_P(const char *topic, const char *payload, boolean retained) { - return publish_P(topic, (const uint8_t*) payload, payload ? strnlen(payload, this->bufferSize) : 0, retained); -} - -boolean PubSubClient::publish_P(const char *topic, const uint8_t *payload, unsigned int plength, boolean retained) { - uint8_t llen = 0; - uint8_t digit; - unsigned int rc = 0; - uint16_t tlen; - unsigned int pos = 0; - unsigned int i; - uint8_t header; - unsigned int len; - uint32_t expectedLength; - - if (!connected()) { - return false; - } - - tlen = strnlen(topic, this->bufferSize); - - header = MQTTPUBLISH; - if (retained) { - header |= 1; - } - this->buffer[pos++] = header; - len = plength + 2 + tlen; - do { - digit = len & 127; //digit = len %128 - len >>= 7; //len = len / 128 - if (len > 0) { - digit |= 0x80; - } - this->buffer[pos++] = digit; - llen++; - } while (len > 0); - - pos = writeString(topic, this->buffer, pos); - - rc += _client->write(this->buffer, pos); - - for (i = 0; i < plength; i++) { - rc += _client->write((char) pgm_read_byte_near(payload + i)); - } - - lastOutActivity = millis(); - - expectedLength = 1 + llen + 2 + tlen + plength; - - return (rc == expectedLength); -} - -boolean PubSubClient::beginPublish(const char *topic, unsigned int plength, boolean retained) { - if (connected()) { - // Send the header and variable length field - uint16_t length = MQTT_MAX_HEADER_SIZE; - length = writeString(topic, this->buffer, length); - uint8_t header = MQTTPUBLISH; - if (retained) { - header |= 1; - } - size_t hlen = buildHeader(header, this->buffer, plength + length - MQTT_MAX_HEADER_SIZE); - uint16_t rc = _client->write(this->buffer + (MQTT_MAX_HEADER_SIZE - hlen), length - (MQTT_MAX_HEADER_SIZE - hlen)); - lastOutActivity = millis(); - return (rc == (length - (MQTT_MAX_HEADER_SIZE - hlen))); - } - return false; -} - -int PubSubClient::endPublish() { - return 1; -} - -size_t PubSubClient::write(uint8_t data) { - lastOutActivity = millis(); - return _client->write(data); -} - -size_t PubSubClient::write(const uint8_t *buffer, size_t size) { - lastOutActivity = millis(); - return _client->write(buffer, size); -} - -size_t PubSubClient::buildHeader(uint8_t header, uint8_t *buf, uint16_t length) { - uint8_t lenBuf[4]; - uint8_t llen = 0; - uint8_t digit; - uint8_t pos = 0; - uint16_t len = length; - do { - - digit = len & 127; //digit = len %128 - len >>= 7; //len = len / 128 - if (len > 0) { - digit |= 0x80; - } - lenBuf[pos++] = digit; - llen++; - } while (len > 0); - - buf[4 - llen] = header; - for (int i = 0; i < llen; i++) { - buf[MQTT_MAX_HEADER_SIZE - llen + i] = lenBuf[i]; - } - return llen + 1; // Full header size is variable length bit plus the 1-byte fixed header -} - -boolean PubSubClient::write(uint8_t header, uint8_t *buf, uint16_t length) { - uint16_t rc; - uint8_t hlen = buildHeader(header, buf, length); - -#ifdef MQTT_MAX_TRANSFER_SIZE - uint8_t* writeBuf = buf+(MQTT_MAX_HEADER_SIZE-hlen); - uint16_t bytesRemaining = length+hlen; //Match the length type - uint8_t bytesToWrite; - boolean result = true; - while((bytesRemaining > 0) && result) { - bytesToWrite = (bytesRemaining > MQTT_MAX_TRANSFER_SIZE)?MQTT_MAX_TRANSFER_SIZE:bytesRemaining; - rc = _client->write(writeBuf,bytesToWrite); - result = (rc == bytesToWrite); - bytesRemaining -= rc; - writeBuf += rc; - } - return result; -#else - rc = _client->write(buf + (MQTT_MAX_HEADER_SIZE - hlen), length + hlen); - lastOutActivity = millis(); - return (rc == hlen + length); -#endif -} - -boolean PubSubClient::subscribe(const char *topic) { - return subscribe(topic, 0); -} - -boolean PubSubClient::subscribe(const char *topic, uint8_t qos) { - size_t topicLength = strnlen(topic, this->bufferSize); - if (topic == 0) { - return false; - } - if (qos > 1) { - return false; - } - if (this->bufferSize < 9 + topicLength) { - // Too long - return false; - } - if (connected()) { - // Leave room in the buffer for header and variable length field - uint16_t length = MQTT_MAX_HEADER_SIZE; - nextMsgId++; - if (nextMsgId == 0) { - nextMsgId = 1; - } - this->buffer[length++] = (nextMsgId >> 8); - this->buffer[length++] = (nextMsgId & 0xFF); - length = writeString((char*) topic, this->buffer, length); - this->buffer[length++] = qos; - return write(MQTTSUBSCRIBE | MQTTQOS1, this->buffer, length - MQTT_MAX_HEADER_SIZE); - } - return false; -} - -boolean PubSubClient::unsubscribe(const char *topic) { - size_t topicLength = strnlen(topic, this->bufferSize); - if (topic == 0) { - return false; - } - if (this->bufferSize < 9 + topicLength) { - // Too long - return false; - } - if (connected()) { - uint16_t length = MQTT_MAX_HEADER_SIZE; - nextMsgId++; - if (nextMsgId == 0) { - nextMsgId = 1; - } - this->buffer[length++] = (nextMsgId >> 8); - this->buffer[length++] = (nextMsgId & 0xFF); - length = writeString(topic, this->buffer, length); - return write(MQTTUNSUBSCRIBE | MQTTQOS1, this->buffer, length - MQTT_MAX_HEADER_SIZE); - } - return false; -} - -void PubSubClient::disconnect() { - this->buffer[0] = MQTTDISCONNECT; - this->buffer[1] = 0; - _client->write(this->buffer, 2); - _state = MQTT_DISCONNECTED; - _client->flush(); - _client->stop(); - lastInActivity = lastOutActivity = millis(); -} - -uint16_t PubSubClient::writeString(const char *string, uint8_t *buf, uint16_t pos) { - const char *idp = string; - uint16_t i = 0; - pos += 2; - while (*idp) { - buf[pos++] = *idp++; - i++; - } - buf[pos - i - 2] = (i >> 8); - buf[pos - i - 1] = (i & 0xFF); - return pos; -} - -boolean PubSubClient::connected() { - boolean rc; - if (_client == NULL) { - rc = false; - } else { - rc = (int) _client->connected(); - if (!rc) { - if (this->_state == MQTT_CONNECTED) { - this->_state = MQTT_CONNECTION_LOST; - _client->flush(); - _client->stop(); - } - } else { - return this->_state == MQTT_CONNECTED; - } - } - return rc; -} - -PubSubClient& PubSubClient::setServer(uint8_t *ip, uint16_t port) { - IPAddress addr(ip[0], ip[1], ip[2], ip[3]); - return setServer(addr, port); -} - -PubSubClient& PubSubClient::setServer(IPAddress ip, uint16_t port) { - this->ip = ip; - this->port = port; - this->domain = NULL; - return *this; -} - -PubSubClient& PubSubClient::setServer(const char *domain, uint16_t port) { - this->domain = domain; - this->port = port; - return *this; -} - -PubSubClient& PubSubClient::setCallback(MQTT_CALLBACK_SIGNATURE) { - this->callback = callback; - return *this; -} - -PubSubClient& PubSubClient::setClient(Client &client) { - this->_client = &client; - return *this; -} - -PubSubClient& PubSubClient::setStream(Stream &stream) { - this->stream = &stream; - return *this; -} - -int PubSubClient::state() { - return this->_state; -} - -boolean PubSubClient::setBufferSize(uint16_t size) { - if (size == 0) { - // Cannot set it back to 0 - return false; - } - if (this->bufferSize == 0) { - this->buffer = (uint8_t*) malloc(size); - } else { - uint8_t *newBuffer = (uint8_t*) realloc(this->buffer, size); - if (newBuffer != NULL) { - this->buffer = newBuffer; - } else { - return false; - } - } - this->bufferSize = size; - return (this->buffer != NULL); -} - -uint16_t PubSubClient::getBufferSize() { - return this->bufferSize; -} -PubSubClient& PubSubClient::setKeepAlive(uint16_t keepAlive) { - this->keepAlive = keepAlive; - return *this; -} -PubSubClient& PubSubClient::setSocketTimeout(uint16_t timeout) { - this->socketTimeout = timeout; - return *this; -} diff --git a/ampel-firmware/src/lib/PubSubClient/src/PubSubClient.h b/ampel-firmware/src/lib/PubSubClient/src/PubSubClient.h deleted file mode 100644 index c70d9fd392bc3018a61ddf1ff9632986eeca0801..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/PubSubClient/src/PubSubClient.h +++ /dev/null @@ -1,184 +0,0 @@ -/* - PubSubClient.h - A simple client for MQTT. - Nick O'Leary - http://knolleary.net -*/ - -#ifndef PubSubClient_h -#define PubSubClient_h - -#include -#include "IPAddress.h" -#include "Client.h" -#include "Stream.h" - -#define MQTT_VERSION_3_1 3 -#define MQTT_VERSION_3_1_1 4 - -// MQTT_VERSION : Pick the version -//#define MQTT_VERSION MQTT_VERSION_3_1 -#ifndef MQTT_VERSION -#define MQTT_VERSION MQTT_VERSION_3_1_1 -#endif - -// MQTT_MAX_PACKET_SIZE : Maximum packet size. Override with setBufferSize(). -#ifndef MQTT_MAX_PACKET_SIZE -#define MQTT_MAX_PACKET_SIZE 256 -#endif - -// MQTT_KEEPALIVE : keepAlive interval in Seconds. Override with setKeepAlive() -#ifndef MQTT_KEEPALIVE -#define MQTT_KEEPALIVE 15 -#endif - -// MQTT_SOCKET_TIMEOUT: socket timeout interval in Seconds. Override with setSocketTimeout() -#ifndef MQTT_SOCKET_TIMEOUT -#define MQTT_SOCKET_TIMEOUT 15 -#endif - -// MQTT_MAX_TRANSFER_SIZE : limit how much data is passed to the network client -// in each write call. Needed for the Arduino Wifi Shield. Leave undefined to -// pass the entire MQTT packet in each write call. -//#define MQTT_MAX_TRANSFER_SIZE 80 - -// Possible values for client.state() -#define MQTT_CONNECTION_TIMEOUT -4 -#define MQTT_CONNECTION_LOST -3 -#define MQTT_CONNECT_FAILED -2 -#define MQTT_DISCONNECTED -1 -#define MQTT_CONNECTED 0 -#define MQTT_CONNECT_BAD_PROTOCOL 1 -#define MQTT_CONNECT_BAD_CLIENT_ID 2 -#define MQTT_CONNECT_UNAVAILABLE 3 -#define MQTT_CONNECT_BAD_CREDENTIALS 4 -#define MQTT_CONNECT_UNAUTHORIZED 5 - -#define MQTTCONNECT 1 << 4 // Client request to connect to Server -#define MQTTCONNACK 2 << 4 // Connect Acknowledgment -#define MQTTPUBLISH 3 << 4 // Publish message -#define MQTTPUBACK 4 << 4 // Publish Acknowledgment -#define MQTTPUBREC 5 << 4 // Publish Received (assured delivery part 1) -#define MQTTPUBREL 6 << 4 // Publish Release (assured delivery part 2) -#define MQTTPUBCOMP 7 << 4 // Publish Complete (assured delivery part 3) -#define MQTTSUBSCRIBE 8 << 4 // Client Subscribe request -#define MQTTSUBACK 9 << 4 // Subscribe Acknowledgment -#define MQTTUNSUBSCRIBE 10 << 4 // Client Unsubscribe request -#define MQTTUNSUBACK 11 << 4 // Unsubscribe Acknowledgment -#define MQTTPINGREQ 12 << 4 // PING Request -#define MQTTPINGRESP 13 << 4 // PING Response -#define MQTTDISCONNECT 14 << 4 // Client is Disconnecting -#define MQTTReserved 15 << 4 // Reserved - -#define MQTTQOS0 (0 << 1) -#define MQTTQOS1 (1 << 1) -#define MQTTQOS2 (2 << 1) - -// Maximum size of fixed header and variable length size header -#define MQTT_MAX_HEADER_SIZE 5 - -#if defined(ESP8266) || defined(ESP32) -#include -#define MQTT_CALLBACK_SIGNATURE std::function callback -#else -#define MQTT_CALLBACK_SIGNATURE void (*callback)(char*, uint8_t*, unsigned int) -#endif - -#define CHECK_STRING_LENGTH(l,s) if (l+2+strnlen(s, this->bufferSize) > this->bufferSize) {_client->stop();return false;} - -class PubSubClient : public Print { -private: - Client* _client; - uint8_t* buffer; - uint16_t bufferSize; - uint16_t keepAlive; - uint16_t socketTimeout; - uint16_t nextMsgId; - unsigned long lastOutActivity; - unsigned long lastInActivity; - bool pingOutstanding; - MQTT_CALLBACK_SIGNATURE; - uint32_t readPacket(uint8_t*); - boolean readByte(uint8_t * result); - boolean readByte(uint8_t * result, uint16_t * index); - boolean write(uint8_t header, uint8_t* buf, uint16_t length); - uint16_t writeString(const char* string, uint8_t* buf, uint16_t pos); - // Build up the header ready to send - // Returns the size of the header - // Note: the header is built at the end of the first MQTT_MAX_HEADER_SIZE bytes, so will start - // (MQTT_MAX_HEADER_SIZE - ) bytes into the buffer - size_t buildHeader(uint8_t header, uint8_t* buf, uint16_t length); - IPAddress ip; - const char* domain; - uint16_t port; - Stream* stream; - int _state; -public: - PubSubClient(); - PubSubClient(Client& client); - PubSubClient(IPAddress, uint16_t, Client& client); - PubSubClient(IPAddress, uint16_t, Client& client, Stream&); - PubSubClient(IPAddress, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client); - PubSubClient(IPAddress, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&); - PubSubClient(uint8_t *, uint16_t, Client& client); - PubSubClient(uint8_t *, uint16_t, Client& client, Stream&); - PubSubClient(uint8_t *, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client); - PubSubClient(uint8_t *, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&); - PubSubClient(const char*, uint16_t, Client& client); - PubSubClient(const char*, uint16_t, Client& client, Stream&); - PubSubClient(const char*, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client); - PubSubClient(const char*, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&); - - ~PubSubClient(); - - PubSubClient& setServer(IPAddress ip, uint16_t port); - PubSubClient& setServer(uint8_t * ip, uint16_t port); - PubSubClient& setServer(const char * domain, uint16_t port); - PubSubClient& setCallback(MQTT_CALLBACK_SIGNATURE); - PubSubClient& setClient(Client& client); - PubSubClient& setStream(Stream& stream); - PubSubClient& setKeepAlive(uint16_t keepAlive); - PubSubClient& setSocketTimeout(uint16_t timeout); - - boolean setBufferSize(uint16_t size); - uint16_t getBufferSize(); - - boolean connect(const char* id); - boolean connect(const char* id, const char* user, const char* pass); - boolean connect(const char* id, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage); - boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage); - boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage, boolean cleanSession); - void disconnect(); - boolean publish(const char* topic, const char* payload); - boolean publish(const char* topic, const char* payload, boolean retained); - boolean publish(const char* topic, const uint8_t * payload, unsigned int plength); - boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained); - boolean publish_P(const char* topic, const char* payload, boolean retained); - boolean publish_P(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained); - // Start to publish a message. - // This API: - // beginPublish(...) - // one or more calls to write(...) - // endPublish() - // Allows for arbitrarily large payloads to be sent without them having to be copied into - // a new buffer and held in memory at one time - // Returns 1 if the message was started successfully, 0 if there was an error - boolean beginPublish(const char* topic, unsigned int plength, boolean retained); - // Finish off this publish message (started with beginPublish) - // Returns 1 if the packet was sent successfully, 0 if there was an error - int endPublish(); - // Write a single byte of payload (only to be used with beginPublish/endPublish) - virtual size_t write(uint8_t); - // Write size bytes from buffer into the payload (only to be used with beginPublish/endPublish) - // Returns the number of bytes written - virtual size_t write(const uint8_t *buffer, size_t size); - boolean subscribe(const char* topic); - boolean subscribe(const char* topic, uint8_t qos); - boolean unsubscribe(const char* topic); - boolean loop(); - boolean connected(); - int state(); - -}; - - -#endif diff --git a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/LICENSE.md b/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/LICENSE.md deleted file mode 100644 index 37238686da3d06815b45154961d5744d28516153..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/LICENSE.md +++ /dev/null @@ -1,55 +0,0 @@ -SparkFun License Information -============================ - -SparkFun uses two different licenses for our files — one for hardware and one for code. - -Hardware ---------- - -**SparkFun hardware is released under [Creative Commons Share-alike 4.0 International](http://creativecommons.org/licenses/by-sa/4.0/).** - -Note: This is a human-readable summary of (and not a substitute for) the [license](http://creativecommons.org/licenses/by-sa/4.0/legalcode). - -You are free to: - -Share — copy and redistribute the material in any medium or format -Adapt — remix, transform, and build upon the material -for any purpose, even commercially. -The licensor cannot revoke these freedoms as long as you follow the license terms. -Under the following terms: - -Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. -ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. -No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. -Notices: - -You do not have to comply with the license for elements of the material in the public domain or where your use is permitted by an applicable exception or limitation. -No warranties are given. The license may not give you all of the permissions necessary for your intended use. For example, other rights such as publicity, privacy, or moral rights may limit how you use the material. - - -Code --------- - -**SparkFun code, firmware, and software is released under the MIT License(http://opensource.org/licenses/MIT).** - -The MIT License (MIT) - -Copyright (c) 2020 SparkFun Electronics - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/README.md b/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/README.md deleted file mode 100644 index 9be1a0eae22818145a733f66955603ef007c49a9..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/README.md +++ /dev/null @@ -1,51 +0,0 @@ -SparkFun SCD30 CO₂ Sensor Library -=========================================================== - -![SparkFun SCD30 CO₂ Sensor](https://cdn.sparkfun.com//assets/parts/1/2/9/8/4/SparkFun_Sensirion_SCD30.jpg) - -[*SparkX CO₂ Humidity and Temperature Sensor - SCD30 (SPX-14751)*](https://www.sparkfun.com/products/14751) - -The SCD30 from Sensirion is a high quality [NDIR](https://en.wikipedia.org/wiki/Nondispersive_infrared_sensor) based CO₂ sensor capable of detecting 400 to 10000ppm with an accuracy of ±(30ppm+3%). In order to improve accuracy the SCD30 has temperature and humidity sensing built-in, as well as commands to compensate for altitude. - -We've written an Arduino library to make reading the CO₂, humidity, and temperature very easy. It can be downloaded through the Arduino Library manager: search for 'SparkFun SCD30'. We recommend using a [Qwiic Breadboard Cable](https://www.sparkfun.com/products/14425) to connect the SCD30 to a Qwiic compatible board. The Ye*LL*ow wire goes in the SC*L* pin. The SCD30 also supports a serial interface but we haven't worked with it. - -The CO₂ sensor works very well and for additional accuracy the SCD30 accepts ambient pressure readings. We recommend using the SCD30 in conjunction with the [Qwiic Pressure Sensor - MS5637](https://www.sparkfun.com/products/14688) or the [Qwiic Environmental Sensor - BME680](https://www.sparkfun.com/products/14570) to obtain the current barometric pressure. - -Note: The SCD30 has an automatic self-calibration routine. Sensirion recommends 7 days of continuous readings with at least 1 hour a day of 'fresh air' for self-calibration to complete. - -Library written by Nathan Seidle ([SparkFun](http://www.sparkfun.com)). - -Thanks to! - -* [jobr97](https://github.com/jobr97) for adding the getTemperatureOffset() method -* [bobobo1618](https://github.com/bobobo1618) for writing a CRC check and improving the return values of the library -* [labeneator](https://github.com/labeneator) for adding method to disable calibrate at begin -* [AndreasExner](https://github.com/AndreasExner) for adding [reset and getAutoSelfCalibration methods](https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library/pull/17) -* [awatterott](https://github.com/awatterott) for adding [getAltitudeCompensation()](https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library/pull/18) -* [jogi-k](https://github.com/jogi-k) for adding [teensy i2clib](https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library/pull/19) support -* [paulvha](https://github.com/paulvha) for the suggestions and corrections in [his version of the library](https://github.com/paulvha/scd30) -* [yamamaya](https://github.com/yamamaya) for the [3ms delay](https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library/pull/24) - -Repository Contents -------------------- - -* **/examples** - Example sketches for the library (.ino). Run these from the Arduino IDE. -* **/src** - Source files for the library (.cpp, .h). -* **keywords.txt** - Keywords from this library that will be highlighted in the Arduino IDE. -* **library.properties** - General library properties for the Arduino package manager. - -Documentation --------------- - -* **[Installing an Arduino Library Guide](https://learn.sparkfun.com/tutorials/installing-an-arduino-library)** - Basic information on how to install an Arduino library. - -License Information -------------------- - -This product is _**open source**_! - -Please use, reuse, and modify these files as you see fit. Please maintain attribution to SparkFun Electronics and release anything derivative under the same license. - -Distributed as-is; no warranty is given. - -- Your friends at SparkFun. diff --git a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/documents/Sensirion_CO2_Sensors_SCD30_Preliminary-Datasheet.pdf b/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/documents/Sensirion_CO2_Sensors_SCD30_Preliminary-Datasheet.pdf deleted file mode 100644 index 588043f0b1b066fb30272a225b2ff8ef544aa401..0000000000000000000000000000000000000000 Binary files a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/documents/Sensirion_CO2_Sensors_SCD30_Preliminary-Datasheet.pdf and /dev/null differ diff --git a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/keywords.txt b/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/keywords.txt deleted file mode 100644 index e1a66d76d114097d56bcaa2596420b5e835c272b..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/keywords.txt +++ /dev/null @@ -1,67 +0,0 @@ -####################################### -# Syntax Coloring Map -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -SCD30 KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -SCD30 KEYWORD2 -begin KEYWORD2 -isConnected KEYWORD2 -enableDebugging KEYWORD2 -beginMeasuring KEYWORD2 -StopMeasurement KEYWORD2 - -setAmbientPressure KEYWORD2 - -getSettingValue KEYWORD2 -getFirmwareVersion KEYWORD2 -getCO2 KEYWORD2 -getHumidity KEYWORD2 -getTemperature KEYWORD2 - -getMeasurementInterval KEYWORD2 -setMeasurementInterval KEYWORD2 - -getAltitudeCompensation KEYWORD2 -setAltitudeCompensation KEYWORD2 - -getAutoSelfCalibration KEYWORD2 -setAutoSelfCalibration KEYWORD2 - -getForcedRecalibration KEYWORD2 -setForcedRecalibrationFactor KEYWORD2 - -getTemperatureOffset KEYWORD2 -setTemperatureOffset KEYWORD2 - -dataAvailable KEYWORD2 -readMeasurement KEYWORD2 -reset KEYWORD2 -sendCommand KEYWORD2 -readRegister KEYWORD2 -computeCRC8 KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - -SCD30_ADDRESS LITERAL1 -COMMAND_CONTINUOUS_MEASUREMENT LITERAL1 -COMMAND_SET_MEASUREMENT_INTERVAL LITERAL1 -COMMAND_GET_DATA_READY LITERAL1 -COMMAND_READ_MEASUREMENT LITERAL1 -COMMAND_AUTOMATIC_SELF_CALIBRATION LITERAL1 -COMMAND_SET_FORCED_RECALIBRATION_FACTOR LITERAL1 -COMMAND_SET_TEMPERATURE_OFFSET LITERAL1 -COMMAND_SET_ALTITUDE_COMPENSATION LITERAL1 -COMMAND_RESET LITERAL1 -COMMAND_STOP_MEAS LITERAL1 -COMMAND_READ_FW_VER LITERAL1 diff --git a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/library.properties b/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/library.properties deleted file mode 100644 index be9ed522d96ab108cbb62a52e4544098f5ea7a39..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=SparkFun SCD30 Arduino Library -version=1.0.17 -author=SparkFun Electronics -maintainer=SparkFun Electronics -sentence=Library for the Sensirion SCD30 CO2 Sensor -paragraph=An Arduinolibrary for the SCD30 CO2 sensor from Sensirion. The SCD30 is a high quality NDIR based CO₂ sensor capable of detecting 400 to 10000ppm with an accuracy of ±(30ppm+3%). In order to improve accuracy the SCD30 has temperature and humidity sensing built-in, as well as commands to set the current altitude.

Get the SCD30 here. -category=Sensors -url=https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library -architectures=* diff --git a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.cpp b/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.cpp deleted file mode 100644 index f83746fb0fd1c4c6606d36289f2b0d5b22122b49..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.cpp +++ /dev/null @@ -1,501 +0,0 @@ -/* - This is a library written for the SCD30 - SparkFun sells these at its website: www.sparkfun.com - Do you like this library? Help support SparkFun. Buy a board! - https://www.sparkfun.com/products/14751 - - Written by Nathan Seidle @ SparkFun Electronics, May 22nd, 2018 - - Updated February 1st 2021 to include some of the features of paulvha's version of the library - (while maintaining backward-compatibility): - https://github.com/paulvha/scd30 - Thank you Paul! - - The SCD30 measures CO2 with accuracy of +/- 30ppm. - - This library handles the initialization of the SCD30 and outputs - CO2 levels, relative humidty, and temperature. - - https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library - - Development environment specifics: - Arduino IDE 1.8.13 - - SparkFun code, firmware, and software is released under the MIT License. - Please see LICENSE.md for more details. -*/ - -#include "SparkFun_SCD30_Arduino_Library.h" - -SCD30::SCD30(void) -{ - // Constructor -} - -// Initialize the Serial port -#ifdef USE_TEENSY3_I2C_LIB -bool SCD30::begin(i2c_t3 &wirePort, bool autoCalibrate, bool measBegin) -#else -bool SCD30::begin(TwoWire &wirePort, bool autoCalibrate, bool measBegin) -#endif -{ - _i2cPort = &wirePort; // Grab which port the user wants us to use - - /* Especially during obtaining the ACK BIT after a byte sent the SCD30 is using clock stretching (but NOT only there)! - * The need for clock stretching is described in the Sensirion_CO2_Sensors_SCD30_Interface_Description.pdf - * - * The default clock stretch (maximum wait time) on the ESP8266-library (2.4.2) is 230us which is set during _i2cPort->begin(); - * In the current implementation of the ESP8266 I2C driver there is NO error message when this time expired, while - * the clock stretch is still happening, causing uncontrolled behaviour of the hardware combination. - * - * To set ClockStretchlimit() a check for ESP8266 boards has been added in the driver. - * - * With setting to 20000, we set a max timeout of 20mS (> 20x the maximum measured) basically disabling the time-out - * and now wait for clock stretch to be controlled by the client. - */ - -#if defined(ARDUINO_ARCH_ESP8266) - _i2cPort->setClockStretchLimit(200000); -#endif - - if (isConnected() == false) - return (false); - - if (measBegin == false) // Exit now if measBegin is false - return (true); - - // Check for device to respond correctly - if (beginMeasuring() == true) // Start continuous measurements - { - setMeasurementInterval(2); // 2 seconds between measurements - setAutoSelfCalibration(autoCalibrate); // Enable auto-self-calibration - - return (true); - } - - return (false); // Something went wrong -} - -// Returns true if device responds to a firmware request -bool SCD30::isConnected() -{ - uint16_t fwVer; - if (getFirmwareVersion(&fwVer) == false) // Read the firmware version. Return false if the CRC check fails. - return (false); - - if (_printDebug == true) - { - _debugPort->print(F("Firmware version 0x")); - _debugPort->println(fwVer, HEX); - } - - return (true); -} - -// Calling this function with nothing sets the debug port to Serial -// You can also call it with other streams like Serial1, SerialUSB, etc. -void SCD30::enableDebugging(Stream &debugPort) -{ - _debugPort = &debugPort; - _printDebug = true; -} - -// Returns the latest available CO2 level -// If the current level has already been reported, trigger a new read -uint16_t SCD30::getCO2(void) -{ - if (co2HasBeenReported == true) // Trigger a new read - { - if (readMeasurement() == false) // Pull in new co2, humidity, and temp into global vars - co2 = 0; // Failed to read sensor - } - - co2HasBeenReported = true; - - return (uint16_t)co2; // Cut off decimal as co2 is 0 to 10,000 -} - -// Returns the latest available humidity -// If the current level has already been reported, trigger a new read -float SCD30::getHumidity(void) -{ - if (humidityHasBeenReported == true) // Trigger a new read - if (readMeasurement() == false) // Pull in new co2, humidity, and temp into global vars - humidity = 0; // Failed to read sensor - - humidityHasBeenReported = true; - - return humidity; -} - -// Returns the latest available temperature -// If the current level has already been reported, trigger a new read -float SCD30::getTemperature(void) -{ - if (temperatureHasBeenReported == true) // Trigger a new read - if (readMeasurement() == false) // Pull in new co2, humidity, and temp into global vars - temperature = 0; // Failed to read sensor - - temperatureHasBeenReported = true; - - return temperature; -} - -// Enables or disables the ASC -bool SCD30::setAutoSelfCalibration(bool enable) -{ - if (enable) - return sendCommand(COMMAND_AUTOMATIC_SELF_CALIBRATION, 1); // Activate continuous ASC - else - return sendCommand(COMMAND_AUTOMATIC_SELF_CALIBRATION, 0); // Deactivate continuous ASC -} - -// Set the forced recalibration factor. See 1.3.7. -// The reference CO2 concentration has to be within the range 400 ppm ≤ cref(CO2) ≤ 2000 ppm. -bool SCD30::setForcedRecalibrationFactor(uint16_t concentration) -{ - if (concentration < 400 || concentration > 2000) - { - return false; // Error check. - } - return sendCommand(COMMAND_SET_FORCED_RECALIBRATION_FACTOR, concentration); -} - -// Get the temperature offset. See 1.3.8. -float SCD30::getTemperatureOffset(void) -{ - uint16_t response = readRegister(COMMAND_SET_TEMPERATURE_OFFSET); - - union - { - int16_t signed16; - uint16_t unsigned16; - } signedUnsigned; // Avoid any ambiguity casting int16_t to uint16_t - signedUnsigned.signed16 = response; - - return (((float)signedUnsigned.signed16) / 100.0); -} - -// Set the temperature offset to remove module heating from temp reading -bool SCD30::setTemperatureOffset(float tempOffset) -{ - // Temp offset is only positive. See: https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library/issues/27#issuecomment-971986826 - //"The SCD30 offset temperature is obtained by subtracting the reference temperature from the SCD30 output temperature" - // https://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/9.5_CO2/Sensirion_CO2_Sensors_SCD30_Low_Power_Mode.pdf - - if (tempOffset < 0.0) - return (false); - - uint16_t value = tempOffset * 100; - - return sendCommand(COMMAND_SET_TEMPERATURE_OFFSET, value); -} - -// Get the altitude compenstation. See 1.3.9. -uint16_t SCD30::getAltitudeCompensation(void) -{ - return readRegister(COMMAND_SET_ALTITUDE_COMPENSATION); -} - -// Set the altitude compenstation. See 1.3.9. -bool SCD30::setAltitudeCompensation(uint16_t altitude) -{ - return sendCommand(COMMAND_SET_ALTITUDE_COMPENSATION, altitude); -} - -// Set the pressure compenstation. This is passed during measurement startup. -// mbar can be 700 to 1200 -bool SCD30::setAmbientPressure(uint16_t pressure_mbar) -{ - if (pressure_mbar < 700 || pressure_mbar > 1200) - { - return false; - } - return sendCommand(COMMAND_CONTINUOUS_MEASUREMENT, pressure_mbar); -} - -// SCD30 soft reset -void SCD30::reset() -{ - sendCommand(COMMAND_RESET); -} - -// Get the current ASC setting -bool SCD30::getAutoSelfCalibration() -{ - uint16_t response = readRegister(COMMAND_AUTOMATIC_SELF_CALIBRATION); - if (response == 1) - { - return true; - } - else - { - return false; - } -} - -// Begins continuous measurements -// Continuous measurement status is saved in non-volatile memory. When the sensor -// is powered down while continuous measurement mode is active SCD30 will measure -// continuously after repowering without sending the measurement command. -// Returns true if successful -bool SCD30::beginMeasuring(uint16_t pressureOffset) -{ - return (sendCommand(COMMAND_CONTINUOUS_MEASUREMENT, pressureOffset)); -} - -// Overload - no pressureOffset -bool SCD30::beginMeasuring(void) -{ - return (beginMeasuring(0)); -} - -// Stop continuous measurement -bool SCD30::StopMeasurement(void) -{ - return (sendCommand(COMMAND_STOP_MEAS)); -} - -// Sets interval between measurements -// 2 seconds to 1800 seconds (30 minutes) -bool SCD30::setMeasurementInterval(uint16_t interval) -{ - return sendCommand(COMMAND_SET_MEASUREMENT_INTERVAL, interval); -} - -// Gets interval between measurements -// 2 seconds to 1800 seconds (30 minutes) -uint16_t SCD30::getMeasurementInterval(void) -{ - uint16_t interval = 0; - getSettingValue(COMMAND_SET_MEASUREMENT_INTERVAL, &interval); - return (interval); -} - -// Returns true when data is available -bool SCD30::dataAvailable() -{ - uint16_t response = readRegister(COMMAND_GET_DATA_READY); - - if (response == 1) - return (true); - return (false); -} - -// Get 18 bytes from SCD30 -// Updates global variables with floats -// Returns true if success -bool SCD30::readMeasurement() -{ - // Verify we have data from the sensor - if (dataAvailable() == false) - return (false); - - ByteToFl tempCO2; - tempCO2.value = 0; - ByteToFl tempHumidity; - tempHumidity.value = 0; - ByteToFl tempTemperature; - tempTemperature.value = 0; - - _i2cPort->beginTransmission(SCD30_ADDRESS); - _i2cPort->write(COMMAND_READ_MEASUREMENT >> 8); // MSB - _i2cPort->write(COMMAND_READ_MEASUREMENT & 0xFF); // LSB - if (_i2cPort->endTransmission() != 0) - return (0); // Sensor did not ACK - - delay(3); - - const uint8_t receivedBytes = _i2cPort->requestFrom((uint8_t)SCD30_ADDRESS, (uint8_t)18); - bool error = false; - if (_i2cPort->available()) - { - byte bytesToCrc[2]; - for (byte x = 0; x < 18; x++) - { - byte incoming = _i2cPort->read(); - - switch (x) - { - case 0: - case 1: - case 3: - case 4: - tempCO2.array[x < 3 ? 3 - x : 4 - x] = incoming; - bytesToCrc[x % 3] = incoming; - break; - case 6: - case 7: - case 9: - case 10: - tempTemperature.array[x < 9 ? 9 - x : 10 - x] = incoming; - bytesToCrc[x % 3] = incoming; - break; - case 12: - case 13: - case 15: - case 16: - tempHumidity.array[x < 15 ? 15 - x : 16 - x] = incoming; - bytesToCrc[x % 3] = incoming; - break; - default: - // Validate CRC - uint8_t foundCrc = computeCRC8(bytesToCrc, 2); - if (foundCrc != incoming) - { - if (_printDebug == true) - { - _debugPort->print(F("readMeasurement: found CRC in byte ")); - _debugPort->print(x); - _debugPort->print(F(", expected 0x")); - _debugPort->print(foundCrc, HEX); - _debugPort->print(F(", got 0x")); - _debugPort->println(incoming, HEX); - } - error = true; - } - break; - } - } - } - else - { - if (_printDebug == true) - { - _debugPort->print(F("readMeasurement: no SCD30 data found from I2C, i2c claims we should receive ")); - _debugPort->print(receivedBytes); - _debugPort->println(F(" bytes")); - } - return false; - } - - if (error) - { - if (_printDebug == true) - _debugPort->println(F("readMeasurement: encountered error reading SCD30 data.")); - return false; - } - // Now copy the uint32s into their associated floats - co2 = tempCO2.value; - temperature = tempTemperature.value; - humidity = tempHumidity.value; - - // Mark our global variables as fresh - co2HasBeenReported = false; - humidityHasBeenReported = false; - temperatureHasBeenReported = false; - - return (true); // Success! New data available in globals. -} - -// Gets a setting by reading the appropriate register. -// Returns true if the CRC is valid. -bool SCD30::getSettingValue(uint16_t registerAddress, uint16_t *val) -{ - _i2cPort->beginTransmission(SCD30_ADDRESS); - _i2cPort->write(registerAddress >> 8); // MSB - _i2cPort->write(registerAddress & 0xFF); // LSB - if (_i2cPort->endTransmission() != 0) - return (false); // Sensor did not ACK - - delay(3); - - _i2cPort->requestFrom((uint8_t)SCD30_ADDRESS, (uint8_t)3); // Request data and CRC - if (_i2cPort->available()) - { - uint8_t data[2]; - data[0] = _i2cPort->read(); - data[1] = _i2cPort->read(); - uint8_t crc = _i2cPort->read(); - *val = (uint16_t)data[0] << 8 | data[1]; - uint8_t expectedCRC = computeCRC8(data, 2); - if (crc == expectedCRC) // Return true if CRC check is OK - return (true); - if (_printDebug == true) - { - _debugPort->print(F("getSettingValue: CRC fail: expected 0x")); - _debugPort->print(expectedCRC, HEX); - _debugPort->print(F(", got 0x")); - _debugPort->println(crc, HEX); - } - } - return (false); -} - -// Gets two bytes from SCD30 -uint16_t SCD30::readRegister(uint16_t registerAddress) -{ - _i2cPort->beginTransmission(SCD30_ADDRESS); - _i2cPort->write(registerAddress >> 8); // MSB - _i2cPort->write(registerAddress & 0xFF); // LSB - if (_i2cPort->endTransmission() != 0) - return (0); // Sensor did not ACK - - delay(3); - - _i2cPort->requestFrom((uint8_t)SCD30_ADDRESS, (uint8_t)2); - if (_i2cPort->available()) - { - uint8_t msb = _i2cPort->read(); - uint8_t lsb = _i2cPort->read(); - return ((uint16_t)msb << 8 | lsb); - } - return (0); // Sensor did not respond -} - -// Sends a command along with arguments and CRC -bool SCD30::sendCommand(uint16_t command, uint16_t arguments) -{ - uint8_t data[2]; - data[0] = arguments >> 8; - data[1] = arguments & 0xFF; - uint8_t crc = computeCRC8(data, 2); // Calc CRC on the arguments only, not the command - - _i2cPort->beginTransmission(SCD30_ADDRESS); - _i2cPort->write(command >> 8); // MSB - _i2cPort->write(command & 0xFF); // LSB - _i2cPort->write(arguments >> 8); // MSB - _i2cPort->write(arguments & 0xFF); // LSB - _i2cPort->write(crc); - if (_i2cPort->endTransmission() != 0) - return (false); // Sensor did not ACK - - return (true); -} - -// Sends just a command, no arguments, no CRC -bool SCD30::sendCommand(uint16_t command) -{ - _i2cPort->beginTransmission(SCD30_ADDRESS); - _i2cPort->write(command >> 8); // MSB - _i2cPort->write(command & 0xFF); // LSB - if (_i2cPort->endTransmission() != 0) - return (false); // Sensor did not ACK - - return (true); -} - -// Given an array and a number of bytes, this calculate CRC8 for those bytes -// CRC is only calc'd on the data portion (two bytes) of the four bytes being sent -// From: http://www.sunshine2k.de/articles/coding/crc/understanding_crc.html -// Tested with: http://www.sunshine2k.de/coding/javascript/crc/crc_js.html -// x^8+x^5+x^4+1 = 0x31 -uint8_t SCD30::computeCRC8(uint8_t data[], uint8_t len) -{ - uint8_t crc = 0xFF; // Init with 0xFF - - for (uint8_t x = 0; x < len; x++) - { - crc ^= data[x]; // XOR-in the next input byte - - for (uint8_t i = 0; i < 8; i++) - { - if ((crc & 0x80) != 0) - crc = (uint8_t)((crc << 1) ^ 0x31); - else - crc <<= 1; - } - } - - return crc; // No output reflection -} diff --git a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.h b/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.h deleted file mode 100644 index c5e7d25e5a49be8c7b676c507bae6a587f545c5d..0000000000000000000000000000000000000000 --- a/ampel-firmware/src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.h +++ /dev/null @@ -1,145 +0,0 @@ -/* - This is a library written for the SCD30 - SparkFun sells these at its website: www.sparkfun.com - Do you like this library? Help support SparkFun. Buy a board! - https://www.sparkfun.com/products/14751 - - Written by Nathan Seidle @ SparkFun Electronics, May 22nd, 2018 - - Updated February 1st 2021 to include some of the features of paulvha's version of the library - (while maintaining backward-compatibility): - https://github.com/paulvha/scd30 - Thank you Paul! - - The SCD30 measures CO2 with accuracy of +/- 30ppm. - - This library handles the initialization of the SCD30 and outputs - CO2 levels, relative humidty, and temperature. - - https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library - - Development environment specifics: - Arduino IDE 1.8.13 - - SparkFun code, firmware, and software is released under the MIT License. - Please see LICENSE.md for more details. -*/ - -#ifndef __SparkFun_SCD30_ARDUINO_LIBARARY_H__ -#define __SparkFun_SCD30_ARDUINO_LIBARARY_H__ - -// Uncomment the next #define if using an Teensy >= 3 or Teensy LC and want to use the dedicated I2C-Library for it -// Then you also have to include on your application instead of - -// #define USE_TEENSY3_I2C_LIB - -#include "Arduino.h" -#ifdef USE_TEENSY3_I2C_LIB -#include -#else -#include -#endif - -// The default I2C address for the SCD30 is 0x61. -#define SCD30_ADDRESS 0x61 - -// Available commands - -#define COMMAND_CONTINUOUS_MEASUREMENT 0x0010 -#define COMMAND_SET_MEASUREMENT_INTERVAL 0x4600 -#define COMMAND_GET_DATA_READY 0x0202 -#define COMMAND_READ_MEASUREMENT 0x0300 -#define COMMAND_AUTOMATIC_SELF_CALIBRATION 0x5306 -#define COMMAND_SET_FORCED_RECALIBRATION_FACTOR 0x5204 -#define COMMAND_SET_TEMPERATURE_OFFSET 0x5403 -#define COMMAND_SET_ALTITUDE_COMPENSATION 0x5102 -#define COMMAND_RESET 0xD304 // Soft reset -#define COMMAND_STOP_MEAS 0x0104 -#define COMMAND_READ_FW_VER 0xD100 - -typedef union -{ - byte array[4]; - float value; -} ByteToFl; // paulvha - -class SCD30 -{ -public: - SCD30(void); - - bool begin(bool autoCalibrate) { return begin(Wire, autoCalibrate); } -#ifdef USE_TEENSY3_I2C_LIB - bool begin(i2c_t3 &wirePort = Wire, bool autoCalibrate = false, bool measBegin = true); // By default use Wire port -#else - bool begin(TwoWire &wirePort = Wire, bool autoCalibrate = false, bool measBegin = true); // By default use Wire port -#endif - - bool isConnected(); - void enableDebugging(Stream &debugPort = Serial); // Turn on debug printing. If user doesn't specify then Serial will be used. - - bool beginMeasuring(uint16_t pressureOffset); - bool beginMeasuring(void); - bool StopMeasurement(void); // paulvha - - bool setAmbientPressure(uint16_t pressure_mbar); - - bool getSettingValue(uint16_t registerAddress, uint16_t *val); - bool getFirmwareVersion(uint16_t *val) { return (getSettingValue(COMMAND_READ_FW_VER, val)); } - uint16_t getCO2(void); - float getHumidity(void); - float getTemperature(void); - - uint16_t getMeasurementInterval(void); - bool getMeasurementInterval(uint16_t *val) { return (getSettingValue(COMMAND_SET_MEASUREMENT_INTERVAL, val)); } - bool setMeasurementInterval(uint16_t interval); - - uint16_t getAltitudeCompensation(void); - bool getAltitudeCompensation(uint16_t *val) { return (getSettingValue(COMMAND_SET_ALTITUDE_COMPENSATION, val)); } - bool setAltitudeCompensation(uint16_t altitude); - - bool getAutoSelfCalibration(void); - bool setAutoSelfCalibration(bool enable); - - bool getForcedRecalibration(uint16_t *val) { return (getSettingValue(COMMAND_SET_FORCED_RECALIBRATION_FACTOR, val)); } - bool setForcedRecalibrationFactor(uint16_t concentration); - - float getTemperatureOffset(void); - bool getTemperatureOffset(uint16_t *val) { return (getSettingValue(COMMAND_SET_TEMPERATURE_OFFSET, val)); } - bool setTemperatureOffset(float tempOffset); - - bool dataAvailable(); - bool readMeasurement(); - - void reset(); - - bool sendCommand(uint16_t command, uint16_t arguments); - bool sendCommand(uint16_t command); - - uint16_t readRegister(uint16_t registerAddress); - - uint8_t computeCRC8(uint8_t data[], uint8_t len); - -private: - // Variables -#ifdef USE_TEENSY3_I2C_LIB - i2c_t3 *_i2cPort; // The generic connection to user's chosen I2C hardware -#else - TwoWire *_i2cPort; // The generic connection to user's chosen I2C hardware -#endif - // Global main datums - float co2 = 0; - float temperature = 0; - float humidity = 0; - - // These track the staleness of the current data - // This allows us to avoid calling readMeasurement() every time individual datums are requested - bool co2HasBeenReported = true; - bool humidityHasBeenReported = true; - bool temperatureHasBeenReported = true; - - // Debug - Stream *_debugPort; // The stream to send debug messages to if enabled. Usually Serial. - boolean _printDebug = false; // Flag to print debugging variables -}; -#endif diff --git a/ampel-firmware/web_server.cpp b/ampel-firmware/web_server.cpp deleted file mode 100644 index 07901a845afce1bcf31601918f08227b5b610d09..0000000000000000000000000000000000000000 --- a/ampel-firmware/web_server.cpp +++ /dev/null @@ -1,274 +0,0 @@ -#include "web_server.h" - -#include "web_config.h" -#include "util.h" -#include "ntp.h" -#include "wifi_util.h" -#include "co2_sensor.h" -#include "sensor_console.h" -#include "csv_writer.h" -#include "mqtt.h" -#include "lorawan.h" - -#if defined(ESP8266) -# include -#elif defined(ESP32) -# include -#endif - -namespace web_server { - - const char *header_template; - const char *body1_template; - const char *body2_template; - const char *script_template; - void handleWebServerRoot(); - void handlePageNotFound(); - void handleWebServerCommand(); - - void handleDeleteCSV(); - void handleWebServerCSV(); - - const __FlashStringHelper* showHTMLIf(bool is_active) { - return is_active ? F("") : F("hidden"); - } - - const __FlashStringHelper* yesOrNo(bool is_active) { - return is_active ? F("Yes") : F("No"); - } - - void definePages() { - header_template = - PSTR("" - "" - "%d ppm - CO2 SENSOR - %s - %s" - "" - // HfT Favicon - "" - // Responsive grid: - "" - "" - // JS Graphs: - "" - // Fullscreen - "" - // Refresh after every measurement. - // "" - "" - "" - "

HfT-Stuttgart CO2 Ampel

" - "
" "" "
" "
"// Graph placeholder - "
" "
" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" -#if defined(ESP32) - "" - "" - "" - "" - "" - "" - "" -#endif - ); - - body2_template = - PSTR( - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "
%s
CO2%5d ppm
Temperature%.1f℃
Humidity%.1f%%
Last measurement%s
Timestep%5d s
CSV
Last write%s
Interval%5d s
Available space%d kB
MQTT
Connected?%s
Last publish%s
Interval%5d s
LoRaWAN
Connected?%s
Frequency%s MHz
Last transmission%s
Interval%5d s
Sensor
Temperature offset%.1fK
Auto-calibration?%s
Local address%s.local
Local IP%s
MAC%s
Free heap space%6d bytes
Largest heap block%6d bytes
Frag%3d%%
Max loop duration%5d ms
Board%s
ID%s
Ampel firmware%s
Uptime%2d d %4d h %02d min %02d s
" - "
" - "
" - "
" - "" - "
" - "" // Can be useful in AP mode - "
" - "Source code " - "Documentation" - "" - "" - ""); - - // Web-server - web_config::http.on("/", handleWebServerRoot); - web_config::http.on("/command", handleWebServerCommand); - web_config::http.on(csv_writer::filename, handleWebServerCSV); - web_config::http.on("/delete_csv", HTTP_POST, handleDeleteCSV); - } - - /* - * Allow access if Ampel is in access point mode, - * if http_user or http_password are empty, - * or if provided credentials match - */ - bool shouldBeAllowed() { - return wifi::isAccessPoint() || strcmp(config::http_user, "") == 0 || strcmp(config::ampel_password(), "") == 0 - || web_config::http.authenticate(config::http_user, config::ampel_password()); - } - - void handleWebServerRoot() { - unsigned long ss = seconds(); - uint8_t dd = ss / 86400; - ss -= dd * 86400; - unsigned int hh = ss / 3600; - ss -= hh * 3600; - uint8_t mm = ss / 60; - ss -= mm * 60; - - //NOTE: Splitting in multiple parts in order to use less RAM. Higher than 2000 apparently crashes the ESP8266 - char content[1600]; - // Current size (with Lorawan, timesteps and long thing name): - // INFO - Header size : 1347 - Body1 size : 1448 - Body2 size : 1475 - Script size : 1507 - - snprintf_P(content, sizeof(content), header_template, sensor::co2, config::ampel_name(), wifi::local_ip); - - Serial.print(F("INFO - Header size : ")); - Serial.print(strlen(content)); - web_config::http.setContentLength(CONTENT_LENGTH_UNKNOWN); - web_config::http.send_P(200, PSTR("text/html"), content); - - // Body - snprintf_P(content, sizeof(content), body1_template, csv_writer::filename, config::ampel_name(), sensor::co2, - sensor::temperature, sensor::humidity, sensor::timestamp, config::measurement_timestep, - showHTMLIf(config::is_csv_active()), csv_writer::last_successful_write, config::csv_interval, - csv_writer::getAvailableSpace() / 1024, showHTMLIf(config::is_mqtt_active()), yesOrNo(mqtt::connected), - mqtt::last_successful_publish, config::mqtt_sending_interval -#if defined(ESP32) - , showHTMLIf(config::is_lorawan_active()), yesOrNo(lorawan::connected), - config::lorawan_frequency_plan, lorawan::last_transmission, config::lorawan_sending_interval -#endif - ); - - Serial.print(F(" - Body1 size : ")); - Serial.print(strlen(content)); - web_config::http.sendContent(content); - - snprintf_P(content, sizeof(content), body2_template, sensor::getTemperatureOffset(), - yesOrNo(config::auto_calibrate_sensor), config::ampel_name(), config::ampel_name(), wifi::local_ip, - wifi::local_ip, ampel.macAddress, ESP.getFreeHeap(), esp_get_max_free_block_size(), - esp_get_heap_fragmentation(), ampel.max_loop_duration, ampel.board, ampel.sensorId, ampel.version, dd, hh, mm, - ss, showHTMLIf(!ntp::connected_at_least_once)); - - Serial.print(F(" - Body2 size : ")); - Serial.print(strlen(content)); - web_config::http.sendContent(content); - - // Script - snprintf_P(content, sizeof(content), script_template, csv_writer::filename, config::ampel_name()); - - Serial.print(F(" - Script size : ")); - Serial.println(strlen(content)); - web_config::http.sendContent(content); - } - - void handleWebServerCSV() { - if (FS_LIB.exists(csv_writer::filename)) { - fs::File csv_file = FS_LIB.open(csv_writer::filename, "r"); - char csv_size[10]; - snprintf(csv_size, sizeof(csv_size), "%d", csv_file.size()); - web_config::http.sendHeader("Content-Length", csv_size); - web_config::http.streamFile(csv_file, F("text/csv")); - csv_file.close(); - } else { - web_config::http.send(204, F("text/html"), F("No data available.")); - } - } - - void handleDeleteCSV() { - if (!shouldBeAllowed()) { - return web_config::http.requestAuthentication(DIGEST_AUTH); - } - Serial.print(F("Removing CSV file...")); - FS_LIB.remove(csv_writer::filename); - Serial.println(F(" Done!")); - web_config::http.sendHeader("Location", "/"); - web_config::http.send(303); - } - - void handleWebServerCommand() { - if (!shouldBeAllowed()) { - return web_config::http.requestAuthentication(DIGEST_AUTH); - } - web_config::http.sendHeader("Location", "/"); - web_config::http.send(303); - sensor_console::execute(web_config::http.arg("send").c_str()); - } - - void handlePageNotFound() { - web_config::http.send(404, F("text/plain"), F("404: Not found")); - } -} diff --git a/ampel-firmware/web_server.h b/ampel-firmware/web_server.h deleted file mode 100644 index df6df91377842e84532775eff8892cd90995e837..0000000000000000000000000000000000000000 --- a/ampel-firmware/web_server.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef WEB_SERVER_H_ -#define WEB_SERVER_H_ - -namespace web_server { - void definePages(); -} -#endif diff --git a/ampel-firmware/wifi_util.cpp b/ampel-firmware/wifi_util.cpp deleted file mode 100644 index 795eeeb9a826f1745e2df9268ce4c5ddc54625ca..0000000000000000000000000000000000000000 --- a/ampel-firmware/wifi_util.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#include "wifi_util.h" - -#include "web_config.h" -#include "util.h" -#include "ntp.h" -#include "led_effects.h" -#include "sensor_console.h" - -#if defined(ESP8266) -# include -#elif defined(ESP32) -# include -#endif - -namespace wifi { - char local_ip[16]; // "255.255.255.255\0" - - bool connected() { - return WiFi.status() == WL_CONNECTED; - } - - bool isAccessPoint() { - return WiFi.getMode() == WIFI_AP; - } - - /* - * Connection attempt, called in blocking mode by setup(). This way, LED effects can be shown - * without needing callbacks, but only during wifi_timeout seconds. - * If connection fails, access point will be started indefinitely, and corresponding - * LED effects will be shown during 5 seconds. - * - * Afterwards, the non-blocking web_config::update() will be called inside loop, and the ampel - * can display CO2 levels. - */ - void tryConnection() { - for (int i = 0; i <= config::wifi_timeout + 5; i++) { - web_config::update(); - sensor_console::checkSerialInput(); // To allow reset or ssid ... during startup - if (isAccessPoint()) { - led_effects::alert(0x1cff68); - } else if (connected()) { - break; - } else { - led_effects::showRainbowWheel(); - } - Serial.print("."); - } - Serial.println(); - } - - void scanNetworks() { - Serial.println(); - Serial.println(F("WiFi - Scanning...")); - bool async = false; - bool showHidden = true; - int n = WiFi.scanNetworks(async, showHidden); - for (int i = 0; i < n; ++i) { - Serial.print(F(" * '")); - Serial.print(WiFi.SSID(i)); - Serial.print(F("' (")); - int16_t quality = 2 * (100 + WiFi.RSSI(i)); - Serial.print(util::min(util::max(quality, 0), 100)); - Serial.println(F(" %)")); - } - Serial.println(F("Done!")); - Serial.println(); - } - - void showLocalIp() { - Serial.print(F("WiFi - Local IP : ")); - Serial.println(wifi::local_ip); - Serial.print(F("WiFi - SSID : ")); - Serial.println(config::selected_ssid()); - } - - void defineCommands() { - sensor_console::defineCommand("wifi_scan", scanNetworks, F("(Scans available WiFi networks)")); - sensor_console::defineCommand("local_ip", showLocalIp, F("(Displays local IP and current SSID)")); - //TODO: Add "update!" command? https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino - } -} diff --git a/ampel-firmware/wifi_util.h b/ampel-firmware/wifi_util.h deleted file mode 100644 index 67323687b7a25926800eb85edade77fa841b470c..0000000000000000000000000000000000000000 --- a/ampel-firmware/wifi_util.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef WIFI_UTIL_H_INCLUDED -#define WIFI_UTIL_H_INCLUDED - -namespace wifi { - extern char local_ip[16]; - void defineCommands(); - bool connected(); - bool isAccessPoint(); - void tryConnection(); -} - -#endif