diff --git a/firmware/libraries/APDS9930-master/.gitattributes b/firmware/libraries/APDS9930-master/.gitattributes new file mode 100755 index 0000000..412eeda --- /dev/null +++ b/firmware/libraries/APDS9930-master/.gitattributes @@ -0,0 +1,22 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/firmware/libraries/APDS9930-master/.gitignore b/firmware/libraries/APDS9930-master/.gitignore new file mode 100755 index 0000000..2778edb --- /dev/null +++ b/firmware/libraries/APDS9930-master/.gitignore @@ -0,0 +1,192 @@ +################# +## SparkFun Useful stuff +################# + +## AVR Development +*.eep +*.elf +*.lst +*.lss +*.sym +*.d +*.o +*.srec +*.map + +## Notepad++ backup files +*.bak + +## BOM files +*bom* + +################# +## Eclipse +################# + +*.pydevproject +.project +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + + +############# +## Eagle +############# + +# Ignore the board and schematic backup files +*.b#? +*.s#? + + +################# +## Visual Studio +################# + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results +[Dd]ebug/ +[Rr]elease/ +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.vspscc +.builds +*.dotCover + +## TODO: If you have NuGet Package Restore enabled, uncomment this +#packages/ + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf + +# Visual Studio profiler +*.psess +*.vsp + +# ReSharper is a .NET coding add-in +_ReSharper* + +# Installshield output folder +[Ee]xpress + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish + +# Others +[Bb]in +[Oo]bj +sql +TestResults +*.Cache +ClientBin +stylecop.* +~$* +*.dbmdl +Generated_Code #added for RIA/Silverlight projects + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML + + +############ +## Windows +############ + +# Windows image file caches +Thumbs.db + +# Folder config file +Desktop.ini + + +############# +## Python +############# + +*.py[co] + +# Packages +*.egg +*.egg-info +dist +build +eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg + +# Mac crap +.DS_Store diff --git a/firmware/libraries/APDS9930-master/LICENSE b/firmware/libraries/APDS9930-master/LICENSE new file mode 100755 index 0000000..9d6e5b5 --- /dev/null +++ b/firmware/libraries/APDS9930-master/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Davide Depau + +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/firmware/libraries/APDS9930-master/README.md b/firmware/libraries/APDS9930-master/README.md new file mode 100755 index 0000000..ce60370 --- /dev/null +++ b/firmware/libraries/APDS9930-master/README.md @@ -0,0 +1,92 @@ +APDS9930 Ambient Light and Proximity sensor +=========================================== + +This is a fork of the [library from Sparkfun for the APDS-9960 sensor](https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor). It has been adapted to read values from this other model. + +[**Quick-start guide available here**](https://web.archive.org/web/20151224052223/http://davideddu.org/blog/posts/apds-9930-arduino-quickstart/) + +[**Purchase an Avago APDS-9930 Breakout Board here**](http://www.dx.com/p/384037?Utm_rid=14976370&Utm_source=affiliate) + + +# DO NOT EMAIL ME IF YOU HAVE AN ISSUE +It will be deleted without reading. If you have an issue, [create an issue](https://github.com/Depau/APDS9930/issues) here on GitHub. + +# Unmaintained +I'm not going to maintain this library any more. I will merge pull requests, though. Contributions are welcome. Just don't expect anything from me. + +![Avago APDS-9930 Breakout Board](http://img.dxcdn.com/productimages/sku_384037_1.jpg) + +**Note:** even though it says APDS-9960, it's an APDS-9930. That's how I ended up getting one of those. I wanted the RGB sensor. I found this crap in my mailbox. But I decided to write a library for it anyways ;) + +Getting Started +--------------- + +* Download the Git repository as a ZIP ("Download ZIP" button) +* Unzip +* Copy the entire library directory (APDS-9930) to +\/libraries +* Open the Arduino program +* Select File -> Examples -> APDS9930 -> GestureTest +* Plug in your Arduino and APDS-9930 with the following connections + +*-OR-* + +* Use the library manager + +| Arduino Pin | APDS-9930 Board | Function | +|---|---|---| +| 3.3V | VCC | Power | +| GND | GND | Ground | +| A4 | SDA | I²C Data | +| A5 | SCL | I²C Clock | +| 2 | INT | Interrupt | + +*P.S.: you already know you can't use this purple little thing with your 5V Arduino without a level shifter, right? :) In case you don't have a level shifter, you can detach the microcontroller from an Arduino Uno, reconnect the oscillator pins, the RX and TX pins, the reset and the LED/SCK pins back to the board with some jumper wires. You can then power the microcontroller from a 3.3V source (the 3V3 output on the board should work) and connect the sensor directly to the MCU. Look up "Arduino on Breadboard".* + +* Go to Tools -> Board and select your Arduino board +* Go to Tools -> Serial Port and select the COM port of your Arduino board +* Click "Upload" +* Go to Tools -> Serial Monitor +* Ensure the baud rate is set at 9600 baud +* Swipe your hand over the sensor in various directions! + +Repository Contents +------------------- + +* **/examples** - Example sketches for the library (.ino). Run these from the Arduino IDE. +* **/extras** - Additional documentation for the user. These files are ignored by the 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 +-------------- + +* **[Quickstart Guide](https://web.archive.org/web/20151224052223/http://davideddu.org/blog/posts/apds-9930-arduino-quickstart/)** - Basic hookup guide for the sensor. +* **[Product Repository](https://github.com/Davideddu/APDS9930)** - Main repository (including hardware files) for the APDS9930 ambient light and proximity sensor. +* **[Installing an Arduino Library Guide](https://learn.sparkfun.com/tutorials/installing-an-arduino-library)** - Basic information on how to install an Arduino library. + + +Version History +--------------- +* master - Adapted for use with APDS-9930 +* [V_1.4.0](https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor_Arduino_Library/tree/V_1.4.0) - Updated to new library structure +* V_1.3.0 - Implemented disableProximitySensor(). Thanks to jmg5150 for catching that! +* V_1.2.0 - Added pinMode line to GestureTest demo to fix interrupt bug with some Arduinos +* V_1.1.0 - Updated GestureTest demo to not freeze with fast swipes +* V_1.0.0: Initial release +* Ambient and RGB light sensing implemented +* Ambient light interrupts working +* Proximity sensing implemented +* Proximity interrupts working + +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. And Davide Depau :* diff --git a/firmware/libraries/APDS9930-master/examples/AmbientLightInterrupt/AmbientLightInterrupt.ino b/firmware/libraries/APDS9930-master/examples/AmbientLightInterrupt/AmbientLightInterrupt.ino new file mode 100755 index 0000000..2c44b52 --- /dev/null +++ b/firmware/libraries/APDS9930-master/examples/AmbientLightInterrupt/AmbientLightInterrupt.ino @@ -0,0 +1,180 @@ +/**************************************************************** +AmbientLightInterrupt.ino +APDS-9930 RGB and Gesture Sensor +Shawn Hymel @ SparkFun Electronics +October 24, 2014 +https://github.com/sparkfun/APDS-9930_RGB_and_Gesture_Sensor + +Tests the ambient light interrupt abilities of the APDS-9930. +Configures the APDS-9930 over I2C and waits for an external +interrupt based on high or low light conditions. Try covering +the sensor with your hand or bringing the sensor close to a +bright light source. You might need to adjust the LIGHT_INT_HIGH +and LIGHT_INT_LOW values to get the interrupt to work correctly. + +Hardware Connections: + +IMPORTANT: The APDS-9930 can only accept 3.3V! + + Arduino Pin APDS-9930 Board Function + + 3.3V VCC Power + GND GND Ground + A4 SDA I2C Data + A5 SCL I2C Clock + 2 INT Interrupt + 13 - LED + +Resources: +Include Wire.h and APDS9930.h + +Development environment specifics: +Written in Arduino 1.0.5 +Tested with SparkFun Arduino Pro Mini 3.3V + +This code is beerware; if you see me (or any other SparkFun +employee) at the local, and you've found our code helpful, please +buy us a round! + +Distributed as-is; no warranty is given. +****************************************************************/ + +#define DUMP_REGS + +#include +#include + +// Pins +#define APDS9930_INT 2 // Needs to be an interrupt pin +#define LED_PIN 13 // LED for showing interrupt + +// Constants +#define LIGHT_INT_HIGH 1000 // High light level for interrupt +#define LIGHT_INT_LOW 10 // Low light level for interrupt + +// Global variables +APDS9930 apds = APDS9930(); +float ambient_light = 0; +uint16_t ch0 = 0; +uint16_t ch1 = 1; +volatile bool isr_flag = false; +uint16_t threshold = 0; + +void setup() { + + // Set LED as output + pinMode(LED_PIN, OUTPUT); + pinMode(APDS9930_INT, INPUT); + + // Initialize Serial port + Serial.begin(9600); + Serial.println(); + Serial.println(F("----------------------------")); + Serial.println(F("APDS-9930 - Light Interrupts")); + Serial.println(F("----------------------------")); + + // Initialize interrupt service routine + attachInterrupt(0, interruptRoutine, FALLING); + + // Initialize APDS-9930 (configure I2C and initial values) + if ( apds.init() ) { + Serial.println(F("APDS-9930 initialization complete")); + } else { + Serial.println(F("Something went wrong during APDS-9930 init!")); + } + + // Set high and low interrupt thresholds + if ( !apds.setLightIntLowThreshold(LIGHT_INT_LOW) ) { + Serial.println(F("Error writing low threshold")); + } + if ( !apds.setLightIntHighThreshold(LIGHT_INT_HIGH) ) { + Serial.println(F("Error writing high threshold")); + } + + // Start running the APDS-9930 light sensor (no interrupts) + if ( apds.enableLightSensor(false) ) { + Serial.println(F("Light sensor is now running")); + } else { + Serial.println(F("Something went wrong during light sensor init!")); + } + + // Read high and low interrupt thresholds + if ( !apds.getLightIntLowThreshold(threshold) ) { + Serial.println(F("Error reading low threshold")); + } else { + Serial.print(F("Low Threshold: ")); + Serial.println(threshold); + } + if ( !apds.getLightIntHighThreshold(threshold) ) { + Serial.println(F("Error reading high threshold")); + } else { + Serial.print(F("High Threshold: ")); + Serial.println(threshold); + } + + // Enable interrupts + if ( !apds.setAmbientLightIntEnable(1) ) { + Serial.println(F("Error enabling interrupts")); + } + +#ifdef DUMP_REGS + /* Register dump */ + uint8_t reg; + uint8_t val; + + for(reg = 0x00; reg <= 0x19; reg++) { + if( (reg != 0x10) && \ + (reg != 0x11) ) + { + apds.wireReadDataByte(reg, val); + Serial.print(reg, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); + } + } + apds.wireReadDataByte(0x1E, val); + Serial.print(0x1E, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); +#endif + + // Wait for initialization and calibration to finish + delay(500); +} + +void loop() { + + // If interrupt occurs, print out the light levels + if ( isr_flag ) { + + // Read the light levels (ambient, red, green, blue) and print + if ( !apds.readAmbientLightLux(ambient_light) || + !apds.readCh0Light(ch0) || + !apds.readCh1Light(ch1) ) { + Serial.println("Error reading light values"); + } else { + Serial.print("Interrupt! Ambient: "); + Serial.print(ambient_light); + Serial.print(F(" Ch0: ")); + Serial.print(ch0); + Serial.print(F(" Ch1: ")); + Serial.println(ch1); + } + + // Turn on LED for a half a second + digitalWrite(LED_PIN, HIGH); + delay(500); + digitalWrite(LED_PIN, LOW); + + // Reset flag and clear APDS-9930 interrupt (IMPORTANT!) + isr_flag = false; + if ( !apds.clearAmbientLightInt() ) { + Serial.println("Error clearing interrupt"); + } + + } +} + +void interruptRoutine() { + isr_flag = true; +} \ No newline at end of file diff --git a/firmware/libraries/APDS9930-master/examples/AmbientLightLED/AmbientLightLED.ino b/firmware/libraries/APDS9930-master/examples/AmbientLightLED/AmbientLightLED.ino new file mode 100755 index 0000000..1cd8869 --- /dev/null +++ b/firmware/libraries/APDS9930-master/examples/AmbientLightLED/AmbientLightLED.ino @@ -0,0 +1,113 @@ +/**************************************************************** +AmbientLightLED.ino + +Tests the ambient light sensing abilities of the +APDS-9930. Configures APDS-9930 over I2C and polls the sensor for +ambient light levels, which are displayed over the +serial console. + +Hardware Connections: + +IMPORTANT: The APDS-9930 can only accept 3.3V! + + Arduino Pin APDS-9930 Board Function + + 3.3V VCC Power + GND GND Ground + A4 SDA I2C Data + A5 SCL I2C Clock + + 10 (pwm) LED anode + +Distributed as-is; no warranty is given. +****************************************************************/ + +#define PWM_LED_PIN 10 +#define DUMP_REGS + +#include +#include + +// Global Variables +APDS9930 apds = APDS9930(); +float ambient_light = 0; // can also be an unsigned long +uint16_t ch0 = 0; +uint16_t ch1 = 1; +float max_light = 0; + +void setup() { + //analogReference(EXTERNAL); + pinMode(PWM_LED_PIN, OUTPUT); + + // Initialize Serial port + Serial.begin(9600); + Serial.println(); + Serial.println(F("--------------------------------")); + Serial.println(F("APDS-9930 - Ambient light sensor")); + Serial.println(F("--------------------------------")); + + // Initialize APDS-9930 (configure I2C and initial values) + if ( apds.init() ) { + Serial.println(F("APDS-9930 initialization complete")); + } else { + Serial.println(F("Something went wrong during APDS-9930 init!")); + } + + // Start running the APDS-9930 light sensor (no interrupts) + if ( apds.enableLightSensor(false) ) { + Serial.println(F("Light sensor is now running")); + } else { + Serial.println(F("Something went wrong during light sensor init!")); + } + +#ifdef DUMP_REGS + /* Register dump */ + uint8_t reg; + uint8_t val; + + for(reg = 0x00; reg <= 0x19; reg++) { + if( (reg != 0x10) && \ + (reg != 0x11) ) + { + apds.wireReadDataByte(reg, val); + Serial.print(reg, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); + } + } + apds.wireReadDataByte(0x1E, val); + Serial.print(0x1E, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); +#endif + + // Wait for initialization and calibration to finish + delay(500); +} + +void loop() { + + // Read the light levels (ambient, red, green, blue) + if ( !apds.readAmbientLightLux(ambient_light) || + !apds.readCh0Light(ch0) || + !apds.readCh1Light(ch1) ) { + Serial.println(F("Error reading light values")); + } else { + Serial.print(F("Ambient: ")); + Serial.print(ambient_light); + Serial.print(F(" Ch0: ")); + Serial.print(ch0); + Serial.print(F(" Ch1: ")); + Serial.println(ch1); + + if ( ambient_light > max_light ) { + max_light = ambient_light; + } + ambient_light = map(ambient_light, 0, max_light, 0, 1023); + analogWrite(PWM_LED_PIN, ambient_light); + + } + + // Wait 1 second before next reading + delay(50); +} \ No newline at end of file diff --git a/firmware/libraries/APDS9930-master/examples/AmbientLightSensor/AmbientLightSensor.ino b/firmware/libraries/APDS9930-master/examples/AmbientLightSensor/AmbientLightSensor.ino new file mode 100755 index 0000000..9d390fe --- /dev/null +++ b/firmware/libraries/APDS9930-master/examples/AmbientLightSensor/AmbientLightSensor.ino @@ -0,0 +1,120 @@ +/**************************************************************** +AmbientLightSensor.ino +APDS-9930 Ambient light and proximity sensor +Davide Depau +December 11, 2015 +https://github.com/Davideddu/APDS9930 + +Shawn Hymel @ SparkFun Electronics +October 15, 2014 +https://github.com/sparkfun/APDS-9930_RGB_and_Gesture_Sensor + +Tests thembient light sensing abilities of the +APDS-9930. Configures APDS-9930 over I2C and polls the sensor for +ambient light levels, which are displayed over the +serial console. + +Hardware Connections: + +IMPORTANT: The APDS-9930 can only accept 3.3V! + + Arduino Pin APDS-9930 Board Function + + 3.3V VCC Power + GND GND Ground + A4 SDA I2C Data + A5 SCL I2C Clock + +Resources: +Include Wire.h and APDS-9930.h + +Development environment specifics: +Written in Arduino 1.6.5 +Tested with Arduino Uno and Mega. + +This code is beerware; if you see me (or any other SparkFun +employee) at the local, and you've found our code helpful, please +buy us a round! + +Distributed as-is; no warranty is given. +****************************************************************/ + +#define DUMP_REGS + +#include +#include + +// Global Variables +APDS9930 apds = APDS9930(); +float ambient_light = 0; // can also be an unsigned long +uint16_t ch0 = 0; +uint16_t ch1 = 1; + +void setup() { + //analogReference(EXTERNAL); + + // Initialize Serial port + Serial.begin(9600); + Serial.println(); + Serial.println(F("--------------------------------")); + Serial.println(F("APDS-9930 - Ambient light sensor")); + Serial.println(F("--------------------------------")); + + // Initialize APDS-9930 (configure I2C and initial values) + if ( apds.init() ) { + Serial.println(F("APDS-9930 initialization complete")); + } else { + Serial.println(F("Something went wrong during APDS-9930 init!")); + } + + // Start running the APDS-9930 light sensor (no interrupts) + if ( apds.enableLightSensor(false) ) { + Serial.println(F("Light sensor is now running")); + } else { + Serial.println(F("Something went wrong during light sensor init!")); + } + +#ifdef DUMP_REGS + /* Register dump */ + uint8_t reg; + uint8_t val; + + for(reg = 0x00; reg <= 0x19; reg++) { + if( (reg != 0x10) && \ + (reg != 0x11) ) + { + apds.wireReadDataByte(reg, val); + Serial.print(reg, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); + } + } + apds.wireReadDataByte(0x1E, val); + Serial.print(0x1E, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); +#endif + + // Wait for initialization and calibration to finish + delay(500); +} + +void loop() { + + // Read the light levels (ambient, red, green, blue) + if ( !apds.readAmbientLightLux(ambient_light) || + !apds.readCh0Light(ch0) || + !apds.readCh1Light(ch1) ) { + Serial.println(F("Error reading light values")); + } else { + Serial.print(F("Ambient: ")); + Serial.print(ambient_light); + Serial.print(F(" Ch0: ")); + Serial.print(ch0); + Serial.print(F(" Ch1: ")); + Serial.println(ch1); + } + + // Wait 1 second before next reading + delay(1000); +} \ No newline at end of file diff --git a/firmware/libraries/APDS9930-master/examples/AmbientLightToneAC/AmbientLightToneAC.ino b/firmware/libraries/APDS9930-master/examples/AmbientLightToneAC/AmbientLightToneAC.ino new file mode 100755 index 0000000..ff369b3 --- /dev/null +++ b/firmware/libraries/APDS9930-master/examples/AmbientLightToneAC/AmbientLightToneAC.ino @@ -0,0 +1,108 @@ +/**************************************************************** +AmbientLightToneAC.ino + +Tests the ambient light sensing abilities of the +APDS-9930. Configures APDS-9930 over I2C and polls the sensor for +ambient light levels, which are displayed over the +serial console. + +Hardware Connections: + +IMPORTANT: The APDS-9930 can only accept 3.3V! + + Arduino Pin APDS-9930 Board Function + + 3.3V VCC Power + GND GND Ground + A4 SDA I2C Data + A5 SCL I2C Clock + +Connect speakers to the correct pins. Check toneAC.h for more info. + +Distributed as-is; no warranty is given. +****************************************************************/ + +#define DUMP_REGS + +#include +#include +#include + +// Global Variables +APDS9930 apds = APDS9930(); +float ambient_light = 0; // can also be an unsigned long +uint16_t ch0 = 0; +uint16_t ch1 = 1; +float max_light = 0; + +void setup() { + //analogReference(EXTERNAL); + + // Initialize Serial port + Serial.begin(9600); + Serial.println(); + Serial.println(F("--------------------------------")); + Serial.println(F("APDS-9930 - Ambient light sensor")); + Serial.println(F("--------------------------------")); + + // Initialize APDS-9930 (configure I2C and initial values) + if ( apds.init() ) { + Serial.println(F("APDS-9930 initialization complete")); + } else { + Serial.println(F("Something went wrong during APDS-9930 init!")); + } + + // Start running the APDS-9930 light sensor (no interrupts) + if ( apds.enableLightSensor(false) ) { + Serial.println(F("Light sensor is now running")); + } else { + Serial.println(F("Something went wrong during light sensor init!")); + } + +#ifdef DUMP_REGS + /* Register dump */ + uint8_t reg; + uint8_t val; + + for(reg = 0x00; reg <= 0x19; reg++) { + if( (reg != 0x10) && \ + (reg != 0x11) ) + { + apds.wireReadDataByte(reg, val); + Serial.print(reg, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); + } + } + apds.wireReadDataByte(0x1E, val); + Serial.print(0x1E, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); +#endif + + // Wait for initialization and calibration to finish + delay(500); +} + +void loop() { + + // Read the light levels (ambient, red, green, blue) + if ( !apds.readAmbientLightLux(ambient_light) || + !apds.readCh0Light(ch0) || + !apds.readCh1Light(ch1) ) { + Serial.println(F("Error reading light values")); + } else { + Serial.print(F("Ambient: ")); + Serial.print(ambient_light); + Serial.print(F(" Ch0: ")); + Serial.print(ch0); + Serial.print(F(" Ch1: ")); + Serial.println(ch1); + + unsigned long freq = map(ch0, 0, 1024, 60, 16000); + toneAC(freq, 10, 50, true); + } + + // Wait 1 second before next reading + delay(50); +} \ No newline at end of file diff --git a/firmware/libraries/APDS9930-master/examples/ProximityInterrupt/ProximityInterrupt.ino b/firmware/libraries/APDS9930-master/examples/ProximityInterrupt/ProximityInterrupt.ino new file mode 100755 index 0000000..b93e914 --- /dev/null +++ b/firmware/libraries/APDS9930-master/examples/ProximityInterrupt/ProximityInterrupt.ino @@ -0,0 +1,157 @@ +/**************************************************************** +ProximityInterrupt.ino +APDS-9930 Ambient light and proximity sensor +Davide Depau +December 11, 2015 +https://github.com/Davideddu/APDS9930 + +Shawn Hymel @ SparkFun Electronics +October 24, 2014 +https://github.com/sparkfun/APDS-9930_RGB_and_Gesture_Sensor + +Tests the proximity interrupt abilities of the APDS-9930. +Configures the APDS-9930 over I2C and waits for an external +interrupt based on high or low proximity conditions. Move your +hand near the sensor and watch the LED on pin 13. + +Hardware Connections: + +IMPORTANT: The APDS-9930 can only accept 3.3V! + + Arduino Pin APDS-9930 Board Function + + 3.3V VCC Power + GND GND Ground + A4 SDA I2C Data + A5 SCL I2C Clock + 2 INT Interrupt + 13 - LED + +Resources: +Include Wire.h and APDS9930.h + +Development environment specifics: +Written in Arduino 1.6.5 +Tested with Arduino Uno and Mega + +This code is beerware; if you see me (or any other SparkFun +employee) at the local, and you've found our code helpful, please +buy us a round! + +Distributed as-is; no warranty is given. +****************************************************************/ + +#define DUMP_REGS + +#include +#include + +// Pins +#define APDS9930_INT 2 // Needs to be an interrupt pin +#define LED_PIN 13 // LED for showing interrupt + +// Constants +#define PROX_INT_HIGH 600 // Proximity level for interrupt +#define PROX_INT_LOW 0 // No far interrupt + +// Global variables +APDS9930 apds = APDS9930(); +uint16_t proximity_data = 0; +volatile bool isr_flag = false; + +void setup() { + + // Set LED as output + pinMode(LED_PIN, OUTPUT); + pinMode(APDS9930_INT, INPUT); + + // Initialize Serial port + Serial.begin(9600); + Serial.println(); + Serial.println(F("------------------------------")); + Serial.println(F("APDS-9930 - ProximityInterrupt")); + Serial.println(F("------------------------------")); + + // Initialize interrupt service routine + attachInterrupt(0, interruptRoutine, FALLING); + + // Initialize APDS-9930 (configure I2C and initial values) + if ( apds.init() ) { + Serial.println(F("APDS-9930 initialization complete")); + } else { + Serial.println(F("Something went wrong during APDS-9930 init!")); + } + + // Adjust the Proximity sensor gain + if ( !apds.setProximityGain(PGAIN_2X) ) { + Serial.println(F("Something went wrong trying to set PGAIN")); + } + + // Set proximity interrupt thresholds + if ( !apds.setProximityIntLowThreshold(PROX_INT_LOW) ) { + Serial.println(F("Error writing low threshold")); + } + if ( !apds.setProximityIntHighThreshold(PROX_INT_HIGH) ) { + Serial.println(F("Error writing high threshold")); + } + + // Start running the APDS-9930 proximity sensor (interrupts) + if ( apds.enableProximitySensor(true) ) { + Serial.println(F("Proximity sensor is now running")); + } else { + Serial.println(F("Something went wrong during sensor init!")); + } + +#ifdef DUMP_REGS + /* Register dump */ + uint8_t reg; + uint8_t val; + + for(reg = 0x00; reg <= 0x19; reg++) { + if( (reg != 0x10) && \ + (reg != 0x11) ) + { + apds.wireReadDataByte(reg, val); + Serial.print(reg, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); + } + } + apds.wireReadDataByte(0x1E, val); + Serial.print(0x1E, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); +#endif + +} + +void loop() { + + // If interrupt occurs, print out the proximity level + if ( isr_flag ) { + + // Read proximity level and print it out + if ( !apds.readProximity(proximity_data) ) { + Serial.println("Error reading proximity value"); + } else { + Serial.print("Proximity detected! Level: "); + Serial.println(proximity_data); + } + + // Turn on LED for a half a second + digitalWrite(LED_PIN, HIGH); + delay(500); + digitalWrite(LED_PIN, LOW); + + // Reset flag and clear APDS-9930 interrupt (IMPORTANT!) + isr_flag = false; + if ( !apds.clearProximityInt() ) { + Serial.println("Error clearing interrupt"); + } + + } +} + +void interruptRoutine() { + isr_flag = true; +} \ No newline at end of file diff --git a/firmware/libraries/APDS9930-master/examples/ProximityLED/ProximityLED.ino b/firmware/libraries/APDS9930-master/examples/ProximityLED/ProximityLED.ino new file mode 100755 index 0000000..1694b4e --- /dev/null +++ b/firmware/libraries/APDS9930-master/examples/ProximityLED/ProximityLED.ino @@ -0,0 +1,131 @@ +/**************************************************************** +ProximityLED.ino +Davide Depau +December 11, 2015 +https://github.com/Davideddu/APDS9930 + +https://github.com/sparkfun/APDS-9930_RGB_and_Gesture_Sensor + +Tests the proximity sensing abilities of the APDS-9930. +Configures the APDS-9930 over I2C and polls for the distance to +the object nearest the sensor, then turns on an LED accordingly. + +Hardware Connections: + +IMPORTANT: The APDS-9930 can only accept 3.3V! + + Arduino Pin APDS-9930 Board Function + + 3.3V VCC Power + GND GND Ground + A4 SDA I2C Data + A5 SCL I2C Clock + + 10 (PWM) LED Anode + +Resources: +Include Wire.h and APDS9930.h + +Development environment specifics: +Written in Sublime Text + Stino + Arduino 1.7.2 +Tested with Arduino Uno + level shifter + +This code is chocolateware; if you see me at the grocery store, +and you've found our code helpful, please buy us me a chocolate bar! :D + +Distributed as-is; no warranty is given. +****************************************************************/ + +#define DUMP_REGS +#define PWM_LED_PIN 10 + +#include +#include + +// Global Variables +APDS9930 apds = APDS9930(); +uint16_t proximity_data = 0; +int proximity_max = 0; + +void setup() { + //analogReference(EXTERNAL); + pinMode(PWM_LED_PIN, OUTPUT); + + // Initialize Serial port + Serial.begin(9600); + Serial.println(); + Serial.println(F("------------------------")); + Serial.println(F("APDS-9930 - ProximityLED")); + Serial.println(F("------------------------")); + + // Initialize APDS-9930 (configure I2C and initial values) + if ( apds.init() ) { + Serial.println(F("APDS-9930 initialization complete")); + } else { + Serial.println(F("Something went wrong during APDS-9930 init!")); + } + + // Adjust the Proximity sensor gain + if ( !apds.setProximityGain(PGAIN_1X) ) { + Serial.println(F("Something went wrong trying to set PGAIN")); + } + + // Start running the APDS-9930 proximity sensor (no interrupts) + if ( apds.enableProximitySensor(false) ) { + Serial.println(F("Proximity sensor is now running")); + } else { + Serial.println(F("Something went wrong during sensor init!")); + } + +#ifdef DUMP_REGS + /* Register dump */ + uint8_t reg; + uint8_t val; + + for(reg = 0x00; reg <= 0x19; reg++) { + if( (reg != 0x10) && \ + (reg != 0x11) ) + { + apds.wireReadDataByte(reg, val); + Serial.print(reg, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); + } + } + apds.wireReadDataByte(0x1E, val); + Serial.print(0x1E, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); +#endif +} + +void loop() { + + // Read the proximity value + if ( !apds.readProximity(proximity_data) ) { + Serial.println("Error reading proximity value"); + } else { + Serial.print("Proximity: "); + Serial.print(proximity_data); + + // This is an ugly hack to reduce sensor noise. + // You may want to adjust POFFSET instead. + /* + proximity_data -= 200; + if (proximity_data > 50000) { + proximity_data = 0; + } + if (proximity_data > proximity_max) { + proximity_max = proximity_data; + } + proximity_data = map(proximity_data, 0, proximity_max, 0, 1023); + */ + + Serial.print(F(" Remapped: ")); + Serial.println(proximity_data); + analogWrite(PWM_LED_PIN, proximity_data); + } + + // Wait 250 ms before next reading + delay(10); +} \ No newline at end of file diff --git a/firmware/libraries/APDS9930-master/examples/ProximitySensor/ProximitySensor.ino b/firmware/libraries/APDS9930-master/examples/ProximitySensor/ProximitySensor.ino new file mode 100755 index 0000000..1fe2054 --- /dev/null +++ b/firmware/libraries/APDS9930-master/examples/ProximitySensor/ProximitySensor.ino @@ -0,0 +1,113 @@ +/**************************************************************** +ProximitySensor.ino +APDS-9930 ambient light and proximity sensor +Davide Depau +December 11, 2015 +https://github.com/Davideddu/APDS9930 + +Shawn Hymel @ SparkFun Electronics +October 28, 2014 +https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor + +Tests the proximity sensing abilities of the APDS-9930. +Configures the APDS-9930 over I2C and polls for the distance to +the object nearest the sensor. + +Hardware Connections: + +IMPORTANT: The APDS-9930 can only accept 3.3V! + + Arduino Pin APDS-9930 Board Function + + 3.3V VCC Power + GND GND Ground + A4 SDA I2C Data + A5 SCL I2C Clock + +Resources: +Include Wire.h and SparkFun_APDS-9930.h + +Development environment specifics: +Written in Arduino 1.0.5 +Tested with SparkFun Arduino Pro Mini 3.3V + +This code is beerware; if you see me (or any other SparkFun +employee) at the local, and you've found our code helpful, please +buy us a round! + +Distributed as-is; no warranty is given. +****************************************************************/ + +#define DUMP_REGS + +#include +#include + +// Global Variables +APDS9930 apds = APDS9930(); +uint16_t proximity_data = 0; + +void setup() { + //analogReference(EXTERNAL); + + // Initialize Serial port + Serial.begin(9600); + Serial.println(); + Serial.println(F("---------------------------")); + Serial.println(F("APDS-9930 - ProximitySensor")); + Serial.println(F("---------------------------")); + + // Initialize APDS-9930 (configure I2C and initial values) + if ( apds.init() ) { + Serial.println(F("APDS-9930 initialization complete")); + } else { + Serial.println(F("Something went wrong during APDS-9930 init!")); + } + + // // Adjust the Proximity sensor gain + // if ( !apds.setProximityGain(PGAIN_2X) ) { + // Serial.println(F("Something went wrong trying to set PGAIN")); + // } + + // Start running the APDS-9930 proximity sensor (no interrupts) + if ( apds.enableProximitySensor(false) ) { + Serial.println(F("Proximity sensor is now running")); + } else { + Serial.println(F("Something went wrong during sensor init!")); + } + +#ifdef DUMP_REGS + /* Register dump */ + uint8_t reg; + uint8_t val; + + for(reg = 0x00; reg <= 0x19; reg++) { + if( (reg != 0x10) && \ + (reg != 0x11) ) + { + apds.wireReadDataByte(reg, val); + Serial.print(reg, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); + } + } + apds.wireReadDataByte(0x1E, val); + Serial.print(0x1E, HEX); + Serial.print(": 0x"); + Serial.println(val, HEX); +#endif +} + +void loop() { + + // Read the proximity value + if ( !apds.readProximity(proximity_data) ) { + Serial.println("Error reading proximity value"); + } else { + Serial.print("Proximity: "); + Serial.println(proximity_data); + } + + // Wait 250 ms before next reading + delay(250); +} \ No newline at end of file diff --git a/firmware/libraries/APDS9930-master/keywords.txt b/firmware/libraries/APDS9930-master/keywords.txt new file mode 100755 index 0000000..e69de29 diff --git a/firmware/libraries/APDS9930-master/library.properties b/firmware/libraries/APDS9930-master/library.properties new file mode 100755 index 0000000..7487b16 --- /dev/null +++ b/firmware/libraries/APDS9930-master/library.properties @@ -0,0 +1,9 @@ +name=APDS-9930 Ambient Light and Proximity Sensor +version=1.5.1 +author=Davide Depau +maintainer=Davide Depau +sentence=Library for the Avago APDS-9930 sensor +paragraph=This library works with the breakout board for the Avago APDS-9930 proximity and light sensor +category=Sensors +url=https://github.com/Davideddu/APDS9930 +architectures=* diff --git a/firmware/libraries/APDS9930-master/src/APDS9930.cpp b/firmware/libraries/APDS9930-master/src/APDS9930.cpp new file mode 100755 index 0000000..ccfd0ff --- /dev/null +++ b/firmware/libraries/APDS9930-master/src/APDS9930.cpp @@ -0,0 +1,1147 @@ +/** + * @file APDS-9930.cpp + * @brief Library for the SparkFun APDS-9930 breakout board + * @author Shawn Hymel (SparkFun Electronics) + * + * @copyright This code is public domain but you buy me a beer if you use + * this and we meet someday (Beerware license). + * + * This library interfaces the Avago APDS-9930 to Arduino over I2C. The library + * relies on the Arduino Wire (I2C) library. to use the library, instantiate an + * APDS9930 object, call init(), and call the appropriate functions. + * + * APDS-9930 current draw tests (default parameters): + * Off: 1mA + * Waiting for gesture: 14mA + * Gesture in progress: 35mA + */ + + #include + #include + + #include "APDS9930.h" + +/** + * @brief Constructor - Instantiates APDS9930 object + */ +APDS9930::APDS9930() +{ + +} + +/** + * @brief Destructor + */ +APDS9930::~APDS9930() +{ + +} + +/** + * @brief Configures I2C communications and initializes registers to defaults + * + * @return True if initialized successfully. False otherwise. + */ +bool APDS9930::init() +{ + uint8_t id; + + /* Initialize I2C */ + Wire.begin(); + + /* Read ID register and check against known values for APDS-9930 */ + if( !wireReadDataByte(APDS9930_ID, id) ) { + Serial.println(F("ID read")); + return false; + } + if( !(id == APDS9930_ID_1 || id == APDS9930_ID_2) ) { + Serial.println(F("ID check")); + Serial.println(String("ID is ") + String(id, HEX)); + //return false; + } + + /* Set ENABLE register to 0 (disable all features) */ + if( !setMode(ALL, OFF) ) { + Serial.println(F("Regs off")); + return false; + } + + /* Set default values for ambient light and proximity registers */ + if( !wireWriteDataByte(APDS9930_ATIME, DEFAULT_ATIME) ) { + return false; + } + if( !wireWriteDataByte(APDS9930_WTIME, DEFAULT_WTIME) ) { + return false; + } + if( !wireWriteDataByte(APDS9930_PPULSE, DEFAULT_PPULSE) ) { + return false; + } + if( !wireWriteDataByte(APDS9930_POFFSET, DEFAULT_POFFSET) ) { + return false; + } + if( !wireWriteDataByte(APDS9930_CONFIG, DEFAULT_CONFIG) ) { + return false; + } + if( !setLEDDrive(DEFAULT_PDRIVE) ) { + return false; + } + if( !setProximityGain(DEFAULT_PGAIN) ) { + return false; + } + if( !setAmbientLightGain(DEFAULT_AGAIN) ) { + return false; + } + if( !setProximityDiode(DEFAULT_PDIODE) ) { + return false; + } + if( !setProximityIntLowThreshold(DEFAULT_PILT) ) { + return false; + } + if( !setProximityIntHighThreshold(DEFAULT_PIHT) ) { + return false; + } + if( !setLightIntLowThreshold(DEFAULT_AILT) ) { + return false; + } + if( !setLightIntHighThreshold(DEFAULT_AIHT) ) { + return false; + } + if( !wireWriteDataByte(APDS9930_PERS, DEFAULT_PERS) ) { + return false; + } + + return true; +} + +/******************************************************************************* + * Public methods for controlling the APDS-9930 + ******************************************************************************/ + +/** + * @brief Reads and returns the contents of the ENABLE register + * + * @return Contents of the ENABLE register. 0xFF if error. + */ +uint8_t APDS9930::getMode() +{ + uint8_t enable_value; + + /* Read current ENABLE register */ + if( !wireReadDataByte(APDS9930_ENABLE, enable_value) ) { + return ERROR; + } + + return enable_value; +} + +/** + * @brief Enables or disables a feature in the APDS-9930 + * + * @param[in] mode which feature to enable + * @param[in] enable ON (1) or OFF (0) + * @return True if operation success. False otherwise. + */ +bool APDS9930::setMode(uint8_t mode, uint8_t enable) +{ + uint8_t reg_val; + + /* Read current ENABLE register */ + reg_val = getMode(); + if( reg_val == ERROR ) { + return false; + } + + /* Change bit(s) in ENABLE register */ + enable = enable & 0x01; + if( mode >= 0 && mode <= 6 ) { + if (enable) { + reg_val |= (1 << mode); + } else { + reg_val &= ~(1 << mode); + } + } else if( mode == ALL ) { + if (enable) { + reg_val = 0x7F; + } else { + reg_val = 0x00; + } + } + + /* Write value back to ENABLE register */ + if( !wireWriteDataByte(APDS9930_ENABLE, reg_val) ) { + return false; + } + + return true; +} + +/** + * @brief Starts the light (Ambient/IR) sensor on the APDS-9930 + * + * @param[in] interrupts true to enable hardware interrupt on high or low light + * @return True if sensor enabled correctly. False on error. + */ +bool APDS9930::enableLightSensor(bool interrupts) +{ + + /* Set default gain, interrupts, enable power, and enable sensor */ + if( !setAmbientLightGain(DEFAULT_AGAIN) ) { + return false; + } + if( interrupts ) { + if( !setAmbientLightIntEnable(1) ) { + return false; + } + } else { + if( !setAmbientLightIntEnable(0) ) { + return false; + } + } + if( !enablePower() ){ + return false; + } + if( !setMode(AMBIENT_LIGHT, 1) ) { + return false; + } + + return true; + +} + +/** + * @brief Ends the light sensor on the APDS-9930 + * + * @return True if sensor disabled correctly. False on error. + */ +bool APDS9930::disableLightSensor() +{ + if( !setAmbientLightIntEnable(0) ) { + return false; + } + if( !setMode(AMBIENT_LIGHT, 0) ) { + return false; + } + + return true; +} + +/** + * @brief Starts the proximity sensor on the APDS-9930 + * + * @param[in] interrupts true to enable hardware external interrupt on proximity + * @return True if sensor enabled correctly. False on error. + */ +bool APDS9930::enableProximitySensor(bool interrupts) +{ + /* Set default gain, LED, interrupts, enable power, and enable sensor */ + if( !setProximityGain(DEFAULT_PGAIN) ) { + return false; + } + if( !setLEDDrive(DEFAULT_PDRIVE) ) { + return false; + } + if( interrupts ) { + if( !setProximityIntEnable(1) ) { + return false; + } + } else { + if( !setProximityIntEnable(0) ) { + return false; + } + } + if( !enablePower() ){ + return false; + } + if( !setMode(PROXIMITY, 1) ) { + return false; + } + + return true; +} + +/** + * @brief Ends the proximity sensor on the APDS-9930 + * + * @return True if sensor disabled correctly. False on error. + */ +bool APDS9930::disableProximitySensor() +{ + if( !setProximityIntEnable(0) ) { + return false; + } + if( !setMode(PROXIMITY, 0) ) { + return false; + } + + return true; +} + +/** + * Turn the APDS-9930 on + * + * @return True if operation successful. False otherwise. + */ +bool APDS9930::enablePower() +{ + if( !setMode(POWER, 1) ) { + return false; + } + + return true; +} + +/** + * Turn the APDS-9930 off + * + * @return True if operation successful. False otherwise. + */ +bool APDS9930::disablePower() +{ + if( !setMode(POWER, 0) ) { + return false; + } + + return true; +} + +/******************************************************************************* + * Ambient light sensor controls + ******************************************************************************/ + +/** + * @brief Reads the ambient (clear) light level as a 16-bit value + * + * @param[out] val value of the light sensor. + * @return True if operation successful. False otherwise. + */ +bool APDS9930::readAmbientLightLux(float &val) +{ + uint16_t Ch0; + uint16_t Ch1; + + /* Read value from channel 0 */ + if( !readCh0Light(Ch0) ) { + return false; + } + + /* Read value from channel 1 */ + if( !readCh1Light(Ch1) ) { + return false; + } + + val = floatAmbientToLux(Ch0, Ch1); + return true; +} + +bool APDS9930::readAmbientLightLux(unsigned long &val) +{ + uint16_t Ch0; + uint16_t Ch1; + + /* Read value from channel 0 */ + if( !readCh0Light(Ch0) ) { + return false; + } + + /* Read value from channel 1 */ + if( !readCh1Light(Ch1) ) { + return false; + } + + val = ulongAmbientToLux(Ch0, Ch1); + return true; +} + +float APDS9930::floatAmbientToLux(uint16_t Ch0, uint16_t Ch1) +{ + uint8_t x[4]={1,8,16,120}; + float ALSIT = 2.73 * (256 - DEFAULT_ATIME); + float iac = max(Ch0 - B * Ch1, C * Ch0 - D * Ch1); + if (iac < 0) iac = 0; + float lpc = GA * DF / (ALSIT * x[getAmbientLightGain()]); + return iac * lpc; +} + +unsigned long APDS9930::ulongAmbientToLux(uint16_t Ch0, uint16_t Ch1) +{ + uint8_t x[4]={1,8,16,120}; + unsigned long ALSIT = 2.73 * (256 - DEFAULT_ATIME); + unsigned long iac = max(Ch0 - B * Ch1, C * Ch0 - D * Ch1); + if (iac < 0) iac = 0; + unsigned long lpc = GA * DF / (ALSIT * x[getAmbientLightGain()]); + return iac * lpc; +} + +bool APDS9930::readCh0Light(uint16_t &val) +{ + uint8_t val_byte; + val = 0; + + /* Read value from channel 0 */ + if( !wireReadDataByte(APDS9930_Ch0DATAL, val_byte) ) { + return false; + } + val = val_byte; + if( !wireReadDataByte(APDS9930_Ch0DATAH, val_byte) ) { + return false; + } + val += ((uint16_t)val_byte << 8); + return true; +} + +bool APDS9930::readCh1Light(uint16_t &val) +{ + uint8_t val_byte; + val = 0; + + /* Read value from channel 0 */ + if( !wireReadDataByte(APDS9930_Ch1DATAL, val_byte) ) { + return false; + } + val = val_byte; + if( !wireReadDataByte(APDS9930_Ch1DATAH, val_byte) ) { + return false; + } + val += ((uint16_t)val_byte << 8); + return true; +} + +/******************************************************************************* + * Proximity sensor controls + ******************************************************************************/ + +/** + * @brief Reads the proximity level as an 8-bit value + * + * @param[out] val value of the proximity sensor. + * @return True if operation successful. False otherwise. + */ +bool APDS9930::readProximity(uint16_t &val) +{ + val = 0; + uint8_t val_byte; + + /* Read value from proximity data register */ + if( !wireReadDataByte(APDS9930_PDATAL, val_byte) ) { + return false; + } + val = val_byte; + if( !wireReadDataByte(APDS9930_PDATAH, val_byte) ) { + return false; + } + val += ((uint16_t)val_byte << 8); + + return true; +} + +/******************************************************************************* + * Getters and setters for register values + ******************************************************************************/ + +/** + * @brief Returns the lower threshold for proximity detection + * + * @return lower threshold + */ +uint16_t APDS9930::getProximityIntLowThreshold() +{ + uint16_t val; + uint8_t val_byte; + + /* Read value from PILT register */ + if( !wireReadDataByte(APDS9930_PILTL, val_byte) ) { + val = 0; + } + val = val_byte; + if( !wireReadDataByte(APDS9930_PILTH, val_byte) ) { + val = 0; + } + val |= ((uint16_t)val_byte << 8); + + return val; +} + +/** + * @brief Sets the lower threshold for proximity detection + * + * @param[in] threshold the lower proximity threshold + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setProximityIntLowThreshold(uint16_t threshold) +{ + uint8_t lo; + uint8_t hi; + hi = threshold >> 8; + lo = threshold & 0x00FF; + + if( !wireWriteDataByte(APDS9930_PILTL, lo) ) { + return false; + } + if( !wireWriteDataByte(APDS9930_PILTH, hi) ) { + return false; + } + + return true; +} + +/** + * @brief Returns the high threshold for proximity detection + * + * @return high threshold + */ +uint16_t APDS9930::getProximityIntHighThreshold() +{ + uint16_t val; + uint8_t val_byte; + + /* Read value from PILT register */ + if( !wireReadDataByte(APDS9930_PIHTL, val_byte) ) { + val = 0; + } + val = val_byte; + if( !wireReadDataByte(APDS9930_PIHTH, val_byte) ) { + val = 0; + } + val |= ((uint16_t)val_byte << 8); + + return val; +} + +/** + * @brief Sets the high threshold for proximity detection + * + * @param[in] threshold the high proximity threshold + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setProximityIntHighThreshold(uint16_t threshold) +{ + uint8_t lo; + uint8_t hi; + hi = threshold >> 8; + lo = threshold & 0x00FF; + + if( !wireWriteDataByte(APDS9930_PIHTL, lo) ) { + return false; + } + if( !wireWriteDataByte(APDS9930_PIHTH, hi) ) { + return false; + } + + return true; +} + +/** + * @brief Returns LED drive strength for proximity and ALS + * + * Value LED Current + * 0 100 mA + * 1 50 mA + * 2 25 mA + * 3 12.5 mA + * + * @return the value of the LED drive strength. 0xFF on failure. + */ +uint8_t APDS9930::getLEDDrive() +{ + uint8_t val; + + /* Read value from CONTROL register */ + if( !wireReadDataByte(APDS9930_CONTROL, val) ) { + return ERROR; + } + + /* Shift and mask out LED drive bits */ + val = (val >> 6) & 0b00000011; + + return val; +} + +/** + * @brief Sets the LED drive strength for proximity and ALS + * + * Value LED Current + * 0 100 mA + * 1 50 mA + * 2 25 mA + * 3 12.5 mA + * + * @param[in] drive the value (0-3) for the LED drive strength + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setLEDDrive(uint8_t drive) +{ + uint8_t val; + + /* Read value from CONTROL register */ + if( !wireReadDataByte(APDS9930_CONTROL, val) ) { + return false; + } + + /* Set bits in register to given value */ + drive &= 0b00000011; + drive = drive << 6; + val &= 0b00111111; + val |= drive; + + /* Write register value back into CONTROL register */ + if( !wireWriteDataByte(APDS9930_CONTROL, val) ) { + return false; + } + + return true; +} + +/** + * @brief Returns receiver gain for proximity detection + * + * Value Gain + * 0 1x + * 1 2x + * 2 4x + * 3 8x + * + * @return the value of the proximity gain. 0xFF on failure. + */ +uint8_t APDS9930::getProximityGain() +{ + uint8_t val; + + /* Read value from CONTROL register */ + if( !wireReadDataByte(APDS9930_CONTROL, val) ) { + return ERROR; + } + + /* Shift and mask out PDRIVE bits */ + val = (val >> 2) & 0b00000011; + + return val; +} + +/** + * @brief Sets the receiver gain for proximity detection + * + * Value Gain + * 0 1x + * 1 2x + * 2 4x + * 3 8x + * + * @param[in] drive the value (0-3) for the gain + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setProximityGain(uint8_t drive) +{ + uint8_t val; + + /* Read value from CONTROL register */ + if( !wireReadDataByte(APDS9930_CONTROL, val) ) { + return false; + } + + /* Set bits in register to given value */ + drive &= 0b00000011; + drive = drive << 2; + val &= 0b11110011; + val |= drive; + + /* Write register value back into CONTROL register */ + if( !wireWriteDataByte(APDS9930_CONTROL, val) ) { + return false; + } + + return true; +} + +/** + * @brief Returns the proximity diode + * + * Value Diode selection + * 0 Reserved + * 1 Reserved + * 2 Use Ch1 diode + * 3 Reserved + * + * @return the selected diode. 0xFF on failure. + */ +uint8_t APDS9930::getProximityDiode() +{ + uint8_t val; + + /* Read value from CONTROL register */ + if( !wireReadDataByte(APDS9930_CONTROL, val) ) { + return ERROR; + } + + /* Shift and mask out PDRIVE bits */ + val = (val >> 4) & 0b00000011; + + return val; +} + +/** + * @brief Selects the proximity diode + * + * Value Diode selection + * 0 Reserved + * 1 Reserved + * 2 Use Ch1 diode + * 3 Reserved + * + * @param[in] drive the value (0-3) for the diode + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setProximityDiode(uint8_t drive) +{ + uint8_t val; + + /* Read value from CONTROL register */ + if( !wireReadDataByte(APDS9930_CONTROL, val) ) { + return false; + } + + /* Set bits in register to given value */ + drive &= 0b00000011; + drive = drive << 4; + val &= 0b11001111; + val |= drive; + + /* Write register value back into CONTROL register */ + if( !wireWriteDataByte(APDS9930_CONTROL, val) ) { + return false; + } + + return true; +} + +/** + * @brief Returns receiver gain for the ambient light sensor (ALS) + * + * Value Gain + * 0 1x + * 1 4x + * 2 16x + * 3 120x + * + * @return the value of the ALS gain. 0xFF on failure. + */ +uint8_t APDS9930::getAmbientLightGain() +{ + uint8_t val; + + /* Read value from CONTROL register */ + if( !wireReadDataByte(APDS9930_CONTROL, val) ) { + return ERROR; + } + + /* Shift and mask out ADRIVE bits */ + val &= 0b00000011; + + return val; +} + +/** + * @brief Sets the receiver gain for the ambient light sensor (ALS) + * + * Value Gain + * 0 1x + * 1 4x + * 2 16x + * 3 64x + * + * @param[in] drive the value (0-3) for the gain + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setAmbientLightGain(uint8_t drive) +{ + uint8_t val; + + /* Read value from CONTROL register */ + if( !wireReadDataByte(APDS9930_CONTROL, val) ) { + return false; + } + + /* Set bits in register to given value */ + drive &= 0b00000011; + val &= 0b11111100; + val |= drive; + + /* Write register value back into CONTROL register */ + if( !wireWriteDataByte(APDS9930_CONTROL, val) ) { + return false; + } + + return true; +} + +/** + * @brief Gets the low threshold for ambient light interrupts + * + * @param[out] threshold current low threshold stored on the APDS-9930 + * @return True if operation successful. False otherwise. + */ +bool APDS9930::getLightIntLowThreshold(uint16_t &threshold) +{ + uint8_t val_byte; + threshold = 0; + + /* Read value from ambient light low threshold, low byte register */ + if( !wireReadDataByte(APDS9930_AILTL, val_byte) ) { + return false; + } + threshold = val_byte; + + /* Read value from ambient light low threshold, high byte register */ + if( !wireReadDataByte(APDS9930_AILTH, val_byte) ) { + return false; + } + threshold = threshold + ((uint16_t)val_byte << 8); + + return true; +} + +/** + * @brief Sets the low threshold for ambient light interrupts + * + * @param[in] threshold low threshold value for interrupt to trigger + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setLightIntLowThreshold(uint16_t threshold) +{ + uint8_t val_low; + uint8_t val_high; + + /* Break 16-bit threshold into 2 8-bit values */ + val_low = threshold & 0x00FF; + val_high = (threshold & 0xFF00) >> 8; + + /* Write low byte */ + if( !wireWriteDataByte(APDS9930_AILTL, val_low) ) { + return false; + } + + /* Write high byte */ + if( !wireWriteDataByte(APDS9930_AILTH, val_high) ) { + return false; + } + + return true; +} + +/** + * @brief Gets the high threshold for ambient light interrupts + * + * @param[out] threshold current low threshold stored on the APDS-9930 + * @return True if operation successful. False otherwise. + */ +bool APDS9930::getLightIntHighThreshold(uint16_t &threshold) +{ + uint8_t val_byte; + threshold = 0; + + /* Read value from ambient light high threshold, low byte register */ + if( !wireReadDataByte(APDS9930_AIHTL, val_byte) ) { + return false; + } + threshold = val_byte; + + /* Read value from ambient light high threshold, high byte register */ + if( !wireReadDataByte(APDS9930_AIHTH, val_byte) ) { + return false; + } + threshold = threshold + ((uint16_t)val_byte << 8); + + return true; +} + +/** + * @brief Sets the high threshold for ambient light interrupts + * + * @param[in] threshold high threshold value for interrupt to trigger + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setLightIntHighThreshold(uint16_t threshold) +{ + uint8_t val_low; + uint8_t val_high; + + /* Break 16-bit threshold into 2 8-bit values */ + val_low = threshold & 0x00FF; + val_high = (threshold & 0xFF00) >> 8; + + /* Write low byte */ + if( !wireWriteDataByte(APDS9930_AIHTL, val_low) ) { + return false; + } + + /* Write high byte */ + if( !wireWriteDataByte(APDS9930_AIHTH, val_high) ) { + return false; + } + + return true; +} + + +/** + * @brief Gets if ambient light interrupts are enabled or not + * + * @return 1 if interrupts are enabled, 0 if not. 0xFF on error. + */ +uint8_t APDS9930::getAmbientLightIntEnable() +{ + uint8_t val; + + /* Read value from ENABLE register */ + if( !wireReadDataByte(APDS9930_ENABLE, val) ) { + return ERROR; + } + + /* Shift and mask out AIEN bit */ + val = (val >> 4) & 0b00000001; + + return val; +} + +/** + * @brief Turns ambient light interrupts on or off + * + * @param[in] enable 1 to enable interrupts, 0 to turn them off + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setAmbientLightIntEnable(uint8_t enable) +{ + uint8_t val; + + /* Read value from ENABLE register */ + if( !wireReadDataByte(APDS9930_ENABLE, val) ) { + return false; + } + + /* Set bits in register to given value */ + enable &= 0b00000001; + enable = enable << 4; + val &= 0b11101111; + val |= enable; + + /* Write register value back into ENABLE register */ + if( !wireWriteDataByte(APDS9930_ENABLE, val) ) { + return false; + } + + return true; +} + +/** + * @brief Gets if proximity interrupts are enabled or not + * + * @return 1 if interrupts are enabled, 0 if not. 0xFF on error. + */ +uint8_t APDS9930::getProximityIntEnable() +{ + uint8_t val; + + /* Read value from ENABLE register */ + if( !wireReadDataByte(APDS9930_ENABLE, val) ) { + return ERROR; + } + + /* Shift and mask out PIEN bit */ + val = (val >> 5) & 0b00000001; + + return val; +} + +/** + * @brief Turns proximity interrupts on or off + * + * @param[in] enable 1 to enable interrupts, 0 to turn them off + * @return True if operation successful. False otherwise. + */ +bool APDS9930::setProximityIntEnable(uint8_t enable) +{ + uint8_t val; + + /* Read value from ENABLE register */ + if( !wireReadDataByte(APDS9930_ENABLE, val) ) { + return false; + } + + /* Set bits in register to given value */ + enable &= 0b00000001; + enable = enable << 5; + val &= 0b11011111; + val |= enable; + + /* Write register value back into ENABLE register */ + if( !wireWriteDataByte(APDS9930_ENABLE, val) ) { + return false; + } + + return true; +} + +/** + * @brief Clears the ambient light interrupt + * + * @return True if operation completed successfully. False otherwise. + */ +bool APDS9930::clearAmbientLightInt() +{ + if( !wireWriteByte(CLEAR_ALS_INT) ) { + return false; + } + + return true; +} + +/** + * @brief Clears the proximity interrupt + * + * @return True if operation completed successfully. False otherwise. + */ +bool APDS9930::clearProximityInt() +{ + if( !wireWriteByte(CLEAR_PROX_INT) ) { + return false; + } + + return true; +} + +/** + * @brief Clears all interrupts + * + * @return True if operation completed successfully. False otherwise. + */ +bool APDS9930::clearAllInts() +{ + if( !wireWriteByte(CLEAR_ALL_INTS) ) { + return false; + } + + return true; +} + +/******************************************************************************* + * Raw I2C Reads and Writes + ******************************************************************************/ + +/** + * @brief Writes a single byte to the I2C device (no register) + * + * @param[in] val the 1-byte value to write to the I2C device + * @return True if successful write operation. False otherwise. + */ +bool APDS9930::wireWriteByte(uint8_t val) +{ + Wire.beginTransmission(APDS9930_I2C_ADDR); + Wire.write(val); + if( Wire.endTransmission() != 0 ) { + return false; + } + + return true; +} + +/** + * @brief Writes a single byte to the I2C device and specified register + * + * @param[in] reg the register in the I2C device to write to + * @param[in] val the 1-byte value to write to the I2C device + * @return True if successful write operation. False otherwise. + */ +bool APDS9930::wireWriteDataByte(uint8_t reg, uint8_t val) +{ + Wire.beginTransmission(APDS9930_I2C_ADDR); + Wire.write(reg | AUTO_INCREMENT); + Wire.write(val); + if( Wire.endTransmission() != 0 ) { + return false; + } + + return true; +} + +/** + * @brief Writes a block (array) of bytes to the I2C device and register + * + * @param[in] reg the register in the I2C device to write to + * @param[in] val pointer to the beginning of the data byte array + * @param[in] len the length (in bytes) of the data to write + * @return True if successful write operation. False otherwise. + */ +bool APDS9930::wireWriteDataBlock( uint8_t reg, + uint8_t *val, + unsigned int len) +{ + unsigned int i; + + Wire.beginTransmission(APDS9930_I2C_ADDR); + Wire.write(reg | AUTO_INCREMENT); + for(i = 0; i < len; i++) { + Wire.beginTransmission(APDS9930_I2C_ADDR); + Wire.write(val[i]); + } + if( Wire.endTransmission() != 0 ) { + return false; + } + + return true; +} + +/** + * @brief Reads a single byte from the I2C device and specified register + * + * @param[in] reg the register to read from + * @param[out] the value returned from the register + * @return True if successful read operation. False otherwise. + */ +bool APDS9930::wireReadDataByte(uint8_t reg, uint8_t &val) +{ + + /* Indicate which register we want to read from */ + if (!wireWriteByte(reg | AUTO_INCREMENT)) { + return false; + } + + /* Read from register */ + Wire.requestFrom(APDS9930_I2C_ADDR, 1); + while (Wire.available()) { + val = Wire.read(); + } + + return true; +} + + +/** + * @brief Reads a block (array) of bytes from the I2C device and register + * + * @param[in] reg the register to read from + * @param[out] val pointer to the beginning of the data + * @param[in] len number of bytes to read + * @return Number of bytes read. -1 on read error. + */ +int APDS9930::wireReadDataBlock( uint8_t reg, + uint8_t *val, + unsigned int len) +{ + unsigned char i = 0; + + /* Indicate which register we want to read from */ + if (!wireWriteByte(reg | AUTO_INCREMENT)) { + return -1; + } + + /* Read block data */ + Wire.requestFrom(APDS9930_I2C_ADDR, len); + while (Wire.available()) { + if (i >= len) { + return -1; + } + val[i] = Wire.read(); + i++; + } + + return i; +} \ No newline at end of file diff --git a/firmware/libraries/APDS9930-master/src/APDS9930.h b/firmware/libraries/APDS9930-master/src/APDS9930.h new file mode 100755 index 0000000..640544d --- /dev/null +++ b/firmware/libraries/APDS9930-master/src/APDS9930.h @@ -0,0 +1,231 @@ +/** + * @file APDS-9930.h + * @brief Library for the SparkFun APDS-9930 breakout board + * @author Shawn Hymel (SparkFun Electronics) + * + * @copyright This code is public domain but you buy me a beer if you use + * this and we meet someday (Beerware license). + * + * This library interfaces the Avago APDS-9930 to Arduino over I2C. The library + * relies on the Arduino Wire (I2C) library. to use the library, instantiate an + * APDS9930 object, call init(), and call the appropriate functions. + */ + +#ifndef APDS9930_H +#define APDS9930_H + +#include + +/* Debug */ +#define DEBUG 0 + +/* APDS-9930 I2C address */ +#define APDS9930_I2C_ADDR 0x39 + +/* Command register modes */ +#define REPEATED_BYTE 0x80 +#define AUTO_INCREMENT 0xA0 +#define SPECIAL_FN 0xE0 + +/* Error code for returned values */ +#define ERROR 0xFF + +/* Acceptable device IDs */ +#define APDS9930_ID_1 0x12 +#define APDS9930_ID_2 0x39 + +/* Misc parameters */ +#define FIFO_PAUSE_TIME 30 // Wait period (ms) between FIFO reads + +/* APDS-9930 register addresses */ +#define APDS9930_ENABLE 0x00 +#define APDS9930_ATIME 0x01 +#define APDS9930_PTIME 0x02 +#define APDS9930_WTIME 0x03 +#define APDS9930_AILTL 0x04 +#define APDS9930_AILTH 0x05 +#define APDS9930_AIHTL 0x06 +#define APDS9930_AIHTH 0x07 +#define APDS9930_PILTL 0x08 +#define APDS9930_PILTH 0x09 +#define APDS9930_PIHTL 0x0A +#define APDS9930_PIHTH 0x0B +#define APDS9930_PERS 0x0C +#define APDS9930_CONFIG 0x0D +#define APDS9930_PPULSE 0x0E +#define APDS9930_CONTROL 0x0F +#define APDS9930_ID 0x12 +#define APDS9930_STATUS 0x13 +#define APDS9930_Ch0DATAL 0x14 +#define APDS9930_Ch0DATAH 0x15 +#define APDS9930_Ch1DATAL 0x16 +#define APDS9930_Ch1DATAH 0x17 +#define APDS9930_PDATAL 0x18 +#define APDS9930_PDATAH 0x19 +#define APDS9930_POFFSET 0x1E + + +/* Bit fields */ +#define APDS9930_PON 0b00000001 +#define APDS9930_AEN 0b00000010 +#define APDS9930_PEN 0b00000100 +#define APDS9930_WEN 0b00001000 +#define APSD9930_AIEN 0b00010000 +#define APDS9930_PIEN 0b00100000 +#define APDS9930_SAI 0b01000000 + +/* On/Off definitions */ +#define OFF 0 +#define ON 1 + +/* Acceptable parameters for setMode */ +#define POWER 0 +#define AMBIENT_LIGHT 1 +#define PROXIMITY 2 +#define WAIT 3 +#define AMBIENT_LIGHT_INT 4 +#define PROXIMITY_INT 5 +#define SLEEP_AFTER_INT 6 +#define ALL 7 + +/* LED Drive values */ +#define LED_DRIVE_100MA 0 +#define LED_DRIVE_50MA 1 +#define LED_DRIVE_25MA 2 +#define LED_DRIVE_12_5MA 3 + +/* Proximity Gain (PGAIN) values */ +#define PGAIN_1X 0 +#define PGAIN_2X 1 +#define PGAIN_4X 2 +#define PGAIN_8X 3 + +/* ALS Gain (AGAIN) values */ +#define AGAIN_1X 0 +#define AGAIN_8X 1 +#define AGAIN_16X 2 +#define AGAIN_120X 3 + +/* Interrupt clear values */ +#define CLEAR_PROX_INT 0xE5 +#define CLEAR_ALS_INT 0xE6 +#define CLEAR_ALL_INTS 0xE7 + +/* Default values */ +#define DEFAULT_ATIME 0xED +#define DEFAULT_WTIME 0xFF +#define DEFAULT_PTIME 0xFF +#define DEFAULT_PPULSE 0x08 +#define DEFAULT_POFFSET 0 // 0 offset +#define DEFAULT_CONFIG 0 +#define DEFAULT_PDRIVE LED_DRIVE_100MA +#define DEFAULT_PDIODE 2 +#define DEFAULT_PGAIN PGAIN_8X +#define DEFAULT_AGAIN AGAIN_1X +#define DEFAULT_PILT 0 // Low proximity threshold +#define DEFAULT_PIHT 50 // High proximity threshold +#define DEFAULT_AILT 0xFFFF // Force interrupt for calibration +#define DEFAULT_AIHT 0 +#define DEFAULT_PERS 0x22 // 2 consecutive prox or ALS for int. + +/* ALS coefficients */ +#define DF 52 +#define GA 0.49 +#define B 1.862 +#define C 0.746 +#define D 1.291 + +/* State definitions */ +enum { + NOTAVAILABLE_STATE, + NEAR_STATE, + FAR_STATE, + ALL_STATE +}; + +#ifdef _AVR_IO_H_ + // Do not use this alias as it's deprecated + #define NA_STATE NOTAVAILABLE_STATE +#endif + +/* APDS9930 Class */ +class APDS9930 { +public: + + /* Initialization methods */ + APDS9930(); + ~APDS9930(); + bool init(); + uint8_t getMode(); + bool setMode(uint8_t mode, uint8_t enable); + + /* Turn the APDS-9930 on and off */ + bool enablePower(); + bool disablePower(); + + /* Enable or disable specific sensors */ + bool enableLightSensor(bool interrupts = false); + bool disableLightSensor(); + bool enableProximitySensor(bool interrupts = false); + bool disableProximitySensor(); + + /* LED drive strength control */ + uint8_t getLEDDrive(); + bool setLEDDrive(uint8_t drive); + // uint8_t getGestureLEDDrive(); + // bool setGestureLEDDrive(uint8_t drive); + + /* Gain control */ + uint8_t getAmbientLightGain(); + bool setAmbientLightGain(uint8_t gain); + uint8_t getProximityGain(); + bool setProximityGain(uint8_t gain); + bool setProximityDiode(uint8_t drive); + uint8_t getProximityDiode(); + + + /* Get and set light interrupt thresholds */ + bool getLightIntLowThreshold(uint16_t &threshold); + bool setLightIntLowThreshold(uint16_t threshold); + bool getLightIntHighThreshold(uint16_t &threshold); + bool setLightIntHighThreshold(uint16_t threshold); + + /* Get and set interrupt enables */ + uint8_t getAmbientLightIntEnable(); + bool setAmbientLightIntEnable(uint8_t enable); + uint8_t getProximityIntEnable(); + bool setProximityIntEnable(uint8_t enable); + + /* Clear interrupts */ + bool clearAmbientLightInt(); + bool clearProximityInt(); + bool clearAllInts(); + + /* Proximity methods */ + bool readProximity(uint16_t &val); + + /* Ambient light methods */ + bool readAmbientLightLux(float &val); + bool readAmbientLightLux(unsigned long &val); + float floatAmbientToLux(uint16_t Ch0, uint16_t Ch1); + unsigned long ulongAmbientToLux(uint16_t Ch0, uint16_t Ch1); + bool readCh0Light(uint16_t &val); + bool readCh1Light(uint16_t &val); + +//private: + + /* Proximity Interrupt Threshold */ + uint16_t getProximityIntLowThreshold(); + bool setProximityIntLowThreshold(uint16_t threshold); + uint16_t getProximityIntHighThreshold(); + bool setProximityIntHighThreshold(uint16_t threshold); + + /* Raw I2C Commands */ + bool wireWriteByte(uint8_t val); + bool wireWriteDataByte(uint8_t reg, uint8_t val); + bool wireWriteDataBlock(uint8_t reg, uint8_t *val, unsigned int len); + bool wireReadDataByte(uint8_t reg, uint8_t &val); + int wireReadDataBlock(uint8_t reg, uint8_t *val, unsigned int len); +}; + +#endif diff --git a/firmware/libraries/Adafruit_APDS9960_Library/Adafruit_APDS9960.cpp b/firmware/libraries/Adafruit_APDS9960_Library/Adafruit_APDS9960.cpp new file mode 100755 index 0000000..8650b33 --- /dev/null +++ b/firmware/libraries/Adafruit_APDS9960_Library/Adafruit_APDS9960.cpp @@ -0,0 +1,726 @@ +/*! + * @file Adafruit_APDS9960.cpp + * + * @mainpage Adafruit APDS9960 Proximity, Light, RGB, and Gesture Sensor + * + * @section author Author + * + * Ladyada, Dean Miller (Adafruit Industries) + * + * @section license License + * + * Software License Agreement (BSD License) + * + * Copyright (c) 2017, Adafruit Industries + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifdef __AVR +#include +#elif defined(ESP8266) +#include +#endif +#include +#include + +#include "Adafruit_APDS9960.h" + +/*! + * @brief Implements missing powf function + * @param x + * Base number + * @param y + * Exponent + * @return x raised to the power of y + */ +float powf(const float x, const float y) { + return (float)(pow((double)x, (double)y)); +} + +/*! + * @brief Enables the device + * Disables the device (putting it in lower power sleep mode) + * @param en + * Enable (True/False) + */ +void Adafruit_APDS9960::enable(boolean en) { + _enable.PON = en; + this->write8(APDS9960_ENABLE, _enable.get()); +} + +/*! + * @brief Initializes I2C and configures the sensor + * @param iTimeMS + * Integration time + * @param aGain + * Gain + * @param addr + * I2C address + * @param *theWire + * Wire object + * @return True if initialization was successful, otherwise false. + */ +boolean Adafruit_APDS9960::begin(uint16_t iTimeMS, apds9960AGain_t aGain, + uint8_t addr, TwoWire *theWire) { + _wire = theWire; + _i2c_init(); + _i2caddr = addr; + + /* Make sure we're actually connected */ + uint8_t x = read8(APDS9960_ID); + if (x != 0xAB) { + return false; + } + + /* Set default integration time and gain */ + setADCIntegrationTime(iTimeMS); + setADCGain(aGain); + + // disable everything to start + enableGesture(false); + enableProximity(false); + enableColor(false); + + disableColorInterrupt(); + disableProximityInterrupt(); + clearInterrupt(); + + /* Note: by default, the device is in power down mode on bootup */ + enable(false); + delay(10); + enable(true); + delay(10); + + // default to all gesture dimensions + setGestureDimensions(APDS9960_DIMENSIONS_ALL); + setGestureFIFOThreshold(APDS9960_GFIFO_4); + setGestureGain(APDS9960_GGAIN_4); + setGestureProximityThreshold(50); + resetCounts(); + + _gpulse.GPLEN = APDS9960_GPULSE_32US; + _gpulse.GPULSE = 9; // 10 pulses + this->write8(APDS9960_GPULSE, _gpulse.get()); + + return true; +} + +/*! + * @brief Sets the integration time for the ADC of the APDS9960, in millis + * @param iTimeMS + * Integration time + */ +void Adafruit_APDS9960::setADCIntegrationTime(uint16_t iTimeMS) { + float temp; + + // convert ms into 2.78ms increments + temp = iTimeMS; + temp /= 2.78; + temp = 256 - temp; + if (temp > 255) + temp = 255; + if (temp < 0) + temp = 0; + + /* Update the timing register */ + write8(APDS9960_ATIME, (uint8_t)temp); +} + +/*! + * @brief Returns the integration time for the ADC of the APDS9960, in millis + * @return Integration time + */ +float Adafruit_APDS9960::getADCIntegrationTime() { + float temp; + + temp = read8(APDS9960_ATIME); + + // convert to units of 2.78 ms + temp = 256 - temp; + temp *= 2.78; + return temp; +} + +/*! + * @brief Adjusts the color/ALS gain on the APDS9960 (adjusts the sensitivity + * to light) + * @param aGain + * Gain + */ +void Adafruit_APDS9960::setADCGain(apds9960AGain_t aGain) { + _control.AGAIN = aGain; + + /* Update the timing register */ + write8(APDS9960_CONTROL, _control.get()); +} + +/*! + * @brief Returns the ADC gain + * @return ADC gain + */ +apds9960AGain_t Adafruit_APDS9960::getADCGain() { + return (apds9960AGain_t)(read8(APDS9960_CONTROL) & 0x03); +} + +/*! + * @brief Adjusts the Proximity gain on the APDS9960 + * @param pGain + * Gain + */ +void Adafruit_APDS9960::setProxGain(apds9960PGain_t pGain) { + _control.PGAIN = pGain; + + /* Update the timing register */ + write8(APDS9960_CONTROL, _control.get()); +} + +/*! + * @brief Returns the Proximity gain on the APDS9960 + * @return Proxmity gain + */ +apds9960PGain_t Adafruit_APDS9960::getProxGain() { + return (apds9960PGain_t)(read8(APDS9960_CONTROL) & 0x0C); +} + +/*! + * @brief Sets number of proxmity pulses + * @param pLen + * Pulse Length + * @param pulses + * Number of pulses + */ +void Adafruit_APDS9960::setProxPulse(apds9960PPulseLen_t pLen, uint8_t pulses) { + if (pulses < 1) + pulses = 1; + if (pulses > 64) + pulses = 64; + pulses--; + + _ppulse.PPLEN = pLen; + _ppulse.PPULSE = pulses; + + write8(APDS9960_PPULSE, _ppulse.get()); +} + +/*! + * @brief Enable proximity readings on APDS9960 + * @param en + * Enable (True/False) + */ +void Adafruit_APDS9960::enableProximity(boolean en) { + _enable.PEN = en; + + write8(APDS9960_ENABLE, _enable.get()); +} + +/*! + * @brief Enable proximity interrupts + */ +void Adafruit_APDS9960::enableProximityInterrupt() { + _enable.PIEN = 1; + write8(APDS9960_ENABLE, _enable.get()); + clearInterrupt(); +} + +/*! + * @brief Disable proximity interrupts + */ +void Adafruit_APDS9960::disableProximityInterrupt() { + _enable.PIEN = 0; + write8(APDS9960_ENABLE, _enable.get()); +} + +/*! + * @brief Set proxmity interrupt thresholds + * @param low + * Low threshold + * @param high + * High threshold + * @param persistance + * Persistance + */ +void Adafruit_APDS9960::setProximityInterruptThreshold(uint8_t low, + uint8_t high, + uint8_t persistance) { + write8(APDS9960_PILT, low); + write8(APDS9960_PIHT, high); + + if (persistance > 7) + persistance = 7; + _pers.PPERS = persistance; + write8(APDS9960_PERS, _pers.get()); +} + +/*! + * @brief Returns proxmity interrupt status + * @return True if enabled, false otherwise. + */ +bool Adafruit_APDS9960::getProximityInterrupt() { + _status.set(this->read8(APDS9960_STATUS)); + return _status.PINT; +}; + +/*! + * @brief Read proximity data + * @return Proximity + */ +uint8_t Adafruit_APDS9960::readProximity() { return read8(APDS9960_PDATA); } + +/*! + * @brief Returns validity status of a gesture + * @return Status (True/False) + */ +bool Adafruit_APDS9960::gestureValid() { + _gstatus.set(this->read8(APDS9960_GSTATUS)); + return _gstatus.GVALID; +} + +/*! + * @brief Sets gesture dimensions + * @param dims + * Dimensions (APDS9960_DIMENSIONS_ALL, APDS9960_DIMENSIONS_UP_DOWM, + * APDS9960_DIMENSIONS_UP_DOWN, APGS9960_DIMENSIONS_LEFT_RIGHT) + */ +void Adafruit_APDS9960::setGestureDimensions(uint8_t dims) { + _gconf3.GDIMS = dims; + this->write8(APDS9960_GCONF3, _gconf3.get()); +} + +/*! + * @brief Sets gesture FIFO Threshold + * @param thresh + * Threshold (APDS9960_GFIFO_1, APDS9960_GFIFO_4, APDS9960_GFIFO_8, + * APDS9960_GFIFO_16) + */ +void Adafruit_APDS9960::setGestureFIFOThreshold(uint8_t thresh) { + _gconf1.GFIFOTH = thresh; + this->write8(APDS9960_GCONF1, _gconf1.get()); +} + +/*! + * @brief Sets gesture sensor gain + * @param gain + * Gain (APDS9960_GAIN_1, APDS9960_GAIN_2, APDS9960_GAIN_4, + * APDS9960_GAIN_8) + */ +void Adafruit_APDS9960::setGestureGain(uint8_t gain) { + _gconf2.GGAIN = gain; + this->write8(APDS9960_GCONF2, _gconf2.get()); +} + +/*! + * @brief Sets gesture sensor threshold + * @param thresh + * Threshold + */ +void Adafruit_APDS9960::setGestureProximityThreshold(uint8_t thresh) { + this->write8(APDS9960_GPENTH, thresh); +} + +/*! + * @brief Sets gesture sensor offset + * @param offset_up + * Up offset + * @param offset_down + * Down offset + * @param offset_left + * Left offset + * @param offset_right + * Right offset + */ +void Adafruit_APDS9960::setGestureOffset(uint8_t offset_up, uint8_t offset_down, + uint8_t offset_left, + uint8_t offset_right) { + this->write8(APDS9960_GOFFSET_U, offset_up); + this->write8(APDS9960_GOFFSET_D, offset_down); + this->write8(APDS9960_GOFFSET_L, offset_left); + this->write8(APDS9960_GOFFSET_R, offset_right); +} + +/*! + * @brief Enable gesture readings on APDS9960 + * @param en + * Enable (True/False) + */ +void Adafruit_APDS9960::enableGesture(boolean en) { + if (!en) { + _gconf4.GMODE = 0; + write8(APDS9960_GCONF4, _gconf4.get()); + } + _enable.GEN = en; + write8(APDS9960_ENABLE, _enable.get()); + resetCounts(); +} + +/*! + * @brief Resets gesture counts + */ +void Adafruit_APDS9960::resetCounts() { + gestCnt = 0; + UCount = 0; + DCount = 0; + LCount = 0; + RCount = 0; +} + +/*! + * @brief Reads gesture + * @return Received gesture (APDS9960_DOWN APDS9960_UP, APDS9960_LEFT + * APDS9960_RIGHT) + */ +uint8_t Adafruit_APDS9960::readGesture() { + uint8_t toRead, bytesRead; + uint8_t buf[256]; + unsigned long t = 0; + uint8_t gestureReceived; + while (1) { + int up_down_diff = 0; + int left_right_diff = 0; + gestureReceived = 0; + if (!gestureValid()) + return 0; + + delay(30); + toRead = this->read8(APDS9960_GFLVL); + + // bytesRead is unused but produces sideffects needed for readGesture to work + bytesRead = this->read(APDS9960_GFIFO_U, buf, toRead); + + if (abs((int)buf[0] - (int)buf[1]) > 13) + up_down_diff += (int)buf[0] - (int)buf[1]; + + if (abs((int)buf[2] - (int)buf[3]) > 13) + left_right_diff += (int)buf[2] - (int)buf[3]; + + if (up_down_diff != 0) { + if (up_down_diff < 0) { + if (DCount > 0) { + gestureReceived = APDS9960_UP; + } else + UCount++; + } else if (up_down_diff > 0) { + if (UCount > 0) { + gestureReceived = APDS9960_DOWN; + } else + DCount++; + } + } + + if (left_right_diff != 0) { + if (left_right_diff < 0) { + if (RCount > 0) { + gestureReceived = APDS9960_LEFT; + } else + LCount++; + } else if (left_right_diff > 0) { + if (LCount > 0) { + gestureReceived = APDS9960_RIGHT; + } else + RCount++; + } + } + + if (up_down_diff != 0 || left_right_diff != 0) + t = millis(); + + if (gestureReceived || millis() - t > 300) { + resetCounts(); + return gestureReceived; + } + } +} + +/*! + * @brief Set LED brightness for proximity/gesture + * @param drive + * LED Drive + * @param boost + * LED Boost + */ +void Adafruit_APDS9960::setLED(apds9960LedDrive_t drive, + apds9960LedBoost_t boost) { + // set BOOST + _config2.LED_BOOST = boost; + write8(APDS9960_CONFIG2, _config2.get()); + + _control.LDRIVE = drive; + write8(APDS9960_CONTROL, _control.get()); +} + +/*! + * @brief Enable proximity readings on APDS9960 + * @param en + * Enable (True/False) + */ +void Adafruit_APDS9960::enableColor(boolean en) { + _enable.AEN = en; + write8(APDS9960_ENABLE, _enable.get()); +} + +/*! + * @brief Returns status of color data + * @return True if color data ready, False otherwise + */ +bool Adafruit_APDS9960::colorDataReady() { + _status.set(this->read8(APDS9960_STATUS)); + return _status.AVALID; +} + +/*! + * @brief Reads the raw red, green, blue and clear channel values + * @param *r + * Red value + * @param *g + * Green value + * @param *b + * Blue value + * @param *c + * Clear channel value + */ +void Adafruit_APDS9960::getColorData(uint16_t *r, uint16_t *g, uint16_t *b, + uint16_t *c) { + + *c = read16R(APDS9960_CDATAL); + *r = read16R(APDS9960_RDATAL); + *g = read16R(APDS9960_GDATAL); + *b = read16R(APDS9960_BDATAL); +} + +/*! + * @brief Converts the raw R/G/B values to color temperature in degrees Kelvin + * @param r + * Red value + * @param g + * Green value + * @param b + * Blue value + * @return Color temperature + */ +uint16_t Adafruit_APDS9960::calculateColorTemperature(uint16_t r, uint16_t g, + uint16_t b) { + float X, Y, Z; /* RGB to XYZ correlation */ + float xc, yc; /* Chromaticity co-ordinates */ + float n; /* McCamy's formula */ + float cct; + + /* 1. Map RGB values to their XYZ counterparts. */ + /* Based on 6500K fluorescent, 3000K fluorescent */ + /* and 60W incandescent values for a wide range. */ + /* Note: Y = Illuminance or lux */ + X = (-0.14282F * r) + (1.54924F * g) + (-0.95641F * b); + Y = (-0.32466F * r) + (1.57837F * g) + (-0.73191F * b); + Z = (-0.68202F * r) + (0.77073F * g) + (0.56332F * b); + + /* 2. Calculate the chromaticity co-ordinates */ + xc = (X) / (X + Y + Z); + yc = (Y) / (X + Y + Z); + + /* 3. Use McCamy's formula to determine the CCT */ + n = (xc - 0.3320F) / (0.1858F - yc); + + /* Calculate the final CCT */ + cct = + (449.0F * powf(n, 3)) + (3525.0F * powf(n, 2)) + (6823.3F * n) + 5520.33F; + + /* Return the results in degrees Kelvin */ + return (uint16_t)cct; +} + +/*! + * @brief Calculate ambient light values + * @param r + * Red value + * @param g + * Green value + * @param b + * Blue value + * @return LUX value + */ +uint16_t Adafruit_APDS9960::calculateLux(uint16_t r, uint16_t g, uint16_t b) { + float illuminance; + + /* This only uses RGB ... how can we integrate clear or calculate lux */ + /* based exclusively on clear since this might be more reliable? */ + illuminance = (-0.32466F * r) + (1.57837F * g) + (-0.73191F * b); + + return (uint16_t)illuminance; +} + +/*! + * @brief Enables color interrupt + */ +void Adafruit_APDS9960::enableColorInterrupt() { + _enable.AIEN = 1; + write8(APDS9960_ENABLE, _enable.get()); +} + +/*! + * @brief Disables color interrupt + */ +void Adafruit_APDS9960::disableColorInterrupt() { + _enable.AIEN = 0; + write8(APDS9960_ENABLE, _enable.get()); +} + +/*! + * @brief Clears interrupt + */ +void Adafruit_APDS9960::clearInterrupt() { + this->write(APDS9960_AICLEAR, NULL, 0); +} + +/*! + * @brief Sets interrupt limits + * @param low + * Low limit + * @param high + * High limit + */ +void Adafruit_APDS9960::setIntLimits(uint16_t low, uint16_t high) { + write8(APDS9960_AILTIL, low & 0xFF); + write8(APDS9960_AILTH, low >> 8); + write8(APDS9960_AIHTL, high & 0xFF); + write8(APDS9960_AIHTH, high >> 8); +} + +/*! + * @brief Writes specified value to given register + * @param reg + * Register to write to + * @param value + * Value to write + */ +void Adafruit_APDS9960::write8(byte reg, byte value) { + this->write(reg, &value, 1); +} + +/*! + * @brief Reads 8 bits from specified register + * @param reg + * Register to write to + * @return Value in register + */ +uint8_t Adafruit_APDS9960::read8(byte reg) { + uint8_t ret; + this->read(reg, &ret, 1); + + return ret; +} + +/*! + * @brief Reads 32 bits from specified register + * @param reg + * Register to write to + * @return Value in register + */ +uint32_t Adafruit_APDS9960::read32(uint8_t reg) { + uint8_t ret[4]; + this->read(reg, ret, 4); + + return (ret[0] << 24) | (ret[1] << 16) | (ret[2] << 8) | ret[3]; +} + +/*! + * @brief Reads 16 bites from specified register + * @param reg + * Register to write to + * @return Value in register + */ +uint16_t Adafruit_APDS9960::read16(uint8_t reg) { + uint8_t ret[2]; + this->read(reg, ret, 2); + + return (ret[0] << 8) | ret[1]; +} + +/*! + * @brief Reads 16 bites from specified register + * @param reg + * Register to write to + * @return Value in register + */ +uint16_t Adafruit_APDS9960::read16R(uint8_t reg) { + uint8_t ret[2]; + this->read(reg, ret, 2); + + return (ret[1] << 8) | ret[0]; +} + +/*! + * @brief Begins I2C communication + */ +void Adafruit_APDS9960::_i2c_init() { _wire->begin(); } + +/*! + * @brief Reads num bytes from specified register into a given buffer + * @param reg + * Register + * @param *buf + * Buffer + * @param num + * Number of bytes + * @return Position after reading + */ +uint8_t Adafruit_APDS9960::read(uint8_t reg, uint8_t *buf, uint8_t num) { + uint8_t pos = 0; + bool eof = false; + + // on arduino we need to read in 32 byte chunks + while (pos < num && !eof) { + + uint8_t read_now = min(32, num - pos); + _wire->beginTransmission((uint8_t)_i2caddr); + _wire->write((uint8_t)reg + pos); + _wire->endTransmission(); + + _wire->requestFrom((uint8_t)_i2caddr, read_now); + + for (int i = 0; i < read_now; i++) { + if (!_wire->available()) { + eof = true; + break; + } + buf[pos] = _wire->read(); + pos++; + } + } + return pos; +} + +/*! + * @brief Writes num bytes from specified buffer into a given register + * @param reg + * Register + * @param *buf + * Buffer + * @param num + * Number of bytes + */ +void Adafruit_APDS9960::write(uint8_t reg, uint8_t *buf, uint8_t num) { + _wire->beginTransmission((uint8_t)_i2caddr); + _wire->write((uint8_t)reg); + _wire->write((uint8_t *)buf, num); + _wire->endTransmission(); +} diff --git a/firmware/libraries/Adafruit_APDS9960_Library/Adafruit_APDS9960.h b/firmware/libraries/Adafruit_APDS9960_Library/Adafruit_APDS9960.h new file mode 100755 index 0000000..1ba957d --- /dev/null +++ b/firmware/libraries/Adafruit_APDS9960_Library/Adafruit_APDS9960.h @@ -0,0 +1,531 @@ +/*! + * @file Adafruit_APDS9960.h + * + * Software License Agreement (BSD License) + * + * Copyright (c) 2017, Adafruit Industries + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _APDS9960_H_ +#define _APDS9960_H_ + +#include +#include + +#define APDS9960_ADDRESS (0x39) /**< I2C Address */ + +/** I2C Registers */ +enum { + APDS9960_RAM = 0x00, + APDS9960_ENABLE = 0x80, + APDS9960_ATIME = 0x81, + APDS9960_WTIME = 0x83, + APDS9960_AILTIL = 0x84, + APDS9960_AILTH = 0x85, + APDS9960_AIHTL = 0x86, + APDS9960_AIHTH = 0x87, + APDS9960_PILT = 0x89, + APDS9960_PIHT = 0x8B, + APDS9960_PERS = 0x8C, + APDS9960_CONFIG1 = 0x8D, + APDS9960_PPULSE = 0x8E, + APDS9960_CONTROL = 0x8F, + APDS9960_CONFIG2 = 0x90, + APDS9960_ID = 0x92, + APDS9960_STATUS = 0x93, + APDS9960_CDATAL = 0x94, + APDS9960_CDATAH = 0x95, + APDS9960_RDATAL = 0x96, + APDS9960_RDATAH = 0x97, + APDS9960_GDATAL = 0x98, + APDS9960_GDATAH = 0x99, + APDS9960_BDATAL = 0x9A, + APDS9960_BDATAH = 0x9B, + APDS9960_PDATA = 0x9C, + APDS9960_POFFSET_UR = 0x9D, + APDS9960_POFFSET_DL = 0x9E, + APDS9960_CONFIG3 = 0x9F, + APDS9960_GPENTH = 0xA0, + APDS9960_GEXTH = 0xA1, + APDS9960_GCONF1 = 0xA2, + APDS9960_GCONF2 = 0xA3, + APDS9960_GOFFSET_U = 0xA4, + APDS9960_GOFFSET_D = 0xA5, + APDS9960_GOFFSET_L = 0xA7, + APDS9960_GOFFSET_R = 0xA9, + APDS9960_GPULSE = 0xA6, + APDS9960_GCONF3 = 0xAA, + APDS9960_GCONF4 = 0xAB, + APDS9960_GFLVL = 0xAE, + APDS9960_GSTATUS = 0xAF, + APDS9960_IFORCE = 0xE4, + APDS9960_PICLEAR = 0xE5, + APDS9960_CICLEAR = 0xE6, + APDS9960_AICLEAR = 0xE7, + APDS9960_GFIFO_U = 0xFC, + APDS9960_GFIFO_D = 0xFD, + APDS9960_GFIFO_L = 0xFE, + APDS9960_GFIFO_R = 0xFF, +}; + +/** ADC gain settings */ +typedef enum { + APDS9960_AGAIN_1X = 0x00, /**< No gain */ + APDS9960_AGAIN_4X = 0x01, /**< 2x gain */ + APDS9960_AGAIN_16X = 0x02, /**< 16x gain */ + APDS9960_AGAIN_64X = 0x03 /**< 64x gain */ +} apds9960AGain_t; + +/** Proxmity gain settings */ +typedef enum { + APDS9960_PGAIN_1X = 0x00, /**< 1x gain */ + APDS9960_PGAIN_2X = 0x04, /**< 2x gain */ + APDS9960_PGAIN_4X = 0x08, /**< 4x gain */ + APDS9960_PGAIN_8X = 0x0C /**< 8x gain */ +} apds9960PGain_t; + +/** Pulse length settings */ +typedef enum { + APDS9960_PPULSELEN_4US = 0x00, /**< 4uS */ + APDS9960_PPULSELEN_8US = 0x40, /**< 8uS */ + APDS9960_PPULSELEN_16US = 0x80, /**< 16uS */ + APDS9960_PPULSELEN_32US = 0xC0 /**< 32uS */ +} apds9960PPulseLen_t; + +/** LED drive settings */ +typedef enum { + APDS9960_LEDDRIVE_100MA = 0x00, /**< 100mA */ + APDS9960_LEDDRIVE_50MA = 0x40, /**< 50mA */ + APDS9960_LEDDRIVE_25MA = 0x80, /**< 25mA */ + APDS9960_LEDDRIVE_12MA = 0xC0 /**< 12.5mA */ +} apds9960LedDrive_t; + +/** LED boost settings */ +typedef enum { + APDS9960_LEDBOOST_100PCNT = 0x00, /**< 100% */ + APDS9960_LEDBOOST_150PCNT = 0x10, /**< 150% */ + APDS9960_LEDBOOST_200PCNT = 0x20, /**< 200% */ + APDS9960_LEDBOOST_300PCNT = 0x30 /**< 300% */ +} apds9960LedBoost_t; + +/** Dimensions */ +enum { + APDS9960_DIMENSIONS_ALL = 0x00, // All dimensions + APDS9960_DIMENSIONS_UP_DOWN = 0x01, // Up/Down dimensions + APGS9960_DIMENSIONS_LEFT_RIGHT = 0x02, // Left/Right dimensions +}; + +/** FIFO Interrupts */ +enum { + APDS9960_GFIFO_1 = 0x00, // Generate interrupt after 1 dataset in FIFO + APDS9960_GFIFO_4 = 0x01, // Generate interrupt after 2 datasets in FIFO + APDS9960_GFIFO_8 = 0x02, // Generate interrupt after 3 datasets in FIFO + APDS9960_GFIFO_16 = 0x03, // Generate interrupt after 4 datasets in FIFO +}; + +/** Gesture Gain */ +enum { + APDS9960_GGAIN_1 = 0x00, // Gain 1x + APDS9960_GGAIN_2 = 0x01, // Gain 2x + APDS9960_GGAIN_4 = 0x02, // Gain 4x + APDS9960_GGAIN_8 = 0x03, // Gain 8x +}; + +/** Pulse Lenghts */ +enum { + APDS9960_GPULSE_4US = 0x00, // Pulse 4us + APDS9960_GPULSE_8US = 0x01, // Pulse 8us + APDS9960_GPULSE_16US = 0x02, // Pulse 16us + APDS9960_GPULSE_32US = 0x03, // Pulse 32us +}; + +#define APDS9960_UP 0x01 /**< Gesture Up */ +#define APDS9960_DOWN 0x02 /**< Gesture Down */ +#define APDS9960_LEFT 0x03 /**< Gesture Left */ +#define APDS9960_RIGHT 0x04 /**< Gesture Right */ + +/*! + * @brief Class that stores state and functions for interacting with + * APDS9960 Sensor + */ +class Adafruit_APDS9960 { +public: + Adafruit_APDS9960(){}; + ~Adafruit_APDS9960(){}; + + boolean begin(uint16_t iTimeMS = 10, apds9960AGain_t = APDS9960_AGAIN_4X, + uint8_t addr = APDS9960_ADDRESS, TwoWire *theWire = &Wire); + void setADCIntegrationTime(uint16_t iTimeMS); + float getADCIntegrationTime(); + void setADCGain(apds9960AGain_t gain); + apds9960AGain_t getADCGain(); + void setLED(apds9960LedDrive_t drive, apds9960LedBoost_t boost); + + // proximity + void enableProximity(boolean en = true); + void setProxGain(apds9960PGain_t gain); + apds9960PGain_t getProxGain(); + void setProxPulse(apds9960PPulseLen_t pLen, uint8_t pulses); + void enableProximityInterrupt(); + void disableProximityInterrupt(); + uint8_t readProximity(); + void setProximityInterruptThreshold(uint8_t low, uint8_t high, + uint8_t persistance = 4); + bool getProximityInterrupt(); + + // gesture + void enableGesture(boolean en = true); + bool gestureValid(); + void setGestureDimensions(uint8_t dims); + void setGestureFIFOThreshold(uint8_t thresh); + void setGestureGain(uint8_t gain); + void setGestureProximityThreshold(uint8_t thresh); + void setGestureOffset(uint8_t offset_up, uint8_t offset_down, + uint8_t offset_left, uint8_t offset_right); + uint8_t readGesture(); + void resetCounts(); + + // light & color + void enableColor(boolean en = true); + bool colorDataReady(); + void getColorData(uint16_t *r, uint16_t *g, uint16_t *b, uint16_t *c); + uint16_t calculateColorTemperature(uint16_t r, uint16_t g, uint16_t b); + uint16_t calculateLux(uint16_t r, uint16_t g, uint16_t b); + void enableColorInterrupt(); + void disableColorInterrupt(); + void clearInterrupt(); + void setIntLimits(uint16_t l, uint16_t h); + + // turn on/off elements + void enable(boolean en = true); + +private: + uint8_t _i2caddr; + TwoWire *_wire; + + uint32_t read32(uint8_t reg); + uint16_t read16(uint8_t reg); + uint16_t read16R(uint8_t reg); + + void write8(byte reg, byte value); + uint8_t read8(byte reg); + + uint8_t gestCnt; + + uint8_t UCount; + uint8_t DCount; + + uint8_t LCount; + uint8_t RCount; + + uint8_t read(uint8_t reg, uint8_t *buf, uint8_t num); + void write(uint8_t reg, uint8_t *buf, uint8_t num); + void _i2c_init(); + + struct enable { + + // power on + uint8_t PON : 1; + + // ALS enable + uint8_t AEN : 1; + + // Proximity detect enable + uint8_t PEN : 1; + + // wait timer enable + uint8_t WEN : 1; + + // ALS interrupt enable + uint8_t AIEN : 1; + + // proximity interrupt enable + uint8_t PIEN : 1; + + // gesture enable + uint8_t GEN : 1; + + uint8_t get() { + return (GEN << 6) | (PIEN << 5) | (AIEN << 4) | (WEN << 3) | (PEN << 2) | + (AEN << 1) | PON; + }; + }; + struct enable _enable; + + struct pers { + // ALS Interrupt Persistence. Controls rate of Clear channel interrupt to + // the host processor + uint8_t APERS : 4; + + // proximity interrupt persistence, controls rate of prox interrupt to host + // processor + uint8_t PPERS : 4; + + uint8_t get() { return (PPERS << 4) | APERS; }; + }; + pers _pers; + + struct config1 { + uint8_t WLONG : 1; + + uint8_t get() { return WLONG << 1; }; + }; + config1 _config1; + + struct ppulse { + + /*Proximity Pulse Count. Specifies the number of proximity pulses to be + generated on LDR. Number of pulses is set by PPULSE value plus 1. + */ + uint8_t PPULSE : 6; + + // Proximity Pulse Length. Sets the LED-ON pulse width during a proximity + // LDR pulse. + uint8_t PPLEN : 2; + + uint8_t get() { return (PPLEN << 6) | PPULSE; } + }; + ppulse _ppulse; + + struct control { + // ALS and Color gain control + uint8_t AGAIN : 2; + + // proximity gain control + uint8_t PGAIN : 2; + + // led drive strength + uint8_t LDRIVE : 2; + + uint8_t get() { return (LDRIVE << 6) | (PGAIN << 2) | AGAIN; } + }; + control _control; + + struct config2 { + /* Additional LDR current during proximity and gesture LED pulses. Current + value, set by LDRIVE, is increased by the percentage of LED_BOOST. + */ + uint8_t LED_BOOST : 2; + + // clear photodiode saturation int enable + uint8_t CPSIEN : 1; + + // proximity saturation interrupt enable + uint8_t PSIEN : 1; + + uint8_t get() { + return (PSIEN << 7) | (CPSIEN << 6) | (LED_BOOST << 4) | 1; + } + }; + config2 _config2; + + struct status { + /* ALS Valid. Indicates that an ALS cycle has completed since AEN was + asserted or since a read from any of the ALS/Color data registers. + */ + uint8_t AVALID : 1; + + /* Proximity Valid. Indicates that a proximity cycle has completed since PEN + was asserted or since PDATA was last read. A read of PDATA automatically + clears PVALID. + */ + uint8_t PVALID : 1; + + /* Gesture Interrupt. GINT is asserted when GFVLV becomes greater than + GFIFOTH or if GVALID has become asserted when GMODE transitioned to zero. + The bit is reset when FIFO is completely emptied (read). + */ + uint8_t GINT : 1; + + // ALS Interrupt. This bit triggers an interrupt if AIEN in ENABLE is set. + uint8_t AINT : 1; + + // Proximity Interrupt. This bit triggers an interrupt if PIEN in ENABLE is + // set. + uint8_t PINT : 1; + + /* Indicates that an analog saturation event occurred during a previous + proximity or gesture cycle. Once set, this bit remains set until cleared by + clear proximity interrupt special function command (0xE5 PICLEAR) or by + disabling Prox (PEN=0). This bit triggers an interrupt if PSIEN is set. + */ + uint8_t PGSAT : 1; + + /* Clear Photodiode Saturation. When asserted, the analog sensor was at the + upper end of its dynamic range. The bit can be de-asserted by sending a + Clear channel interrupt command (0xE6 CICLEAR) or by disabling the ADC + (AEN=0). This bit triggers an interrupt if CPSIEN is set. + */ + uint8_t CPSAT : 1; + + void set(uint8_t data) { + AVALID = data & 0x01; + PVALID = (data >> 1) & 0x01; + GINT = (data >> 2) & 0x01; + AINT = (data >> 4) & 0x01; + PINT = (data >> 5) & 0x01; + PGSAT = (data >> 6) & 0x01; + CPSAT = (data >> 7) & 0x01; + } + }; + status _status; + + struct config3 { + // proximity mask + uint8_t PMASK_R : 1; + uint8_t PMASK_L : 1; + uint8_t PMASK_D : 1; + uint8_t PMASK_U : 1; + + /* Sleep After Interrupt. When enabled, the device will automatically enter + low power mode when the INT pin is asserted and the state machine has + progressed to the SAI decision block. Normal operation is resumed when INT + pin is cleared over I2C. + */ + uint8_t SAI : 1; + + /* Proximity Gain Compensation Enable. This bit provides gain compensation + when proximity photodiode signal is reduced as a result of sensor masking. + If only one diode of the diode pair is contributing, then only half of the + signal is available at the ADC; this results in a maximum ADC value of 127. + Enabling PCMP enables an additional gain of 2X, resulting in a maximum ADC + value of 255. + */ + uint8_t PCMP : 1; + + uint8_t get() { + return (PCMP << 5) | (SAI << 4) | (PMASK_U << 3) | (PMASK_D << 2) | + (PMASK_L << 1) | PMASK_R; + } + }; + config3 _config3; + + struct gconf1 { + /* Gesture Exit Persistence. When a number of consecutive “gesture end” + occurrences become equal or greater to the GEPERS value, the Gesture state + machine is exited. + */ + uint8_t GEXPERS : 2; + + /* Gesture Exit Mask. Controls which of the gesture detector photodiodes + (UDLR) will be included to determine a “gesture end” and subsequent exit + of the gesture state machine. Unmasked UDLR data will be compared with the + value in GTHR_OUT. Field value bits correspond to UDLR detectors. + */ + uint8_t GEXMSK : 4; + + /* Gesture FIFO Threshold. This value is compared with the FIFO Level (i.e. + the number of UDLR datasets) to generate an interrupt (if enabled). + */ + uint8_t GFIFOTH : 2; + + uint8_t get() { return (GFIFOTH << 6) | (GEXMSK << 2) | GEXPERS; } + }; + gconf1 _gconf1; + + struct gconf2 { + /* Gesture Wait Time. The GWTIME controls the amount of time in a low power + mode between gesture detection cycles. + */ + uint8_t GWTIME : 3; + + // Gesture LED Drive Strength. Sets LED Drive Strength in gesture mode. + uint8_t GLDRIVE : 2; + + // Gesture Gain Control. Sets the gain of the proximity receiver in gesture + // mode. + uint8_t GGAIN : 2; + + uint8_t get() { return (GGAIN << 5) | (GLDRIVE << 3) | GWTIME; } + }; + gconf2 _gconf2; + + struct gpulse { + /* Number of Gesture Pulses. Specifies the number of pulses to be generated + on LDR. Number of pulses is set by GPULSE value plus 1. + */ + uint8_t GPULSE : 6; + + // Gesture Pulse Length. Sets the LED_ON pulse width during a Gesture LDR + // Pulse. + uint8_t GPLEN : 2; + + uint8_t get() { return (GPLEN << 6) | GPULSE; } + }; + gpulse _gpulse; + + struct gconf3 { + /* Gesture Dimension Select. Selects which gesture photodiode pairs are + enabled to gather results during gesture. + */ + uint8_t GDIMS : 2; + + uint8_t get() { return GDIMS; } + }; + gconf3 _gconf3; + + struct gconf4 { + /* Gesture Mode. Reading this bit reports if the gesture state machine is + actively running, 1 = Gesture, 0= ALS, Proximity, Color. Writing a 1 to this + bit causes immediate entry in to the gesture state machine (as if GPENTH had + been exceeded). Writing a 0 to this bit causes exit of gesture when current + analog conversion has finished (as if GEXTH had been exceeded). + */ + uint8_t GMODE : 1; + + /* Gesture interrupt enable. Gesture Interrupt Enable. When asserted, all + gesture related interrupts are unmasked. + */ + uint8_t GIEN : 2; + + uint8_t get() { return (GIEN << 1) | GMODE; } + void set(uint8_t data) { + GIEN = (data >> 1) & 0x01; + GMODE = data & 0x01; + } + }; + gconf4 _gconf4; + + struct gstatus { + /* Gesture FIFO Data. GVALID bit is sent when GFLVL becomes greater than + GFIFOTH (i.e. FIFO has enough data to set GINT). GFIFOD is reset when GMODE + = 0 and the GFLVL=0 (i.e. All FIFO data has been read). + */ + uint8_t GVALID : 1; + + /* Gesture FIFO Overflow. A setting of 1 indicates that the FIFO has filled + to capacity and that new gesture detector data has been lost. + */ + uint8_t GFOV : 1; + + void set(uint8_t data) { + GFOV = (data >> 1) & 0x01; + GVALID = data & 0x01; + } + }; + gstatus _gstatus; +}; + +#endif diff --git a/firmware/libraries/Adafruit_APDS9960_Library/README.md b/firmware/libraries/Adafruit_APDS9960_Library/README.md new file mode 100755 index 0000000..b115d7c --- /dev/null +++ b/firmware/libraries/Adafruit_APDS9960_Library/README.md @@ -0,0 +1,18 @@ +# Adafruit APDS9960 Library [![Build Status](https://travis-ci.com/adafruit/Adafruit_APDS9960.svg?branch=master)](https://travis-ci.com/adafruit/Adafruit_APDS9960) + + + +This is the Adafruit APDS9960 Proximity, Light, RGB, and Gesture sensor Library + +Tested and works great with the Adafruit APDS9960 Board +* http://www.adafruit.com/products/3595 + +This chip uses I2C to communicate, 2 pins are required to interface + +Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! + +Written by Dean Miller, Limor Fried for Adafruit Industries. +BSD license, check license.txt for more information +All text above must be included in any redistribution + +To install, use the Arduino Library Manager and search for "Adafruit APDS9960 Library" and install the library. diff --git a/firmware/libraries/Adafruit_APDS9960_Library/assets/board.jpg b/firmware/libraries/Adafruit_APDS9960_Library/assets/board.jpg new file mode 100755 index 0000000..dafb0d3 Binary files /dev/null and b/firmware/libraries/Adafruit_APDS9960_Library/assets/board.jpg differ diff --git a/firmware/libraries/Adafruit_APDS9960_Library/code-of-conduct.md b/firmware/libraries/Adafruit_APDS9960_Library/code-of-conduct.md new file mode 100755 index 0000000..8ee6e44 --- /dev/null +++ b/firmware/libraries/Adafruit_APDS9960_Library/code-of-conduct.md @@ -0,0 +1,127 @@ +# Adafruit Community Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and leaders pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level or type of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +We are committed to providing a friendly, safe and welcoming environment for +all. + +Examples of behavior that contributes to creating a positive environment +include: + +* Be kind and courteous to others +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Collaborating with other community members +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and sexual attention or advances +* The use of inappropriate images, including in a community member's avatar +* The use of inappropriate language, including in a community member's nickname +* Any spamming, flaming, baiting or other attention-stealing behavior +* Excessive or unwelcome helping; answering outside the scope of the question + asked +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate + +The goal of the standards and moderation guidelines outlined here is to build +and maintain a respectful community. We ask that you don’t just aim to be +"technically unimpeachable", but rather try to be your best self. + +We value many things beyond technical expertise, including collaboration and +supporting others within our community. Providing a positive experience for +other community members can have a much more significant impact than simply +providing the correct answer. + +## Our Responsibilities + +Project leaders are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project leaders have the right and responsibility to remove, edit, or +reject messages, comments, commits, code, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any community member for other behaviors that they deem +inappropriate, threatening, offensive, or harmful. + +## Moderation + +Instances of behaviors that violate the Adafruit Community Code of Conduct +may be reported by any member of the community. Community members are +encouraged to report these situations, including situations they witness +involving other community members. + +You may report in the following ways: + +In any situation, you may send an email to . + +On the Adafruit Discord, you may send an open message from any channel +to all Community Helpers by tagging @community helpers. You may also send an +open message from any channel, or a direct message to @kattni#1507, +@tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or +@Andon#8175. + +Email and direct message reports will be kept confidential. + +In situations on Discord where the issue is particularly egregious, possibly +illegal, requires immediate action, or violates the Discord terms of service, +you should also report the message directly to Discord. + +These are the steps for upholding our community’s standards of conduct. + +1. Any member of the community may report any situation that violates the +Adafruit Community Code of Conduct. All reports will be reviewed and +investigated. +2. If the behavior is an egregious violation, the community member who +committed the violation may be banned immediately, without warning. +3. Otherwise, moderators will first respond to such behavior with a warning. +4. Moderators follow a soft "three strikes" policy - the community member may +be given another chance, if they are receptive to the warning and change their +behavior. +5. If the community member is unreceptive or unreasonable when warned by a +moderator, or the warning goes unheeded, they may be banned for a first or +second offense. Repeated offenses will result in the community member being +banned. + +## Scope + +This Code of Conduct and the enforcement policies listed above apply to all +Adafruit Community venues. This includes but is not limited to any community +spaces (both public and private), the entire Adafruit Discord server, and +Adafruit GitHub repositories. Examples of Adafruit Community spaces include +but are not limited to meet-ups, audio chats on the Adafruit Discord, or +interaction at a conference. + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. As a community +member, you are representing our community, and are expected to behave +accordingly. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.4, available at +, +and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). + +For other projects adopting the Adafruit Community Code of +Conduct, please contact the maintainers of those projects for enforcement. +If you wish to use this code of conduct for your own project, consider +explicitly mentioning your moderation policy or making a copy with your +own moderation policy so as to avoid confusion. diff --git a/firmware/libraries/Adafruit_APDS9960_Library/examples/color_sensor/color_sensor.ino b/firmware/libraries/Adafruit_APDS9960_Library/examples/color_sensor/color_sensor.ino new file mode 100755 index 0000000..938394f --- /dev/null +++ b/firmware/libraries/Adafruit_APDS9960_Library/examples/color_sensor/color_sensor.ino @@ -0,0 +1,59 @@ +/*************************************************************************** + This is a library for the APDS9960 digital proximity, ambient light, RGB, and gesture sensor + + This sketch puts the sensor in color mode and reads the RGB and clear values. + + Designed specifically to work with the Adafruit APDS9960 breakout + ----> http://www.adafruit.com/products/3595 + + These sensors use I2C to communicate. The device's I2C address is 0x39 + + Adafruit invests time and resources providing this open source code, + please support Adafruit andopen-source hardware by purchasing products + from Adafruit! + + Written by Dean Miller for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ***************************************************************************/ + +#include "Adafruit_APDS9960.h" +Adafruit_APDS9960 apds; + +void setup() { + Serial.begin(115200); + + if(!apds.begin()){ + Serial.println("failed to initialize device! Please check your wiring."); + } + else Serial.println("Device initialized!"); + + //enable color sensign mode + apds.enableColor(true); +} + +void loop() { + //create some variables to store the color data in + uint16_t r, g, b, c; + + //wait for color data to be ready + while(!apds.colorDataReady()){ + delay(5); + } + + //get the data and print the different channels + apds.getColorData(&r, &g, &b, &c); + Serial.print("red: "); + Serial.print(r); + + Serial.print(" green: "); + Serial.print(g); + + Serial.print(" blue: "); + Serial.print(b); + + Serial.print(" clear: "); + Serial.println(c); + Serial.println(); + + delay(500); +} \ No newline at end of file diff --git a/firmware/libraries/Adafruit_APDS9960_Library/examples/gesture_sensor/gesture_sensor.ino b/firmware/libraries/Adafruit_APDS9960_Library/examples/gesture_sensor/gesture_sensor.ino new file mode 100755 index 0000000..fcbfa1e --- /dev/null +++ b/firmware/libraries/Adafruit_APDS9960_Library/examples/gesture_sensor/gesture_sensor.ino @@ -0,0 +1,47 @@ +/*************************************************************************** + This is a library for the APDS9960 digital proximity, ambient light, RGB, and gesture sensor + + This sketch puts the sensor in gesture mode and decodes gestures. + To use this, first put your hand close to the sensor to enable gesture mode. + Then move your hand about 6" from the sensor in the up -> down, down -> up, + left -> right, or right -> left direction. + + Designed specifically to work with the Adafruit APDS9960 breakout + ----> http://www.adafruit.com/products/3595 + + These sensors use I2C to communicate. The device's I2C address is 0x39 + + Adafruit invests time and resources providing this open source code, + please support Adafruit andopen-source hardware by purchasing products + from Adafruit! + + Written by Dean Miller for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ***************************************************************************/ + +#include "Adafruit_APDS9960.h" +Adafruit_APDS9960 apds; + +// the setup function runs once when you press reset or power the board +void setup() { + Serial.begin(115200); + + if(!apds.begin()){ + Serial.println("failed to initialize device! Please check your wiring."); + } + else Serial.println("Device initialized!"); + + //gesture mode will be entered once proximity mode senses something close + apds.enableProximity(true); + apds.enableGesture(true); +} + +// the loop function runs over and over again forever +void loop() { + //read a gesture from the device + uint8_t gesture = apds.readGesture(); + if(gesture == APDS9960_DOWN) Serial.println("v"); + if(gesture == APDS9960_UP) Serial.println("^"); + if(gesture == APDS9960_LEFT) Serial.println("<"); + if(gesture == APDS9960_RIGHT) Serial.println(">"); +} \ No newline at end of file diff --git a/firmware/libraries/Adafruit_APDS9960_Library/examples/proximity_sensor/proximity_sensor.ino b/firmware/libraries/Adafruit_APDS9960_Library/examples/proximity_sensor/proximity_sensor.ino new file mode 100755 index 0000000..61cbadd --- /dev/null +++ b/firmware/libraries/Adafruit_APDS9960_Library/examples/proximity_sensor/proximity_sensor.ino @@ -0,0 +1,56 @@ +/*************************************************************************** + This is a library for the APDS9960 digital proximity, ambient light, RGB, and gesture sensor + + This sketch puts the sensor in proximity mode and enables the interrupt + to fire when proximity goes over a set value + + Designed specifically to work with the Adafruit APDS9960 breakout + ----> http://www.adafruit.com/products/3595 + + These sensors use I2C to communicate. The device's I2C address is 0x39 + + Adafruit invests time and resources providing this open source code, + please support Adafruit andopen-source hardware by purchasing products + from Adafruit! + + Written by Dean Miller for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ***************************************************************************/ + +#include "Adafruit_APDS9960.h" + +//the pin that the interrupt is attached to +#define INT_PIN 3 + +//create the APDS9960 object +Adafruit_APDS9960 apds; + +void setup() { + Serial.begin(115200); + pinMode(INT_PIN, INPUT_PULLUP); + + if(!apds.begin()){ + Serial.println("failed to initialize device! Please check your wiring."); + } + else Serial.println("Device initialized!"); + + //enable proximity mode + apds.enableProximity(true); + + //set the interrupt threshold to fire when proximity reading goes above 175 + apds.setProximityInterruptThreshold(0, 175); + + //enable the proximity interrupt + apds.enableProximityInterrupt(); +} + +void loop() { + + //print the proximity reading when the interrupt pin goes low + if(!digitalRead(INT_PIN)){ + Serial.println(apds.readProximity()); + + //clear the interrupt + apds.clearInterrupt(); + } +} \ No newline at end of file diff --git a/firmware/libraries/Adafruit_APDS9960_Library/library.properties b/firmware/libraries/Adafruit_APDS9960_Library/library.properties new file mode 100755 index 0000000..4302f99 --- /dev/null +++ b/firmware/libraries/Adafruit_APDS9960_Library/library.properties @@ -0,0 +1,9 @@ +name=Adafruit APDS9960 Library +version=1.1.1 +author=Adafruit +maintainer=Adafruit +sentence=This is a library for the Adafruit APDS9960 gesture/proximity/color/light sensor. +paragraph=This is a library for the Adafruit APDS9960 gesture/proximity/color/light sensor. +category=Sensors +url=https://github.com/adafruit/Adafruit_APDS9960 +architectures=* diff --git a/firmware/libraries/Adafruit_APDS9960_Library/license.txt b/firmware/libraries/Adafruit_APDS9960_Library/license.txt new file mode 100755 index 0000000..f6a0f22 --- /dev/null +++ b/firmware/libraries/Adafruit_APDS9960_Library/license.txt @@ -0,0 +1,26 @@ +Software License Agreement (BSD License) + +Copyright (c) 2012, Adafruit Industries +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. +3. Neither the name of the copyright holders nor the +names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/firmware/libraries/Adafruit_BME280_Library/Adafruit_BME280.cpp b/firmware/libraries/Adafruit_BME280_Library/Adafruit_BME280.cpp new file mode 100755 index 0000000..7b89736 --- /dev/null +++ b/firmware/libraries/Adafruit_BME280_Library/Adafruit_BME280.cpp @@ -0,0 +1,560 @@ +/*! + * @file Adafruit_BME280.cpp + * + * @mainpage Adafruit BME280 humidity, temperature & pressure sensor + * + * @section intro_sec Introduction + * + * Driver for the BME280 humidity, temperature & pressure sensor + * + * These sensors use I2C or SPI to communicate, 2 or 4 pins are required + * to interface. + * + * Designed specifically to work with the Adafruit BME280 Breakout + * ----> http://www.adafruit.com/products/2652 + * + * 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 Kevin "KTOWN" Townsend for Adafruit Industries. + * + * @section license License + * + * BSD license, all text here must be included in any redistribution. + * See the LICENSE file for details. + * + */ + +#include "Adafruit_BME280.h" +#include "Arduino.h" +#include +#include + +/*! + * @brief class constructor + */ +Adafruit_BME280::Adafruit_BME280() : _cs(-1), _mosi(-1), _miso(-1), _sck(-1) {} + +/*! + * @brief class constructor if using hardware SPI + * @param cspin the chip select pin to use + * @param *theSPI + * optional SPI object + */ +Adafruit_BME280::Adafruit_BME280(int8_t cspin, SPIClass *theSPI) { + _cs = cspin; + _mosi = _miso = _sck = -1; + _spi = theSPI; +} + +/*! + * @brief class constructor if using software SPI + * @param cspin the chip select pin to use + * @param mosipin the MOSI pin to use + * @param misopin the MISO pin to use + * @param sckpin the SCK pin to use + */ +Adafruit_BME280::Adafruit_BME280(int8_t cspin, int8_t mosipin, int8_t misopin, + int8_t sckpin) + : _cs(cspin), _mosi(mosipin), _miso(misopin), _sck(sckpin) {} + +/*! + * @brief Initialise sensor with given parameters / settings + * @param theWire the I2C object to use + * @returns true on success, false otherwise + */ +bool Adafruit_BME280::begin(TwoWire *theWire) { + _wire = theWire; + _i2caddr = BME280_ADDRESS; + return init(); +} + +/*! + * @brief Initialise sensor with given parameters / settings + * @param addr the I2C address the device can be found on + * @returns true on success, false otherwise + */ +bool Adafruit_BME280::begin(uint8_t addr) { + _i2caddr = addr; + _wire = &Wire; + return init(); +} + +/*! + * @brief Initialise sensor with given parameters / settings + * @param addr the I2C address the device can be found on + * @param theWire the I2C object to use + * @returns true on success, false otherwise + */ +bool Adafruit_BME280::begin(uint8_t addr, TwoWire *theWire) { + _i2caddr = addr; + _wire = theWire; + return init(); +} + +/*! + * @brief Initialise sensor with given parameters / settings + * @returns true on success, false otherwise + */ +bool Adafruit_BME280::begin(void) { + bool status = false; + _i2caddr = BME280_ADDRESS; + _wire = &Wire; + status = init(); + if (!status) { + _i2caddr = BME280_ADDRESS_ALTERNATE; + status = init(); + } + return status; +} + +/*! + * @brief Initialise sensor with given parameters / settings + * @returns true on success, false otherwise + */ +bool Adafruit_BME280::init() { + // init I2C or SPI sensor interface + if (_cs == -1) { + // I2C + _wire->begin(); + } else { + digitalWrite(_cs, HIGH); + pinMode(_cs, OUTPUT); + if (_sck == -1) { + // hardware SPI + _spi->begin(); + } else { + // software SPI + pinMode(_sck, OUTPUT); + pinMode(_mosi, OUTPUT); + pinMode(_miso, INPUT); + } + } + + // check if sensor, i.e. the chip ID is correct + _sensorID = read8(BME280_REGISTER_CHIPID); + if (_sensorID != 0x60) + return false; + + // reset the device using soft-reset + // this makes sure the IIR is off, etc. + write8(BME280_REGISTER_SOFTRESET, 0xB6); + + // wait for chip to wake up. + delay(300); + + // if chip is still reading calibration, delay + while (isReadingCalibration()) + delay(100); + + readCoefficients(); // read trimming parameters, see DS 4.2.2 + + setSampling(); // use defaults + + delay(100); + + return true; +} + +/*! + * @brief setup sensor with given parameters / settings + * + * This is simply a overload to the normal begin()-function, so SPI users + * don't get confused about the library requiring an address. + * @param mode the power mode to use for the sensor + * @param tempSampling the temp samping rate to use + * @param pressSampling the pressure sampling rate to use + * @param humSampling the humidity sampling rate to use + * @param filter the filter mode to use + * @param duration the standby duration to use + */ +void Adafruit_BME280::setSampling(sensor_mode mode, + sensor_sampling tempSampling, + sensor_sampling pressSampling, + sensor_sampling humSampling, + sensor_filter filter, + standby_duration duration) { + _measReg.mode = mode; + _measReg.osrs_t = tempSampling; + _measReg.osrs_p = pressSampling; + + _humReg.osrs_h = humSampling; + _configReg.filter = filter; + _configReg.t_sb = duration; + + // you must make sure to also set REGISTER_CONTROL after setting the + // CONTROLHUMID register, otherwise the values won't be applied (see + // DS 5.4.3) + write8(BME280_REGISTER_CONTROLHUMID, _humReg.get()); + write8(BME280_REGISTER_CONFIG, _configReg.get()); + write8(BME280_REGISTER_CONTROL, _measReg.get()); +} + +/*! + * @brief Encapsulate hardware and software SPI transfer into one + * function + * @param x the data byte to transfer + * @returns the data byte read from the device + */ +uint8_t Adafruit_BME280::spixfer(uint8_t x) { + // hardware SPI + if (_sck == -1) + return _spi->transfer(x); + + // software SPI + uint8_t reply = 0; + for (int i = 7; i >= 0; i--) { + reply <<= 1; + digitalWrite(_sck, LOW); + digitalWrite(_mosi, x & (1 << i)); + digitalWrite(_sck, HIGH); + if (digitalRead(_miso)) + reply |= 1; + } + return reply; +} + +/*! + * @brief Writes an 8 bit value over I2C or SPI + * @param reg the register address to write to + * @param value the value to write to the register + */ +void Adafruit_BME280::write8(byte reg, byte value) { + if (_cs == -1) { + _wire->beginTransmission((uint8_t)_i2caddr); + _wire->write((uint8_t)reg); + _wire->write((uint8_t)value); + _wire->endTransmission(); + } else { + if (_sck == -1) + _spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); + digitalWrite(_cs, LOW); + spixfer(reg & ~0x80); // write, bit 7 low + spixfer(value); + digitalWrite(_cs, HIGH); + if (_sck == -1) + _spi->endTransaction(); // release the SPI bus + } +} + +/*! + * @brief Reads an 8 bit value over I2C or SPI + * @param reg the register address to read from + * @returns the data byte read from the device + */ +uint8_t Adafruit_BME280::read8(byte reg) { + uint8_t value; + + if (_cs == -1) { + _wire->beginTransmission((uint8_t)_i2caddr); + _wire->write((uint8_t)reg); + _wire->endTransmission(); + _wire->requestFrom((uint8_t)_i2caddr, (byte)1); + value = _wire->read(); + } else { + if (_sck == -1) + _spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); + digitalWrite(_cs, LOW); + spixfer(reg | 0x80); // read, bit 7 high + value = spixfer(0); + digitalWrite(_cs, HIGH); + if (_sck == -1) + _spi->endTransaction(); // release the SPI bus + } + return value; +} + +/*! + * @brief Reads a 16 bit value over I2C or SPI + * @param reg the register address to read from + * @returns the 16 bit data value read from the device + */ +uint16_t Adafruit_BME280::read16(byte reg) { + uint16_t value; + + if (_cs == -1) { + _wire->beginTransmission((uint8_t)_i2caddr); + _wire->write((uint8_t)reg); + _wire->endTransmission(); + _wire->requestFrom((uint8_t)_i2caddr, (byte)2); + value = (_wire->read() << 8) | _wire->read(); + } else { + if (_sck == -1) + _spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); + digitalWrite(_cs, LOW); + spixfer(reg | 0x80); // read, bit 7 high + value = (spixfer(0) << 8) | spixfer(0); + digitalWrite(_cs, HIGH); + if (_sck == -1) + _spi->endTransaction(); // release the SPI bus + } + + return value; +} + +/*! + * @brief Reads a signed 16 bit little endian value over I2C or SPI + * @param reg the register address to read from + * @returns the 16 bit data value read from the device + */ +uint16_t Adafruit_BME280::read16_LE(byte reg) { + uint16_t temp = read16(reg); + return (temp >> 8) | (temp << 8); +} + +/*! + * @brief Reads a signed 16 bit value over I2C or SPI + * @param reg the register address to read from + * @returns the 16 bit data value read from the device + */ +int16_t Adafruit_BME280::readS16(byte reg) { return (int16_t)read16(reg); } + +/*! + * @brief Reads a signed little endian 16 bit value over I2C or SPI + * @param reg the register address to read from + * @returns the 16 bit data value read from the device + */ +int16_t Adafruit_BME280::readS16_LE(byte reg) { + return (int16_t)read16_LE(reg); +} + +/*! + * @brief Reads a 24 bit value over I2C + * @param reg the register address to read from + * @returns the 24 bit data value read from the device + */ +uint32_t Adafruit_BME280::read24(byte reg) { + uint32_t value; + + if (_cs == -1) { + _wire->beginTransmission((uint8_t)_i2caddr); + _wire->write((uint8_t)reg); + _wire->endTransmission(); + _wire->requestFrom((uint8_t)_i2caddr, (byte)3); + + value = _wire->read(); + value <<= 8; + value |= _wire->read(); + value <<= 8; + value |= _wire->read(); + } else { + if (_sck == -1) + _spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); + digitalWrite(_cs, LOW); + spixfer(reg | 0x80); // read, bit 7 high + + value = spixfer(0); + value <<= 8; + value |= spixfer(0); + value <<= 8; + value |= spixfer(0); + + digitalWrite(_cs, HIGH); + if (_sck == -1) + _spi->endTransaction(); // release the SPI bus + } + + return value; +} + +/*! + * @brief Take a new measurement (only possible in forced mode) + */ +void Adafruit_BME280::takeForcedMeasurement() { + // If we are in forced mode, the BME sensor goes back to sleep after each + // measurement and we need to set it to forced mode once at this point, so + // it will take the next measurement and then return to sleep again. + // In normal mode simply does new measurements periodically. + if (_measReg.mode == MODE_FORCED) { + // set to forced mode, i.e. "take next measurement" + write8(BME280_REGISTER_CONTROL, _measReg.get()); + // wait until measurement has been completed, otherwise we would read + // the values from the last measurement + while (read8(BME280_REGISTER_STATUS) & 0x08) + delay(1); + } +} + +/*! + * @brief Reads the factory-set coefficients + */ +void Adafruit_BME280::readCoefficients(void) { + _bme280_calib.dig_T1 = read16_LE(BME280_REGISTER_DIG_T1); + _bme280_calib.dig_T2 = readS16_LE(BME280_REGISTER_DIG_T2); + _bme280_calib.dig_T3 = readS16_LE(BME280_REGISTER_DIG_T3); + + _bme280_calib.dig_P1 = read16_LE(BME280_REGISTER_DIG_P1); + _bme280_calib.dig_P2 = readS16_LE(BME280_REGISTER_DIG_P2); + _bme280_calib.dig_P3 = readS16_LE(BME280_REGISTER_DIG_P3); + _bme280_calib.dig_P4 = readS16_LE(BME280_REGISTER_DIG_P4); + _bme280_calib.dig_P5 = readS16_LE(BME280_REGISTER_DIG_P5); + _bme280_calib.dig_P6 = readS16_LE(BME280_REGISTER_DIG_P6); + _bme280_calib.dig_P7 = readS16_LE(BME280_REGISTER_DIG_P7); + _bme280_calib.dig_P8 = readS16_LE(BME280_REGISTER_DIG_P8); + _bme280_calib.dig_P9 = readS16_LE(BME280_REGISTER_DIG_P9); + + _bme280_calib.dig_H1 = read8(BME280_REGISTER_DIG_H1); + _bme280_calib.dig_H2 = readS16_LE(BME280_REGISTER_DIG_H2); + _bme280_calib.dig_H3 = read8(BME280_REGISTER_DIG_H3); + _bme280_calib.dig_H4 = (read8(BME280_REGISTER_DIG_H4) << 4) | + (read8(BME280_REGISTER_DIG_H4 + 1) & 0xF); + _bme280_calib.dig_H5 = (read8(BME280_REGISTER_DIG_H5 + 1) << 4) | + (read8(BME280_REGISTER_DIG_H5) >> 4); + _bme280_calib.dig_H6 = (int8_t)read8(BME280_REGISTER_DIG_H6); +} + +/*! + * @brief return true if chip is busy reading cal data + * @returns true if reading calibration, false otherwise + */ +bool Adafruit_BME280::isReadingCalibration(void) { + uint8_t const rStatus = read8(BME280_REGISTER_STATUS); + + return (rStatus & (1 << 0)) != 0; +} + +/*! + * @brief Returns the temperature from the sensor + * @returns the temperature read from the device + */ +float Adafruit_BME280::readTemperature(void) { + int32_t var1, var2; + + int32_t adc_T = read24(BME280_REGISTER_TEMPDATA); + if (adc_T == 0x800000) // value in case temp measurement was disabled + return NAN; + adc_T >>= 4; + + var1 = ((((adc_T >> 3) - ((int32_t)_bme280_calib.dig_T1 << 1))) * + ((int32_t)_bme280_calib.dig_T2)) >> + 11; + + var2 = (((((adc_T >> 4) - ((int32_t)_bme280_calib.dig_T1)) * + ((adc_T >> 4) - ((int32_t)_bme280_calib.dig_T1))) >> + 12) * + ((int32_t)_bme280_calib.dig_T3)) >> + 14; + + t_fine = var1 + var2; + + float T = (t_fine * 5 + 128) >> 8; + return T / 100; +} + +/*! + * @brief Returns the pressure from the sensor + * @returns the pressure value (in Pascal) read from the device + */ +float Adafruit_BME280::readPressure(void) { + int64_t var1, var2, p; + + readTemperature(); // must be done first to get t_fine + + int32_t adc_P = read24(BME280_REGISTER_PRESSUREDATA); + if (adc_P == 0x800000) // value in case pressure measurement was disabled + return NAN; + adc_P >>= 4; + + var1 = ((int64_t)t_fine) - 128000; + var2 = var1 * var1 * (int64_t)_bme280_calib.dig_P6; + var2 = var2 + ((var1 * (int64_t)_bme280_calib.dig_P5) << 17); + var2 = var2 + (((int64_t)_bme280_calib.dig_P4) << 35); + var1 = ((var1 * var1 * (int64_t)_bme280_calib.dig_P3) >> 8) + + ((var1 * (int64_t)_bme280_calib.dig_P2) << 12); + var1 = + (((((int64_t)1) << 47) + var1)) * ((int64_t)_bme280_calib.dig_P1) >> 33; + + if (var1 == 0) { + return 0; // avoid exception caused by division by zero + } + p = 1048576 - adc_P; + p = (((p << 31) - var2) * 3125) / var1; + var1 = (((int64_t)_bme280_calib.dig_P9) * (p >> 13) * (p >> 13)) >> 25; + var2 = (((int64_t)_bme280_calib.dig_P8) * p) >> 19; + + p = ((p + var1 + var2) >> 8) + (((int64_t)_bme280_calib.dig_P7) << 4); + return (float)p / 256; +} + +/*! + * @brief Returns the humidity from the sensor + * @returns the humidity value read from the device + */ +float Adafruit_BME280::readHumidity(void) { + readTemperature(); // must be done first to get t_fine + + int32_t adc_H = read16(BME280_REGISTER_HUMIDDATA); + if (adc_H == 0x8000) // value in case humidity measurement was disabled + return NAN; + + int32_t v_x1_u32r; + + v_x1_u32r = (t_fine - ((int32_t)76800)); + + v_x1_u32r = (((((adc_H << 14) - (((int32_t)_bme280_calib.dig_H4) << 20) - + (((int32_t)_bme280_calib.dig_H5) * v_x1_u32r)) + + ((int32_t)16384)) >> + 15) * + (((((((v_x1_u32r * ((int32_t)_bme280_calib.dig_H6)) >> 10) * + (((v_x1_u32r * ((int32_t)_bme280_calib.dig_H3)) >> 11) + + ((int32_t)32768))) >> + 10) + + ((int32_t)2097152)) * + ((int32_t)_bme280_calib.dig_H2) + + 8192) >> + 14)); + + v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * + ((int32_t)_bme280_calib.dig_H1)) >> + 4)); + + v_x1_u32r = (v_x1_u32r < 0) ? 0 : v_x1_u32r; + v_x1_u32r = (v_x1_u32r > 419430400) ? 419430400 : v_x1_u32r; + float h = (v_x1_u32r >> 12); + return h / 1024.0; +} + +/*! + * Calculates the altitude (in meters) from the specified atmospheric + * pressure (in hPa), and sea-level pressure (in hPa). + * @param seaLevel Sea-level pressure in hPa + * @returns the altitude value read from the device + */ +float Adafruit_BME280::readAltitude(float seaLevel) { + // Equation taken from BMP180 datasheet (page 16): + // http://www.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf + + // Note that using the equation from wikipedia can give bad results + // at high altitude. See this thread for more information: + // http://forums.adafruit.com/viewtopic.php?f=22&t=58064 + + float atmospheric = readPressure() / 100.0F; + return 44330.0 * (1.0 - pow(atmospheric / seaLevel, 0.1903)); +} + +/*! + * Calculates the pressure at sea level (in hPa) from the specified + * altitude (in meters), and atmospheric pressure (in hPa). + * @param altitude Altitude in meters + * @param atmospheric Atmospheric pressure in hPa + * @returns the pressure at sea level (in hPa) from the specified altitude + */ +float Adafruit_BME280::seaLevelForAltitude(float altitude, float atmospheric) { + // Equation taken from BMP180 datasheet (page 17): + // http://www.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf + + // Note that using the equation from wikipedia can give bad results + // at high altitude. See this thread for more information: + // http://forums.adafruit.com/viewtopic.php?f=22&t=58064 + + return atmospheric / pow(1.0 - (altitude / 44330.0), 5.255); +} + +/*! + * Returns Sensor ID found by init() for diagnostics + * @returns Sensor ID 0x60 for BME280, 0x56, 0x57, 0x58 BMP280 + */ +uint32_t Adafruit_BME280::sensorID(void) { return _sensorID; } diff --git a/firmware/libraries/Adafruit_BME280_Library/Adafruit_BME280.h b/firmware/libraries/Adafruit_BME280_Library/Adafruit_BME280.h new file mode 100755 index 0000000..930afc1 --- /dev/null +++ b/firmware/libraries/Adafruit_BME280_Library/Adafruit_BME280.h @@ -0,0 +1,339 @@ +/*! + * @file Adafruit_BME280.h + * + * Designed specifically to work with the Adafruit BME280 Breakout + * ----> http://www.adafruit.com/products/2650 + * + * These sensors use I2C or SPI to communicate, 2 or 4 pins are required + * to interface. + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Kevin "KTOWN" Townsend for Adafruit Industries. + * + * BSD license, all text here must be included in any redistribution. + * See the LICENSE file for details. + * + */ + +#ifndef __BME280_H__ +#define __BME280_H__ + +#include "Arduino.h" + +#include +#include +#include + +/*! + * @brief default I2C address + */ +#define BME280_ADDRESS (0x77) // Primary I2C Address + /*! + * @brief alternate I2C address + */ +#define BME280_ADDRESS_ALTERNATE (0x76) // Alternate Address + +/*! + * @brief Register addresses + */ +enum { + BME280_REGISTER_DIG_T1 = 0x88, + BME280_REGISTER_DIG_T2 = 0x8A, + BME280_REGISTER_DIG_T3 = 0x8C, + + BME280_REGISTER_DIG_P1 = 0x8E, + BME280_REGISTER_DIG_P2 = 0x90, + BME280_REGISTER_DIG_P3 = 0x92, + BME280_REGISTER_DIG_P4 = 0x94, + BME280_REGISTER_DIG_P5 = 0x96, + BME280_REGISTER_DIG_P6 = 0x98, + BME280_REGISTER_DIG_P7 = 0x9A, + BME280_REGISTER_DIG_P8 = 0x9C, + BME280_REGISTER_DIG_P9 = 0x9E, + + BME280_REGISTER_DIG_H1 = 0xA1, + BME280_REGISTER_DIG_H2 = 0xE1, + BME280_REGISTER_DIG_H3 = 0xE3, + BME280_REGISTER_DIG_H4 = 0xE4, + BME280_REGISTER_DIG_H5 = 0xE5, + BME280_REGISTER_DIG_H6 = 0xE7, + + BME280_REGISTER_CHIPID = 0xD0, + BME280_REGISTER_VERSION = 0xD1, + BME280_REGISTER_SOFTRESET = 0xE0, + + BME280_REGISTER_CAL26 = 0xE1, // R calibration stored in 0xE1-0xF0 + + BME280_REGISTER_CONTROLHUMID = 0xF2, + BME280_REGISTER_STATUS = 0XF3, + BME280_REGISTER_CONTROL = 0xF4, + BME280_REGISTER_CONFIG = 0xF5, + BME280_REGISTER_PRESSUREDATA = 0xF7, + BME280_REGISTER_TEMPDATA = 0xFA, + BME280_REGISTER_HUMIDDATA = 0xFD +}; + +/**************************************************************************/ +/*! + @brief calibration data +*/ +/**************************************************************************/ +typedef struct { + uint16_t dig_T1; ///< temperature compensation value + int16_t dig_T2; ///< temperature compensation value + int16_t dig_T3; ///< temperature compensation value + + uint16_t dig_P1; ///< pressure compensation value + int16_t dig_P2; ///< pressure compensation value + int16_t dig_P3; ///< pressure compensation value + int16_t dig_P4; ///< pressure compensation value + int16_t dig_P5; ///< pressure compensation value + int16_t dig_P6; ///< pressure compensation value + int16_t dig_P7; ///< pressure compensation value + int16_t dig_P8; ///< pressure compensation value + int16_t dig_P9; ///< pressure compensation value + + uint8_t dig_H1; ///< humidity compensation value + int16_t dig_H2; ///< humidity compensation value + uint8_t dig_H3; ///< humidity compensation value + int16_t dig_H4; ///< humidity compensation value + int16_t dig_H5; ///< humidity compensation value + int8_t dig_H6; ///< humidity compensation value +} bme280_calib_data; +/*=========================================================================*/ + +/* +class Adafruit_BME280_Unified : public Adafruit_Sensor +{ + public: + Adafruit_BME280_Unified(int32_t sensorID = -1); + + bool begin(uint8_t addr = BME280_ADDRESS); + void getTemperature(float *temp); + void getPressure(float *pressure); + float pressureToAltitude(float seaLevel, float atmospheric, float temp); + float seaLevelForAltitude(float altitude, float atmospheric, float temp); + void getEvent(sensors_event_t*); + void getSensor(sensor_t*); + + private: + uint8_t _i2c_addr; + int32_t _sensorID; +}; + +*/ + +/**************************************************************************/ +/*! + @brief Class that stores state and functions for interacting with BME280 IC +*/ +/**************************************************************************/ +class Adafruit_BME280 { +public: + /**************************************************************************/ + /*! + @brief sampling rates + */ + /**************************************************************************/ + enum sensor_sampling { + SAMPLING_NONE = 0b000, + SAMPLING_X1 = 0b001, + SAMPLING_X2 = 0b010, + SAMPLING_X4 = 0b011, + SAMPLING_X8 = 0b100, + SAMPLING_X16 = 0b101 + }; + + /**************************************************************************/ + /*! + @brief power modes + */ + /**************************************************************************/ + enum sensor_mode { + MODE_SLEEP = 0b00, + MODE_FORCED = 0b01, + MODE_NORMAL = 0b11 + }; + + /**************************************************************************/ + /*! + @brief filter values + */ + /**************************************************************************/ + enum sensor_filter { + FILTER_OFF = 0b000, + FILTER_X2 = 0b001, + FILTER_X4 = 0b010, + FILTER_X8 = 0b011, + FILTER_X16 = 0b100 + }; + + /**************************************************************************/ + /*! + @brief standby duration in ms + */ + /**************************************************************************/ + enum standby_duration { + STANDBY_MS_0_5 = 0b000, + STANDBY_MS_10 = 0b110, + STANDBY_MS_20 = 0b111, + STANDBY_MS_62_5 = 0b001, + STANDBY_MS_125 = 0b010, + STANDBY_MS_250 = 0b011, + STANDBY_MS_500 = 0b100, + STANDBY_MS_1000 = 0b101 + }; + + // constructors + Adafruit_BME280(); + Adafruit_BME280(int8_t cspin, SPIClass *theSPI = &SPI); + Adafruit_BME280(int8_t cspin, int8_t mosipin, int8_t misopin, + int8_t sckpin); + + bool begin(); + bool begin(TwoWire *theWire); + bool begin(uint8_t addr); + bool begin(uint8_t addr, TwoWire *theWire); + bool init(); + + void setSampling(sensor_mode mode = MODE_NORMAL, + sensor_sampling tempSampling = SAMPLING_X16, + sensor_sampling pressSampling = SAMPLING_X16, + sensor_sampling humSampling = SAMPLING_X16, + sensor_filter filter = FILTER_OFF, + standby_duration duration = STANDBY_MS_0_5); + + void takeForcedMeasurement(); + float readTemperature(void); + float readPressure(void); + float readHumidity(void); + + float readAltitude(float seaLevel); + float seaLevelForAltitude(float altitude, float pressure); + uint32_t sensorID(void); + +protected: + TwoWire *_wire; //!< pointer to a TwoWire object + SPIClass *_spi; //!< pointer to SPI object + void readCoefficients(void); + bool isReadingCalibration(void); + uint8_t spixfer(uint8_t x); + + void write8(byte reg, byte value); + uint8_t read8(byte reg); + uint16_t read16(byte reg); + uint32_t read24(byte reg); + int16_t readS16(byte reg); + uint16_t read16_LE(byte reg); // little endian + int16_t readS16_LE(byte reg); // little endian + + uint8_t _i2caddr; //!< I2C addr for the TwoWire interface + int32_t _sensorID; //!< ID of the BME Sensor + int32_t t_fine; //!< temperature with high resolution, stored as an attribute + //!< as this is used for temperature compensation reading + //!< humidity and pressure + + int8_t _cs; //!< for the SPI interface + int8_t _mosi; //!< for the SPI interface + int8_t _miso; //!< for the SPI interface + int8_t _sck; //!< for the SPI interface + + bme280_calib_data _bme280_calib; //!< here calibration data is stored + + /**************************************************************************/ + /*! + @brief config register + */ + /**************************************************************************/ + struct config { + // inactive duration (standby time) in normal mode + // 000 = 0.5 ms + // 001 = 62.5 ms + // 010 = 125 ms + // 011 = 250 ms + // 100 = 500 ms + // 101 = 1000 ms + // 110 = 10 ms + // 111 = 20 ms + unsigned int t_sb : 3; ///< inactive duration (standby time) in normal mode + + // filter settings + // 000 = filter off + // 001 = 2x filter + // 010 = 4x filter + // 011 = 8x filter + // 100 and above = 16x filter + unsigned int filter : 3; ///< filter settings + + // unused - don't set + unsigned int none : 1; ///< unused - don't set + unsigned int spi3w_en : 1; ///< unused - don't set + + /// @return combined config register + unsigned int get() { return (t_sb << 5) | (filter << 2) | spi3w_en; } + }; + config _configReg; //!< config register object + + /**************************************************************************/ + /*! + @brief ctrl_meas register + */ + /**************************************************************************/ + struct ctrl_meas { + // temperature oversampling + // 000 = skipped + // 001 = x1 + // 010 = x2 + // 011 = x4 + // 100 = x8 + // 101 and above = x16 + unsigned int osrs_t : 3; ///< temperature oversampling + + // pressure oversampling + // 000 = skipped + // 001 = x1 + // 010 = x2 + // 011 = x4 + // 100 = x8 + // 101 and above = x16 + unsigned int osrs_p : 3; ///< pressure oversampling + + // device mode + // 00 = sleep + // 01 or 10 = forced + // 11 = normal + unsigned int mode : 2; ///< device mode + + /// @return combined ctrl register + unsigned int get() { return (osrs_t << 5) | (osrs_p << 2) | mode; } + }; + ctrl_meas _measReg; //!< measurement register object + + /**************************************************************************/ + /*! + @brief ctrl_hum register + */ + /**************************************************************************/ + struct ctrl_hum { + /// unused - don't set + unsigned int none : 5; + + // pressure oversampling + // 000 = skipped + // 001 = x1 + // 010 = x2 + // 011 = x4 + // 100 = x8 + // 101 and above = x16 + unsigned int osrs_h : 3; ///< pressure oversampling + + /// @return combined ctrl hum register + unsigned int get() { return (osrs_h); } + }; + ctrl_hum _humReg; //!< hum register object +}; + +#endif diff --git a/firmware/libraries/Adafruit_BME280_Library/LICENSE b/firmware/libraries/Adafruit_BME280_Library/LICENSE new file mode 100755 index 0000000..f4db09c --- /dev/null +++ b/firmware/libraries/Adafruit_BME280_Library/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2015, Limor Fried & Kevin Townsend for Adafruit Industries +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Adafruit Industries nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + diff --git a/firmware/libraries/Adafruit_BME280_Library/README.md b/firmware/libraries/Adafruit_BME280_Library/README.md new file mode 100755 index 0000000..2ba2668 --- /dev/null +++ b/firmware/libraries/Adafruit_BME280_Library/README.md @@ -0,0 +1,31 @@ +# Adafruit BME280 Library [![Build Status](https://travis-ci.com/adafruit/Adafruit_BME280_Library.svg?branch=master)](https://travis-ci.com/adafruit/Adafruit_BME280_Library) + + + +This is a library for the Adafruit BME280 Humidity, Barometric Pressure + Temp sensor + +Designed specifically to work with the Adafruit BME280 Breakout + * http://www.adafruit.com/products/2652 + +These sensors use I2C or SPI to communicate, up to 4 pins are required to interface + +Use of this library also requires [Adafruit_Sensor](https://github.com/adafruit/Adafruit_Sensor) +to be installed on your local system. + +Adafruit invests time and resources providing this open source code, +please support Adafruit and open-source hardware by purchasing +products from Adafruit! + +Check out the links above for our tutorials and wiring diagrams + +Written by Limor Fried/Ladyada for Adafruit Industries. +BSD license, all text above must be included in any redistribution + +To download. click the DOWNLOAD ZIP button, rename the uncompressed folder Adafruit_BME280. +Check that the Adafruit_BME280 folder contains Adafruit_BME280.cpp and Adafruit_BME280.h + +Place the Adafruit_BME280 library folder your arduinosketchfolder/libraries/ folder. +You may need to create the libraries subfolder if its your first library. Restart the IDE. + +We also have a great tutorial on Arduino library installation at: +http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use diff --git a/firmware/libraries/Adafruit_BME280_Library/assets/board.jpg b/firmware/libraries/Adafruit_BME280_Library/assets/board.jpg new file mode 100755 index 0000000..581f4ba Binary files /dev/null and b/firmware/libraries/Adafruit_BME280_Library/assets/board.jpg differ diff --git a/firmware/libraries/Adafruit_BME280_Library/examples/advancedsettings/advancedsettings.ino b/firmware/libraries/Adafruit_BME280_Library/examples/advancedsettings/advancedsettings.ino new file mode 100755 index 0000000..b4f0810 --- /dev/null +++ b/firmware/libraries/Adafruit_BME280_Library/examples/advancedsettings/advancedsettings.ino @@ -0,0 +1,159 @@ +/*************************************************************************** + This is a library for the BME280 humidity, temperature & pressure sensor + + Designed specifically to work with the Adafruit BME280 Breakout + ----> http://www.adafruit.com/products/2650 + + These sensors use I2C or SPI to communicate, 2 or 4 pins are required + to interface. The device's I2C address is either 0x76 or 0x77. + + Adafruit invests time and resources providing this open source code, + please support Adafruit andopen-source hardware by purchasing products + from Adafruit! + + Written by Limor Fried & Kevin Townsend for Adafruit Industries. + BSD license, all text above must be included in any redistribution + See the LICENSE file for details. + ***************************************************************************/ + +#include +#include +#include +#include + +#define BME_SCK 13 +#define BME_MISO 12 +#define BME_MOSI 11 +#define BME_CS 10 + +#define SEALEVELPRESSURE_HPA (1013.25) + +Adafruit_BME280 bme; // I2C +//Adafruit_BME280 bme(BME_CS); // hardware SPI +//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI + +unsigned long delayTime; + +void setup() { + Serial.begin(9600); + Serial.println(F("BME280 test")); + + if (! bme.begin(&Wire)) { + Serial.println("Could not find a valid BME280 sensor, check wiring!"); + while (1); + } + + Serial.println("-- Default Test --"); + Serial.println("normal mode, 16x oversampling for all, filter off,"); + Serial.println("0.5ms standby period"); + delayTime = 5000; + + + // For more details on the following scenarious, see chapter + // 3.5 "Recommended modes of operation" in the datasheet + +/* + // weather monitoring + Serial.println("-- Weather Station Scenario --"); + Serial.println("forced mode, 1x temperature / 1x humidity / 1x pressure oversampling,"); + Serial.println("filter off"); + bme.setSampling(Adafruit_BME280::MODE_FORCED, + Adafruit_BME280::SAMPLING_X1, // temperature + Adafruit_BME280::SAMPLING_X1, // pressure + Adafruit_BME280::SAMPLING_X1, // humidity + Adafruit_BME280::FILTER_OFF ); + + // suggested rate is 1/60Hz (1m) + delayTime = 60000; // in milliseconds +*/ + +/* + // humidity sensing + Serial.println("-- Humidity Sensing Scenario --"); + Serial.println("forced mode, 1x temperature / 1x humidity / 0x pressure oversampling"); + Serial.println("= pressure off, filter off"); + bme.setSampling(Adafruit_BME280::MODE_FORCED, + Adafruit_BME280::SAMPLING_X1, // temperature + Adafruit_BME280::SAMPLING_NONE, // pressure + Adafruit_BME280::SAMPLING_X1, // humidity + Adafruit_BME280::FILTER_OFF ); + + // suggested rate is 1Hz (1s) + delayTime = 1000; // in milliseconds +*/ + +/* + // indoor navigation + Serial.println("-- Indoor Navigation Scenario --"); + Serial.println("normal mode, 16x pressure / 2x temperature / 1x humidity oversampling,"); + Serial.println("0.5ms standby period, filter 16x"); + bme.setSampling(Adafruit_BME280::MODE_NORMAL, + Adafruit_BME280::SAMPLING_X2, // temperature + Adafruit_BME280::SAMPLING_X16, // pressure + Adafruit_BME280::SAMPLING_X1, // humidity + Adafruit_BME280::FILTER_X16, + Adafruit_BME280::STANDBY_MS_0_5 ); + + // suggested rate is 25Hz + // 1 + (2 * T_ovs) + (2 * P_ovs + 0.5) + (2 * H_ovs + 0.5) + // T_ovs = 2 + // P_ovs = 16 + // H_ovs = 1 + // = 40ms (25Hz) + // with standby time that should really be 24.16913... Hz + delayTime = 41; + */ + + /* + // gaming + Serial.println("-- Gaming Scenario --"); + Serial.println("normal mode, 4x pressure / 1x temperature / 0x humidity oversampling,"); + Serial.println("= humidity off, 0.5ms standby period, filter 16x"); + bme.setSampling(Adafruit_BME280::MODE_NORMAL, + Adafruit_BME280::SAMPLING_X1, // temperature + Adafruit_BME280::SAMPLING_X4, // pressure + Adafruit_BME280::SAMPLING_NONE, // humidity + Adafruit_BME280::FILTER_X16, + Adafruit_BME280::STANDBY_MS_0_5 ); + + // Suggested rate is 83Hz + // 1 + (2 * T_ovs) + (2 * P_ovs + 0.5) + // T_ovs = 1 + // P_ovs = 4 + // = 11.5ms + 0.5ms standby + delayTime = 12; +*/ + + Serial.println(); +} + + +void loop() { + // Only needed in forced mode! In normal mode, you can remove the next line. + bme.takeForcedMeasurement(); // has no effect in normal mode + + printValues(); + delay(delayTime); +} + + +void printValues() { + Serial.print("Temperature = "); + Serial.print(bme.readTemperature()); + Serial.println(" *C"); + + Serial.print("Pressure = "); + + Serial.print(bme.readPressure() / 100.0F); + Serial.println(" hPa"); + + Serial.print("Approx. Altitude = "); + Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA)); + Serial.println(" m"); + + Serial.print("Humidity = "); + Serial.print(bme.readHumidity()); + Serial.println(" %"); + + Serial.println(); +} diff --git a/firmware/libraries/Adafruit_BME280_Library/examples/bme280test/bme280test.ino b/firmware/libraries/Adafruit_BME280_Library/examples/bme280test/bme280test.ino new file mode 100755 index 0000000..9fb8c43 --- /dev/null +++ b/firmware/libraries/Adafruit_BME280_Library/examples/bme280test/bme280test.ino @@ -0,0 +1,89 @@ +/*************************************************************************** + This is a library for the BME280 humidity, temperature & pressure sensor + + Designed specifically to work with the Adafruit BME280 Breakout + ----> http://www.adafruit.com/products/2650 + + These sensors use I2C or SPI to communicate, 2 or 4 pins are required + to interface. The device's I2C address is either 0x76 or 0x77. + + Adafruit invests time and resources providing this open source code, + please support Adafruit andopen-source hardware by purchasing products + from Adafruit! + + Written by Limor Fried & Kevin Townsend for Adafruit Industries. + BSD license, all text above must be included in any redistribution + See the LICENSE file for details. + ***************************************************************************/ + +#include +#include +#include +#include + +#define BME_SCK 13 +#define BME_MISO 12 +#define BME_MOSI 11 +#define BME_CS 10 + +#define SEALEVELPRESSURE_HPA (1013.25) + +Adafruit_BME280 bme; // I2C +//Adafruit_BME280 bme(BME_CS); // hardware SPI +//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI + +unsigned long delayTime; + +void setup() { + Serial.begin(9600); + while(!Serial); // time to get serial running + Serial.println(F("BME280 test")); + + unsigned status; + + // default settings + // (you can also pass in a Wire library object like &Wire2) + status = bme.begin(); + if (!status) { + Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!"); + Serial.print("SensorID was: 0x"); Serial.println(bme.sensorID(),16); + Serial.print(" ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n"); + Serial.print(" ID of 0x56-0x58 represents a BMP 280,\n"); + Serial.print(" ID of 0x60 represents a BME 280.\n"); + Serial.print(" ID of 0x61 represents a BME 680.\n"); + while (1); + } + + Serial.println("-- Default Test --"); + delayTime = 1000; + + Serial.println(); +} + + +void loop() { + printValues(); + delay(delayTime); +} + + +void printValues() { + Serial.print("Temperature = "); + Serial.print(bme.readTemperature()); + Serial.println(" *C"); + + Serial.print("Pressure = "); + + Serial.print(bme.readPressure() / 100.0F); + Serial.println(" hPa"); + + Serial.print("Approx. Altitude = "); + Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA)); + Serial.println(" m"); + + Serial.print("Humidity = "); + Serial.print(bme.readHumidity()); + Serial.println(" %"); + + Serial.println(); +} diff --git a/firmware/libraries/Adafruit_BME280_Library/library.properties b/firmware/libraries/Adafruit_BME280_Library/library.properties new file mode 100755 index 0000000..f3ce2ba --- /dev/null +++ b/firmware/libraries/Adafruit_BME280_Library/library.properties @@ -0,0 +1,9 @@ +name=Adafruit BME280 Library +version=1.0.9 +author=Adafruit +maintainer=Adafruit +sentence=Arduino library for BME280 sensors. +paragraph=Arduino library for BME280 humidity and pressure sensors. +category=Sensors +url=https://github.com/adafruit/Adafruit_BME280_Library +architectures=* diff --git a/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.h b/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.h new file mode 100755 index 0000000..8ac638f --- /dev/null +++ b/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.h @@ -0,0 +1,156 @@ +/* +* Copyright (C) 2008 The Android Open Source Project +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software< /span> +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* Update by K. Townsend (Adafruit Industries) for lighter typedefs, and + * extended sensor support to include color, voltage and current */ + +#ifndef _ADAFRUIT_SENSOR_H +#define _ADAFRUIT_SENSOR_H + +#ifndef ARDUINO + #include +#elif ARDUINO >= 100 + #include "Arduino.h" + #include "Print.h" +#else + #include "WProgram.h" +#endif + +/* Intentionally modeled after sensors.h in the Android API: + * https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h */ + +/* Constants */ +#define SENSORS_GRAVITY_EARTH (9.80665F) /**< Earth's gravity in m/s^2 */ +#define SENSORS_GRAVITY_MOON (1.6F) /**< The moon's gravity in m/s^2 */ +#define SENSORS_GRAVITY_SUN (275.0F) /**< The sun's gravity in m/s^2 */ +#define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH) +#define SENSORS_MAGFIELD_EARTH_MAX (60.0F) /**< Maximum magnetic field on Earth's surface */ +#define SENSORS_MAGFIELD_EARTH_MIN (30.0F) /**< Minimum magnetic field on Earth's surface */ +#define SENSORS_PRESSURE_SEALEVELHPA (1013.25F) /**< Average sea level pressure is 1013.25 hPa */ +#define SENSORS_DPS_TO_RADS (0.017453293F) /**< Degrees/s to rad/s multiplier */ +#define SENSORS_GAUSS_TO_MICROTESLA (100) /**< Gauss to micro-Tesla multiplier */ + +/** Sensor types */ +typedef enum +{ + SENSOR_TYPE_ACCELEROMETER = (1), /**< Gravity + linear acceleration */ + SENSOR_TYPE_MAGNETIC_FIELD = (2), + SENSOR_TYPE_ORIENTATION = (3), + SENSOR_TYPE_GYROSCOPE = (4), + SENSOR_TYPE_LIGHT = (5), + SENSOR_TYPE_PRESSURE = (6), + SENSOR_TYPE_PROXIMITY = (8), + SENSOR_TYPE_GRAVITY = (9), + SENSOR_TYPE_LINEAR_ACCELERATION = (10), /**< Acceleration not including gravity */ + SENSOR_TYPE_ROTATION_VECTOR = (11), + SENSOR_TYPE_RELATIVE_HUMIDITY = (12), + SENSOR_TYPE_AMBIENT_TEMPERATURE = (13), + SENSOR_TYPE_VOLTAGE = (15), + SENSOR_TYPE_CURRENT = (16), + SENSOR_TYPE_COLOR = (17) +} sensors_type_t; + +/** struct sensors_vec_s is used to return a vector in a common format. */ +typedef struct { + union { + float v[3]; + struct { + float x; + float y; + float z; + }; + /* Orientation sensors */ + struct { + float roll; /**< Rotation around the longitudinal axis (the plane body, 'X axis'). Roll is positive and increasing when moving downward. -90°<=roll<=90° */ + float pitch; /**< Rotation around the lateral axis (the wing span, 'Y axis'). Pitch is positive and increasing when moving upwards. -180°<=pitch<=180°) */ + float heading; /**< Angle between the longitudinal axis (the plane body) and magnetic north, measured clockwise when viewing from the top of the device. 0-359° */ + }; + }; + int8_t status; + uint8_t reserved[3]; +} sensors_vec_t; + +/** struct sensors_color_s is used to return color data in a common format. */ +typedef struct { + union { + float c[3]; + /* RGB color space */ + struct { + float r; /**< Red component */ + float g; /**< Green component */ + float b; /**< Blue component */ + }; + }; + uint32_t rgba; /**< 24-bit RGBA value */ +} sensors_color_t; + +/* Sensor event (36 bytes) */ +/** struct sensor_event_s is used to provide a single sensor event in a common format. */ +typedef struct +{ + int32_t version; /**< must be sizeof(struct sensors_event_t) */ + int32_t sensor_id; /**< unique sensor identifier */ + int32_t type; /**< sensor type */ + int32_t reserved0; /**< reserved */ + int32_t timestamp; /**< time is in milliseconds */ + union + { + float data[4]; + sensors_vec_t acceleration; /**< acceleration values are in meter per second per second (m/s^2) */ + sensors_vec_t magnetic; /**< magnetic vector values are in micro-Tesla (uT) */ + sensors_vec_t orientation; /**< orientation values are in degrees */ + sensors_vec_t gyro; /**< gyroscope values are in rad/s */ + float temperature; /**< temperature is in degrees centigrade (Celsius) */ + float distance; /**< distance in centimeters */ + float light; /**< light in SI lux units */ + float pressure; /**< pressure in hectopascal (hPa) */ + float relative_humidity; /**< relative humidity in percent */ + float current; /**< current in milliamps (mA) */ + float voltage; /**< voltage in volts (V) */ + sensors_color_t color; /**< color in RGB component values */ + }; +} sensors_event_t; + +/* Sensor details (40 bytes) */ +/** struct sensor_s is used to describe basic information about a specific sensor. */ +typedef struct +{ + char name[12]; /**< sensor name */ + int32_t version; /**< version of the hardware + driver */ + int32_t sensor_id; /**< unique sensor identifier */ + int32_t type; /**< this sensor's type (ex. SENSOR_TYPE_LIGHT) */ + float max_value; /**< maximum value of this sensor's value in SI units */ + float min_value; /**< minimum value of this sensor's value in SI units */ + float resolution; /**< smallest difference between two values reported by this sensor */ + int32_t min_delay; /**< min delay in microseconds between events. zero = not a constant rate */ +} sensor_t; + +class Adafruit_Sensor { + public: + // Constructor(s) + Adafruit_Sensor() {} + virtual ~Adafruit_Sensor() {} + + // These must be defined by the subclass + virtual void enableAutoRange(bool enabled) { (void)enabled; /* suppress unused warning */ }; + virtual bool getEvent(sensors_event_t*) = 0; + virtual void getSensor(sensor_t*) = 0; + + private: + bool _autoRange; +}; + +#endif diff --git a/firmware/libraries/Adafruit_Unified_Sensor/README.md b/firmware/libraries/Adafruit_Unified_Sensor/README.md new file mode 100755 index 0000000..fd99597 --- /dev/null +++ b/firmware/libraries/Adafruit_Unified_Sensor/README.md @@ -0,0 +1,229 @@ +# Adafruit Unified Sensor Driver # + +Many small embedded systems exist to collect data from sensors, analyse the data, and either take an appropriate action or send that sensor data to another system for processing. + +One of the many challenges of embedded systems design is the fact that parts you used today may be out of production tomorrow, or system requirements may change and you may need to choose a different sensor down the road. + +Creating new drivers is a relatively easy task, but integrating them into existing systems is both error prone and time consuming since sensors rarely use the exact same units of measurement. + +By reducing all data to a single **sensors\_event\_t** 'type' and settling on specific, **standardised SI units** for each sensor family the same sensor types return values that are comparable with any other similar sensor. This enables you to switch sensor models with very little impact on the rest of the system, which can help mitigate some of the risks and problems of sensor availability and code reuse. + +The unified sensor abstraction layer is also useful for data-logging and data-transmission since you only have one well-known type to log or transmit over the air or wire. + +## Unified Sensor Drivers ## + +The following drivers are based on the Adafruit Unified Sensor Driver: + +**Accelerometers** + - [Adafruit\_ADXL345](https://github.com/adafruit/Adafruit_ADXL345) + - [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC) + - [Adafruit\_MMA8451\_Library](https://github.com/adafruit/Adafruit_MMA8451_Library) + +**Gyroscope** + - [Adafruit\_L3GD20\_U](https://github.com/adafruit/Adafruit_L3GD20_U) + +**Light** + - [Adafruit\_TSL2561](https://github.com/adafruit/Adafruit_TSL2561) + - [Adafruit\_TSL2591\_Library](https://github.com/adafruit/Adafruit_TSL2591_Library) + +**Magnetometers** + - [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC) + - [Adafruit\_HMC5883\_Unified](https://github.com/adafruit/Adafruit_HMC5883_Unified) + +**Barometric Pressure** + - [Adafruit\_BMP085\_Unified](https://github.com/adafruit/Adafruit_BMP085_Unified) + - [Adafruit\_BMP183\_Unified\_Library](https://github.com/adafruit/Adafruit_BMP183_Unified_Library) + +**Humidity & Temperature** + - [DHT-sensor-library](https://github.com/adafruit/DHT-sensor-library) + +**Humidity, Temperature, & Barometric Pressure** + - [Adafruit_BME280_Library](https://github.com/adafruit/Adafruit_BME280_Library/) + +**Orientation** + - [Adafruit_BNO055](https://github.com/adafruit/Adafruit_BNO055) + +**All in one device** +- [Adafruit_LSM9DS0](https://github.com/adafruit/Adafruit_LSM9DS0_Library) (accelerometer, gyroscope, magnetometer) +- [Adafruit_LSM9DS1](https://github.com/adafruit/Adafruit_LSM9DS1/) (accelerometer, gyroscope, magnetometer) + + +## How Does it Work? ## + +Any driver that supports the Adafruit unified sensor abstraction layer will implement the Adafruit\_Sensor base class. There are two main typedefs and one enum defined in Adafruit_Sensor.h that are used to 'abstract' away the sensor details and values: + +**Sensor Types (sensors\_type\_t)** + +These pre-defined sensor types are used to properly handle the two related typedefs below, and allows us determine what types of units the sensor uses, etc. + +``` +/** Sensor types */ +typedef enum +{ + SENSOR_TYPE_ACCELEROMETER = (1), + SENSOR_TYPE_MAGNETIC_FIELD = (2), + SENSOR_TYPE_ORIENTATION = (3), + SENSOR_TYPE_GYROSCOPE = (4), + SENSOR_TYPE_LIGHT = (5), + SENSOR_TYPE_PRESSURE = (6), + SENSOR_TYPE_PROXIMITY = (8), + SENSOR_TYPE_GRAVITY = (9), + SENSOR_TYPE_LINEAR_ACCELERATION = (10), + SENSOR_TYPE_ROTATION_VECTOR = (11), + SENSOR_TYPE_RELATIVE_HUMIDITY = (12), + SENSOR_TYPE_AMBIENT_TEMPERATURE = (13), + SENSOR_TYPE_VOLTAGE = (15), + SENSOR_TYPE_CURRENT = (16), + SENSOR_TYPE_COLOR = (17) +} sensors_type_t; +``` + +**Sensor Details (sensor\_t)** + +This typedef describes the specific capabilities of this sensor, and allows us to know what sensor we are using beneath the abstraction layer. + +``` +/* Sensor details (40 bytes) */ +/** struct sensor_s is used to describe basic information about a specific sensor. */ +typedef struct +{ + char name[12]; + int32_t version; + int32_t sensor_id; + int32_t type; + float max_value; + float min_value; + float resolution; + int32_t min_delay; +} sensor_t; +``` + +The individual fields are intended to be used as follows: + +- **name**: The sensor name or ID, up to a maximum of twelve characters (ex. "MPL115A2") +- **version**: The version of the sensor HW and the driver to allow us to differentiate versions of the board or driver +- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network +- **type**: The sensor type, based on **sensors\_type\_t** in sensors.h +- **max\_value**: The maximum value that this sensor can return (in the appropriate SI unit) +- **min\_value**: The minimum value that this sensor can return (in the appropriate SI unit) +- **resolution**: The smallest difference between two values that this sensor can report (in the appropriate SI unit) +- **min\_delay**: The minimum delay in microseconds between two sensor events, or '0' if there is no constant sensor rate + +**Sensor Data/Events (sensors\_event\_t)** + +This typedef is used to return sensor data from any sensor supported by the abstraction layer, using standard SI units and scales. + +``` +/* Sensor event (36 bytes) */ +/** struct sensor_event_s is used to provide a single sensor event in a common format. */ +typedef struct +{ + int32_t version; + int32_t sensor_id; + int32_t type; + int32_t reserved0; + int32_t timestamp; + union + { + float data[4]; + sensors_vec_t acceleration; + sensors_vec_t magnetic; + sensors_vec_t orientation; + sensors_vec_t gyro; + float temperature; + float distance; + float light; + float pressure; + float relative_humidity; + float current; + float voltage; + sensors_color_t color; + }; +} sensors_event_t; +``` +It includes the following fields: + +- **version**: Contain 'sizeof(sensors\_event\_t)' to identify which version of the API we're using in case this changes in the future +- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network (must match the sensor\_id value in the corresponding sensor\_t enum above!) +- **type**: the sensor type, based on **sensors\_type\_t** in sensors.h +- **timestamp**: time in milliseconds when the sensor value was read +- **data[4]**: An array of four 32-bit values that allows us to encapsulate any type of sensor data via a simple union (further described below) + +**Required Functions** + +In addition to the two standard types and the sensor type enum, all drivers based on Adafruit_Sensor must also implement the following two functions: + +``` +bool getEvent(sensors_event_t*); +``` +Calling this function will populate the supplied sensors\_event\_t reference with the latest available sensor data. You should call this function as often as you want to update your data. + +``` +void getSensor(sensor_t*); +``` +Calling this function will provide some basic information about the sensor (the sensor name, driver version, min and max values, etc. + +**Standardised SI values for sensors\_event\_t** + +A key part of the abstraction layer is the standardisation of values on SI units of a particular scale, which is accomplished via the data[4] union in sensors\_event\_t above. This 16 byte union includes fields for each main sensor type, and uses the following SI units and scales: + +- **acceleration**: values are in **meter per second per second** (m/s^2) +- **magnetic**: values are in **micro-Tesla** (uT) +- **orientation**: values are in **degrees** +- **gyro**: values are in **rad/s** +- **temperature**: values in **degrees centigrade** (Celsius) +- **distance**: values are in **centimeters** +- **light**: values are in **SI lux** units +- **pressure**: values are in **hectopascal** (hPa) +- **relative\_humidity**: values are in **percent** +- **current**: values are in **milliamps** (mA) +- **voltage**: values are in **volts** (V) +- **color**: values are in 0..1.0 RGB channel luminosity and 32-bit RGBA format + +## The Unified Driver Abstraction Layer in Practice ## + +Using the unified sensor abstraction layer is relatively easy once a compliant driver has been created. + +Every compliant sensor can now be read using a single, well-known 'type' (sensors\_event\_t), and there is a standardised way of interrogating a sensor about its specific capabilities (via sensor\_t). + +An example of reading the [TSL2561](https://github.com/adafruit/Adafruit_TSL2561) light sensor can be seen below: + +``` + Adafruit_TSL2561 tsl = Adafruit_TSL2561(TSL2561_ADDR_FLOAT, 12345); + ... + /* Get a new sensor event */ + sensors_event_t event; + tsl.getEvent(&event); + + /* Display the results (light is measured in lux) */ + if (event.light) + { + Serial.print(event.light); Serial.println(" lux"); + } + else + { + /* If event.light = 0 lux the sensor is probably saturated + and no reliable data could be generated! */ + Serial.println("Sensor overload"); + } +``` + +Similarly, we can get the basic technical capabilities of this sensor with the following code: + +``` + sensor_t sensor; + + sensor_t sensor; + tsl.getSensor(&sensor); + + /* Display the sensor details */ + Serial.println("------------------------------------"); + Serial.print ("Sensor: "); Serial.println(sensor.name); + Serial.print ("Driver Ver: "); Serial.println(sensor.version); + Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); + Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux"); + Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux"); + Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux"); + Serial.println("------------------------------------"); + Serial.println(""); +``` diff --git a/firmware/libraries/Adafruit_Unified_Sensor/library.properties b/firmware/libraries/Adafruit_Unified_Sensor/library.properties new file mode 100755 index 0000000..e0bcd3e --- /dev/null +++ b/firmware/libraries/Adafruit_Unified_Sensor/library.properties @@ -0,0 +1,10 @@ +name=Adafruit Unified Sensor +version=1.0.3 +author=Adafruit +maintainer=Adafruit +sentence=Required for all Adafruit Unified Sensor based libraries. +paragraph=A unified sensor abstraction layer used by many Adafruit sensor libraries. +category=Sensors +url=https://github.com/adafruit/Adafruit_Sensor +architectures=* +includes=Adafruit_Sensor.h diff --git a/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.cpp b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.cpp new file mode 100755 index 0000000..caf16bc --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.cpp @@ -0,0 +1,176 @@ +#include "Arduino.h" +#include "ESP8266Influxdb.h" +#include + +#define DEBUG_PRINT // comment this line to disable debug print + +#ifndef DEBUG_PRINT +#define DEBUG_PRINT(a) +#else +#define DEBUG_PRINT(a) (Serial.println(String(F("[Debug]: "))+(a))) +#define _DEBUG +#endif + +Influxdb::Influxdb(const char *host, uint16_t port) : WiFiClient() { + _port = port; + _host = host; +} + +DB_RESPONSE Influxdb::opendb(String db, String user, String password) { + _db = "db=" + db + "&u=" + user + "&p=" + password; +} + +DB_RESPONSE Influxdb::opendb(String db) { + _db = "db=" + db; + +} + +DB_RESPONSE Influxdb::write(FIELD data) { + return write(data.postString()); +} + +DB_RESPONSE Influxdb::write(String data) { + if (!connect(_host, _port)) { + DEBUG_PRINT("connection failed"); + _response = DB_CONNECT_FAILED; + return _response; + } + String postHead = "POST /write?" + _db + " HTTP/1.1\r\n"; + postHead += "Host: " + String(_host) + ":" + String(_port) + "\r\n"; + // postHead += "Content-Type: application/x-www-form-urlencoded\r\n"; + postHead += "Content-Length: " + String(data.length()) + "\r\n\r\n"; + + DEBUG_PRINT("Writing data to " + String(_host) + ":" + String(_port)); + print(postHead + data); + DEBUG_PRINT(postHead + data); + + uint8_t t = 0; + // Check the reply whether writing is success or not + while (!available() && t < 200) { + delay(10); + t++; + } + if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out. + +#if !defined _DEBUG + if (available()) { + _response = (findUntil("204", "\r")) ? DB_SUCCESS : DB_ERROR; + return _response; + } +#else + _response=DB_ERROR; + while (available()) { + String line = readStringUntil('\n'); + if (line.substring(9,12)=="204") + _response = DB_SUCCESS; + DEBUG_PRINT("(Responsed): " + line); + } + return _response; +#endif + return DB_ERROR; +} + +DB_RESPONSE Influxdb::query(String sql) { + + if (!connect(_host, _port)) { + DEBUG_PRINT("connection failed"); + _response = DB_CONNECT_FAILED; + return _response; + } + + String url = "/query?"; +#if defined _DEBUG + url += "pretty=true&"; +#endif + url += _db; + url += "&q=" + URLEncode(sql); + DEBUG_PRINT("Requesting URL: "); + DEBUG_PRINT(url); + + // This will send the request to the server + print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + _host + + ":" + _port + "\r\n" + "Connection: close\r\n\r\n"); + + // Read all the lines of the reply from server and print them to Serial + uint8_t t = 0; + while (!available() && t < 200) { + delay(10); + t++; + } + if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out. + + DEBUG_PRINT("Receiving...."); + uint8_t i=0; + String line = readStringUntil('\n'); + DEBUG_PRINT("[HEAD] " + line); + + if (line.substring(9,12) == "200") { + while (available()) { + line = readStringUntil('\n'); + DEBUG_PRINT("(HEAD) " + line); + if (i < 6 ) i++; else return _response; + } + _response = DB_SUCCESS; + } + else{ + _response = DB_ERROR; +#if defined _DEBUG + while (available()) { + line = readStringUntil('\n'); + DEBUG_PRINT("[HEAD] " + line); + } +#endif + } + + return _response; +} + +DB_RESPONSE Influxdb::response() { + return _response; +} + +/* -----------------------------------------------*/ +// Field object +/* -----------------------------------------------*/ +FIELD::FIELD(String m) { + measurement = m; +} + +void FIELD::empty() { + _data = ""; + _tag = ""; +} + +void FIELD::addTag(String key, String value) { + _tag += "," + key + "=" + value; +} + +void FIELD::addField(String key, float value) { + _data = (_data == "") ? (" ") : (_data += ","); + _data += key + "=" + String(value); +} + +String FIELD::postString() { + // uint32_t utc = 1448114561 + millis() /1000; + return measurement + _tag + _data; +} + +// URL Encode with Arduino String object +String URLEncode(String msg) { + const char *hex = "0123456789abcdef"; + String encodedMsg = ""; + + uint16_t i; + for (i = 0; i < msg.length(); i++) { + if (('a' <= msg.charAt(i) && msg.charAt(i) <= 'z') || + ('A' <= msg.charAt(i) && msg.charAt(i) <= 'Z') || + ('0' <= msg.charAt(i) && msg.charAt(i) <= '9')) { + encodedMsg += msg.charAt(i); + } else { + encodedMsg += '%'; + encodedMsg += hex[msg.charAt(i) >> 4]; + encodedMsg += hex[msg.charAt(i) & 15]; + } + } + return encodedMsg; +} diff --git a/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.h b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.h new file mode 100755 index 0000000..4b0f78e --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.h @@ -0,0 +1,72 @@ +/* Influxdb library + + MIT license + Written by HW Wong + */ + +#ifndef INFLUXDB_H +#define INFLUXDB_H +#include "Arduino.h" +#include + +enum DB_RESPONSE {DB_SUCCESS, DB_ERROR, DB_CONNECT_FAILED}; + +// Url encode function +String URLEncode(String msg); + +class FIELD +{ +public: + FIELD(String m); + + String measurement; + + void addField(String key, float value); + void addTag(String key, String value); + void empty(); + String postString(); + +private: + String _data; + String _tag; + +}; + +class Influxdb : private WiFiClient +{ +public: + Influxdb(const char* host, uint16_t port); + + DB_RESPONSE opendb(String db); + DB_RESPONSE opendb(String db, String user, String password); + DB_RESPONSE write(FIELD data); + DB_RESPONSE write(String data); + DB_RESPONSE query(String sql); + //uint8_t createDatabase(char *dbname); + DB_RESPONSE response(); + + using WiFiClient::available; + using WiFiClient::read; + using WiFiClient::flush; + using WiFiClient::find; + using WiFiClient::findUntil; + using WiFiClient::peek; + using WiFiClient::readBytes; + using WiFiClient::readBytesUntil; + using WiFiClient::readString; + using WiFiClient::readStringUntil; + using WiFiClient::parseInt; + using WiFiClient::setTimeout; + +private: + uint16_t _port; + const char* _host; + String _db; + DB_RESPONSE _response; + +}; + + + + +#endif diff --git a/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb.cpp b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb.cpp new file mode 100755 index 0000000..caf16bc --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb.cpp @@ -0,0 +1,176 @@ +#include "Arduino.h" +#include "ESP8266Influxdb.h" +#include + +#define DEBUG_PRINT // comment this line to disable debug print + +#ifndef DEBUG_PRINT +#define DEBUG_PRINT(a) +#else +#define DEBUG_PRINT(a) (Serial.println(String(F("[Debug]: "))+(a))) +#define _DEBUG +#endif + +Influxdb::Influxdb(const char *host, uint16_t port) : WiFiClient() { + _port = port; + _host = host; +} + +DB_RESPONSE Influxdb::opendb(String db, String user, String password) { + _db = "db=" + db + "&u=" + user + "&p=" + password; +} + +DB_RESPONSE Influxdb::opendb(String db) { + _db = "db=" + db; + +} + +DB_RESPONSE Influxdb::write(FIELD data) { + return write(data.postString()); +} + +DB_RESPONSE Influxdb::write(String data) { + if (!connect(_host, _port)) { + DEBUG_PRINT("connection failed"); + _response = DB_CONNECT_FAILED; + return _response; + } + String postHead = "POST /write?" + _db + " HTTP/1.1\r\n"; + postHead += "Host: " + String(_host) + ":" + String(_port) + "\r\n"; + // postHead += "Content-Type: application/x-www-form-urlencoded\r\n"; + postHead += "Content-Length: " + String(data.length()) + "\r\n\r\n"; + + DEBUG_PRINT("Writing data to " + String(_host) + ":" + String(_port)); + print(postHead + data); + DEBUG_PRINT(postHead + data); + + uint8_t t = 0; + // Check the reply whether writing is success or not + while (!available() && t < 200) { + delay(10); + t++; + } + if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out. + +#if !defined _DEBUG + if (available()) { + _response = (findUntil("204", "\r")) ? DB_SUCCESS : DB_ERROR; + return _response; + } +#else + _response=DB_ERROR; + while (available()) { + String line = readStringUntil('\n'); + if (line.substring(9,12)=="204") + _response = DB_SUCCESS; + DEBUG_PRINT("(Responsed): " + line); + } + return _response; +#endif + return DB_ERROR; +} + +DB_RESPONSE Influxdb::query(String sql) { + + if (!connect(_host, _port)) { + DEBUG_PRINT("connection failed"); + _response = DB_CONNECT_FAILED; + return _response; + } + + String url = "/query?"; +#if defined _DEBUG + url += "pretty=true&"; +#endif + url += _db; + url += "&q=" + URLEncode(sql); + DEBUG_PRINT("Requesting URL: "); + DEBUG_PRINT(url); + + // This will send the request to the server + print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + _host + + ":" + _port + "\r\n" + "Connection: close\r\n\r\n"); + + // Read all the lines of the reply from server and print them to Serial + uint8_t t = 0; + while (!available() && t < 200) { + delay(10); + t++; + } + if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out. + + DEBUG_PRINT("Receiving...."); + uint8_t i=0; + String line = readStringUntil('\n'); + DEBUG_PRINT("[HEAD] " + line); + + if (line.substring(9,12) == "200") { + while (available()) { + line = readStringUntil('\n'); + DEBUG_PRINT("(HEAD) " + line); + if (i < 6 ) i++; else return _response; + } + _response = DB_SUCCESS; + } + else{ + _response = DB_ERROR; +#if defined _DEBUG + while (available()) { + line = readStringUntil('\n'); + DEBUG_PRINT("[HEAD] " + line); + } +#endif + } + + return _response; +} + +DB_RESPONSE Influxdb::response() { + return _response; +} + +/* -----------------------------------------------*/ +// Field object +/* -----------------------------------------------*/ +FIELD::FIELD(String m) { + measurement = m; +} + +void FIELD::empty() { + _data = ""; + _tag = ""; +} + +void FIELD::addTag(String key, String value) { + _tag += "," + key + "=" + value; +} + +void FIELD::addField(String key, float value) { + _data = (_data == "") ? (" ") : (_data += ","); + _data += key + "=" + String(value); +} + +String FIELD::postString() { + // uint32_t utc = 1448114561 + millis() /1000; + return measurement + _tag + _data; +} + +// URL Encode with Arduino String object +String URLEncode(String msg) { + const char *hex = "0123456789abcdef"; + String encodedMsg = ""; + + uint16_t i; + for (i = 0; i < msg.length(); i++) { + if (('a' <= msg.charAt(i) && msg.charAt(i) <= 'z') || + ('A' <= msg.charAt(i) && msg.charAt(i) <= 'Z') || + ('0' <= msg.charAt(i) && msg.charAt(i) <= '9')) { + encodedMsg += msg.charAt(i); + } else { + encodedMsg += '%'; + encodedMsg += hex[msg.charAt(i) >> 4]; + encodedMsg += hex[msg.charAt(i) & 15]; + } + } + return encodedMsg; +} diff --git a/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb.h b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb.h new file mode 100755 index 0000000..4b0f78e --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb.h @@ -0,0 +1,72 @@ +/* Influxdb library + + MIT license + Written by HW Wong + */ + +#ifndef INFLUXDB_H +#define INFLUXDB_H +#include "Arduino.h" +#include + +enum DB_RESPONSE {DB_SUCCESS, DB_ERROR, DB_CONNECT_FAILED}; + +// Url encode function +String URLEncode(String msg); + +class FIELD +{ +public: + FIELD(String m); + + String measurement; + + void addField(String key, float value); + void addTag(String key, String value); + void empty(); + String postString(); + +private: + String _data; + String _tag; + +}; + +class Influxdb : private WiFiClient +{ +public: + Influxdb(const char* host, uint16_t port); + + DB_RESPONSE opendb(String db); + DB_RESPONSE opendb(String db, String user, String password); + DB_RESPONSE write(FIELD data); + DB_RESPONSE write(String data); + DB_RESPONSE query(String sql); + //uint8_t createDatabase(char *dbname); + DB_RESPONSE response(); + + using WiFiClient::available; + using WiFiClient::read; + using WiFiClient::flush; + using WiFiClient::find; + using WiFiClient::findUntil; + using WiFiClient::peek; + using WiFiClient::readBytes; + using WiFiClient::readBytesUntil; + using WiFiClient::readString; + using WiFiClient::readStringUntil; + using WiFiClient::parseInt; + using WiFiClient::setTimeout; + +private: + uint16_t _port; + const char* _host; + String _db; + DB_RESPONSE _response; + +}; + + + + +#endif diff --git a/firmware/libraries/ESP8266Influxdb/README 2.md b/firmware/libraries/ESP8266Influxdb/README 2.md new file mode 100755 index 0000000..99ad2ec --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/README 2.md @@ -0,0 +1 @@ +# ESP8266Influxdb diff --git a/firmware/libraries/ESP8266Influxdb/README.md b/firmware/libraries/ESP8266Influxdb/README.md new file mode 100755 index 0000000..99ad2ec --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/README.md @@ -0,0 +1 @@ +# ESP8266Influxdb diff --git a/firmware/libraries/ESP8266Influxdb/examples/influxdb_write/influxdb_write.ino b/firmware/libraries/ESP8266Influxdb/examples/influxdb_write/influxdb_write.ino new file mode 100755 index 0000000..c89fc0b --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/examples/influxdb_write/influxdb_write.ino @@ -0,0 +1,63 @@ + +#include +#include +#include +#include + +const char *INFLUXDB_HOST = "host_or_ip"; +const uint16_t INFLUXDB_PORT = 8086; + +const char *DATABASE = "dbname"; +const char *DB_USER = "dbuser"; +const char *DB_PASSWORD = "dbpassword"; + +ESP8266WiFiMulti WiFiMulti; +Influxdb influxdb(INFLUXDB_HOST, INFLUXDB_PORT); + +void setup() { + Serial.begin(115200); + WiFiMulti.addAP("SSID", "PASSWORD"); + while (WiFiMulti.run() != WL_CONNECTED) { + delay(100); + } + Serial.println("Ready"); + influxdb.opendb(DATABASE, DB_USER, DB_PASSWORD); +} + +void loop() { + // Writing data with influxdb HTTP API + // https://influxdb.com/docs/v0.9/guides/writing_data.html + Serial.println("Writing data to host " + String(INFLUXDB_HOST) + ":" + + INFLUXDB_PORT + "'s database=" + DATABASE); + String data = "analog_read,method=HTTP_API,pin=A0 value=" + String(analogRead(A0)); + influxdb.write(data); + Serial.println(influxdb.response() == DB_SUCCESS ? "HTTP write success" + : "Writing failed"); + + // Writing data using FIELD object + // Create field object with measurment name=analog_read + FIELD dataObj("analog_read"); + dataObj.addTag("method", "Field_object"); // Add method tag + dataObj.addTag("pin", "A0"); // Add pin tag + dataObj.addField("value", analogRead(A0)); // Add value field + Serial.println(influxdb.write(dataObj) == DB_SUCCESS ? "Object write success" + : "Writing failed"); + + // Empty field object. + dataObj.empty(); + + // Querying Data + // https://influxdb.com/docs/v0.9/query_language/query_syntax.html + Serial.println("Querying data ........"); + + String sql = "select * from analog_read order by time desc limit 2"; + if (influxdb.query(sql) == DB_SUCCESS) { + while (influxdb.available()) { + String line = influxdb.readStringUntil('\n'); + Serial.println(line); + } + } + else + Serial.println("Query Failed"); + delay(30000); +} diff --git a/firmware/libraries/ESP8266Influxdb/keywords 2.txt b/firmware/libraries/ESP8266Influxdb/keywords 2.txt new file mode 100755 index 0000000..6b493f8 --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/keywords 2.txt @@ -0,0 +1,24 @@ +################################################## +# Syntax Coloring Map For ESP8266 Influxdb library +################################################## + +################################################## +# Datatypes (KEYWORD1) +################################################## + +Influxdb KEYWORD1 +FIELD KEYWORD1 +DB_RESPOND KEYWORD1 + +################################################## +# Methods and Functions (KEYWORD2) +################################################## + +addField KEYWORD2 +addTag KEYWORD2 +empty KEYWORD2 +opendb KEYWORD2 +write KEYWORD2 +query KEYWORD2 +postString KEYWORD2 +response KEYWORD2 diff --git a/firmware/libraries/ESP8266Influxdb/keywords.txt b/firmware/libraries/ESP8266Influxdb/keywords.txt new file mode 100755 index 0000000..6b493f8 --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/keywords.txt @@ -0,0 +1,24 @@ +################################################## +# Syntax Coloring Map For ESP8266 Influxdb library +################################################## + +################################################## +# Datatypes (KEYWORD1) +################################################## + +Influxdb KEYWORD1 +FIELD KEYWORD1 +DB_RESPOND KEYWORD1 + +################################################## +# Methods and Functions (KEYWORD2) +################################################## + +addField KEYWORD2 +addTag KEYWORD2 +empty KEYWORD2 +opendb KEYWORD2 +write KEYWORD2 +query KEYWORD2 +postString KEYWORD2 +response KEYWORD2 diff --git a/firmware/libraries/ESP8266_Influxdb/CHANGELOG.md b/firmware/libraries/ESP8266_Influxdb/CHANGELOG.md new file mode 100644 index 0000000..fb8da21 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/CHANGELOG.md @@ -0,0 +1,148 @@ +# Changelog +## 3.12.1 [2022-08-29] +### Fixes +- [193](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/193) - Automatically adjusting point timestamp according to the setting of write precision. + +## 3.12.0 [2022-03-21] +### Features +- [185](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/185) - Added diagnostic server connection state getter `bool InfluxDBClient::isConnected()` + +## 3.11.0 [2022-02-18] +### Features + - [174](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/174),[181](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/181) - All API methods with a string param allow specifying string by all basic types: + - Arduino `String` class + - C `char *` or `char[]` + - Flash string using `F`,`PSTR` or `FPSTR` macros +### Fixes + - [176](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/176) - Cleared all compiler warnings + +## 3.10.0 [2022-01-20] +### Features + - [167](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/167) - Added `InfluxDBClient::writeRecord(const char *record)`. + - [167](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/167) - Added possibility to disable retrying by setting `maxRetryAttempts` to zero: `client.setWriteOptions(WriteOptions().maxRetryAttempts(0));` + - [172](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/172) - Added directly streaming batch for write. It can be enabled by `InfluxDBClient::setStreamWrite(bool enable = true)`. Writing by streaming lines of batch saves RAM as it sends data without allocating a buffer. On the other hand, this way of writing is about half times slower than the classic way, when allocating the buffer for writing the whole batch. + - [172](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/172) - Allowing larger batch size, > 255. + - [173](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/173) - Added Flux query parameters. Now supported by InfluxDB Cloud only. + +## 3.9.0 [2021-09-17] +### Features + - [#147](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/147) - Updated InfluxDB 2 Cloud CA root certificate to _ISRG Root X1_. + Current InfluxDB 2 Cloud CA root certificate _DST Root CA X3_ expires on September 30th 2021! + - [#157](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/157) - Added Buckets sub-client for managing buckets in InfluxDB 2. + +### Fixes + - [#150](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/150) - `HTTPOptions::httpReadTimeout` is also set as the connect timeout for HTTP connection on ESP32. It also works for HTTPS connection since ESP32 Arduino Core 2.0.0. + - [#156](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/156) - Correctly rounding _writeBufferSize_, when _bufferSize/batchSize >= 256_. + - [#162](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/162) - Fixed flushing of not full buffer after the flush timeout. + + ### Documentation + - [#163](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/163) - More precise description of supported devices. + +## 3.8.0 [2021-04-01] +### Features + - [#143](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/143) - `InfluxDBClient::setInsecure` now works also for ESP32. Requires Arduino ESP32 SDK 1.0.5 or higher + +### Documentation + - [#134](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/134): + - Added untrusted connection (skipping certificate validation) info to Readme + - `SecureWrite` and `SecureBatchWrite` demos enhanced with example about using untrusted connection + - Various fixes of typos + +### Fixes + - [#137](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/137) - Fixed parsing Flux response with unexpected annotations + +## 3.7.0 [2020-12-24] +### Features + - [#125](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/124) - Added credentials to the InfluxDB 1.x validation endpoint (/ping). To leverage this, [enable ping authentication](https://docs.influxdata.com/influxdb/v1.8/administration/config/#ping-auth-enabled-false) + +### Fixes + - [#129](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/129) - Updated InfluxDB 2 Cloud CA certificate to trust servers from all cloud providers (AWS, Azure, GCP) + +## 3.6.1 [2020-11-30] +### Features +### Fixes +- [#121](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/121) - Fixed compile error in case of warning is treated as an error +- [#122](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/122) - Deleting WiFiClient instance to avoid memory leaking when the InfluxDBClient is reinitialized +- [#124](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/124) - Fixed compilation warnings + +### Doc +- [#120](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/120) - Improved language wording in the Readme + +## 3.6.0 [2020-11-10] +### Features +- [#117](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/117) - Added `InfluxDBClient::pointToLineProtocol(const Point& point)` for simple creation of InfluxDB line-protocol string with respect to default tags + +### Fixes +- [#114](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/114) - Renamed `getRemaingRetryTime()`->`getRemainingRetryTime()` +- [#115](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/115) - Restored writing capability after a connection failure +- [#118](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/118) - Added escaping of URL params (org, bucker, V1 username and pass) + +## 3.5.0 [2020-10-30] +### Features + - [#107](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/107) - Added possibility to set default tags. Use `WriteOptions::addDefaultTag()` to add a tag that will be added to each written point using the `writePoint()` function. + - [#109](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/109) - Retry strategy improvements: + - Added `canSendRequest()` function to check if retry strategy is applied + - Added `getRemaingRetryTime()` function to get wait time before another request (write/query) can be sent + - Removed applying retry wait time in case of network error + - Better explanatory error message when a request is about to be sent in the retry wait state + +### Fixes +- [#108](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/108) - Added optional param for specifying decimal places of double.: `void Point::addField(String name, double value, int decimalPlaces = 2)` +- [#111](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/111) - Fixed blocked writing after another point reached max retry count (#110) + +## 3.4.0 [2020-10-02] +### Features + - [#89](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/89) - ESP8266 only - Added Max Fragment Length Negotiation for TLS communication to reduce memory allocation. If server supports MFLN, it saves ~10kB. Standalone InfluxDB OSS server doesn't support MFLN, Cloud yes. To leverage MFLN for standalone OSS, a reverse proxy needs to be used. + - [#91](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/91) - Improved API for settings of write and HTTP options: + - Introduced `WriteOptions` to wrap the write related options (write precision, batch-size, etc). It offers fluent style API allowing to change only the required options. `InfluxDBClient` has overloaded `setWriteOptions(const WriteOptions& writeOptions)` method. + - Introduced `HTTPOptions` to wrap the HTTP related options (e.g. reusing connection). It offers fluent style API allowing to change only the required options. `InfluxDBClient` has `setHTTPOptions(const HTTPOptions& httpOptions)` method. + - Added possibility to set HTTP response read timeout (part of the `HTTPOptions`). + - Method `InfluxDBClient::void setWriteOptions(WritePrecision precision, uint16_t batchSize = 1, uint16_t bufferSize = 5, uint16_t flushInterval = 60, bool preserveConnection = true)` is deprecated and it will be removed in the next release. + - [#93](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/93) - Write logic improvements + - Retry on failure logic unification with other InfluxDB clients (exponential retry, max retry count 3, max retry interval) + - Better write buffer memory management + +### Documentation + - [#87](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/87) - Fixed include file name in the Readme + - [#99](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/99) - Changed default InfluxDB 2 port from 9999 to 8086 (default since InfluxDB 2 RC0) + +### Fixes + - [#90](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/90) - Fixed boolean type recognition of InfluxDB Flux + - [#101](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/101) - Better memory efficient point line composition + +## Version 3.3.0 (2020-07-07) + - [NEW] Added possibility skip server certification validation (`setInsecure()` method) + - [NEW] Added possibility to query flux on secured InfluxDB 1.8 using V1 approach + - [NEW] `validateConnection()` can be used also for the [forward compatibility](https://docs.influxdata.com/influxdb/latest/tools/api/#influxdb-2-0-api-compatibility-endpoints) connection to InfluxDB 1.8 + - [FIX] More precise default timestamp generating, up to microseconds + - [FIX] Debug compilation error + - [FIX] SecureBatchWrite compile error + +## Version 3.2.0 (2020-06-09) +- [NEW] Added possibility to read data from InfluxDB using Flux queries +- [NEW] `timeSync` utility function for synchronous time synchronization using NTP +- [FIX] Properly initialize member variable (#59) +- [FIX] ASCII chars & compilation warning fix (#60) +- [Update] ESP8266 SDK 2.7+ required + +## Version 3.1.3 (2020-04-27) + - [FIX] SecureWrite crash (#54) + +## Version 3.1.2 (2020-04-18) + - [FIX] Compilation error on fields order (#43) + - [FIX] Invalid precision constant for microseconds (#49) + - [FIX] Write error in case point has no tags (#50) + +## Version 3.1.1 (2020-04-06) + - [Updated] CA Certificate for SSL (#38) + +## Version 3.1.0 (2020-03-12) + - [NEW] Added User-agent header + - [FIX] status code check when pinging an InfluxDB version 1.x instance + +## Version 3.0.0 (2020-02-11) + - New API with similar keywords as other official InfluxDB clients + - Richer set of data types for fields and timestamp methods + - Advanced features, such as implicit batching, automatic retrying on server back-pressure and connection failure, along with secured communication over TLS supported for both devices and authentication + - Special characters escaping + - Backward support for original API of V1/V2 diff --git a/firmware/libraries/ESP8266_Influxdb/LICENSE b/firmware/libraries/ESP8266_Influxdb/LICENSE new file mode 100644 index 0000000..35659e0 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018-2020 Tobias Schürg, InfluxData + +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/firmware/libraries/ESP8266_Influxdb/README.md b/firmware/libraries/ESP8266_Influxdb/README.md new file mode 100644 index 0000000..35e5058 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/README.md @@ -0,0 +1,696 @@ +[![PlatformIO](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/workflows/PlatformIO/badge.svg)](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/actions/) + +# InfluxDB Arduino Client + +Simple Arduino client for writing and reading data from [InfluxDB](https://www.influxdata.com/products/influxdb-overview/), no matter whether it is a local server or InfluxDB Cloud. The library supports authentication, secure communication over TLS, [batching](#writing-in-batches), [automatic retrying](#buffer-handling-and-retrying) on server back-pressure and connection failure. + +It also allows setting data in various formats, automatically escapes special characters and offers specifying timestamp in various precisions. + +Library supports both [InfluxDB 2](#basic-code-for-influxdb-2) and [InfluxDB 1](#basic-code-for-influxdb-2). + +This is a new implementation and the API, [original API](#original-api) is still supported. + +Supported devices: + - ESP8266 with [Arduino core for ESP8266](https://github.com/esp8266/Arduino) at least version [3.0.2](https://github.com/esp8266/Arduino/releases/tag/3.0.2). + - ESP32 with [Arduino core for the ESP32](https://github.com/espressif/arduino-esp32) at least version [2.0.2](https://github.com/espressif/arduino-esp32/releases/tag/2.0.2). + +This library doesn't support using those devices as a peripheral. + +:warning: Only connection over internal WiFi capability is supported for now. + +## Table of contents +- [InfluxDB Arduino Client](#influxdb-arduino-client) + - [Basic code for InfluxDB 2](#basic-code-for-influxdb-2) + - [Basic code for InfluxDB 1](#basic-code-for-influxdb-1) + - [Connecting to InfluxDB Cloud 2](#connecting-to-influxdb-cloud-2) + - [Writing in Batches](#writing-in-batches) + - [Timestamp](#timestamp) + - [Configure Time](#configure-time) + - [Batch Size](#batch-size) + - [Large Batch Size](#large-batch-size) + - [Write Modes](#write-modes) + - [Buffer Handling and Retrying](#buffer-handling-and-retrying) + - [Write Options](#write-options) + - [HTTP Options](#http-options) + - [Secure Connection](#secure-connection) + - [InfluxDb 2](#influxdb-2) + - [InfluxDb 1](#influxdb-1) + - [Skipping certificate validation](#skipping-certificate-validation) + - [Querying](#querying) + - [Parametrized Queries](#parametrized-queries) + - [Original API](#original-api) + - [Initialization](#initialization) + - [Sending a single measurement](#sending-a-single-measurement) + - [Write multiple data points at once](#write-multiple-data-points-at-once) + - [Troubleshooting](#troubleshooting) + - [Contributing](#contributing) + - [License](#license) + + +## Basic code for InfluxDB 2 +After [setting up an InfluxDB 2 server](https://docs.influxdata.com/influxdb/v2.0/get-started/), first define connection parameters and a client instance: +```cpp +// InfluxDB 2 server url, e.g. http://192.168.1.48:8086 (Use: InfluxDB UI -> Load Data -> Client Libraries) +#define INFLUXDB_URL "influxdb-url" +// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> ) +#define INFLUXDB_TOKEN "token" +// InfluxDB 2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> ) +#define INFLUXDB_ORG "org" +// InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets) +#define INFLUXDB_BUCKET "bucket" +``` + +You need to pass an additional parameter to the client constructor, which is a certificate of the server to trust. The constant `InfluxDbCloud2CACert` contains the InfluxDB Cloud 2 CA certificate, which is predefined in this library: +```cpp +// Single InfluxDB instance +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); +``` +Read more about [secure connection](#secure-connection). + +Additionally, time needs to be synced: +```cpp +// Synchronize time with NTP servers and set timezone +// Accurate time is necessary for certificate validation and writing in batches +// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ +configTzTime(TZ_INFO "pool.ntp.org", "time.nis.gov"); +``` +Read more about time synchronization in [Configure Time](#configure-time). + +Defining data and writing it to the DB is the same as in the case of [BasicWrite](#basic-code): +```cpp +// Define data point with measurement name 'device_status` +Point pointDevice("device_status"); +// Set tags +pointDevice.addTag("device", "ESP8266"); +pointDevice.addTag("SSID", WiFi.SSID()); +// Add data +pointDevice.addField("rssi", WiFi.RSSI()); +pointDevice.addField("uptime", millis()); + +// Write data +client.writePoint(pointDevice); +``` +Complete source code is available in [SecureWrite example](examples/SecureWrite/SecureWrite.ino). + +## Writing in Batches +InfluxDB client for Arduino can also write data in batches. A batch is simply a set of points that will be sent at once. To create a batch, the client will keep all points until the number of points reaches the batch size and then it will write all points at once to the InfluxDB server. This is often more efficient than writing each point separately. + +### Timestamp +If using batch writes, the timestamp should be employed. Timestamp specifies the time when data was gathered and it is used in the form of a number of seconds (milliseconds, etc) from epoch (1.1.1970) UTC. +If points have no timestamp assigned, InfluxDB assigns a timestamp at the time of writing, which could happen much later than the data has been obtained, because the final batch write will happen when the batch is full (or when [flush buffer](#buffer-handling-and-retrying) is forced). + +InfluxDB allows sending timestamps in various precisions - nanoseconds, microseconds, milliseconds or seconds. The milliseconds precision is usually enough for using on Arduino. The maximum available precision is microseconds. Setting the timestamp to nanoseconds will just add zeroes for microseconds fraction and will not improve timestamp accuracy. + +The client has to be configured with a time precision. The default settings is to not use the timestamp, which means that the server will assign a timestamp when the data is written to the database. The `setWriteOptions` functions allows setting custom `WriteOptions` params and one of them is __write precision__: +``` cpp +// Set write precision to milliseconds. Leave other parameters default. +client.setWriteOptions(WriteOptions().writePrecision(WritePrecision::MS)); +``` +When a write precision is configured, the client will automatically assign the current time to the timestamp of each written point which doesn't have a timestamp assigned. + +If you want to manage timestamp on your own, there are several ways to set the timestamp explicitly. +- `setTime(WritePrecision writePrecision)` - Sets the timestamp to the actual time in the desired precision. The same precision must set in WriteOptions. +- `setTime(unsigned long long timestamp)` - Sets the timestamp to an offset since the epoch. Correct precision must be set InfluxDBClient::setWriteOptions. +- `setTime(String timestamp)` - Sets the timestamp to an offset since the epoch. Correct precision must be set InfluxDBClient::setWriteOptions. + +The `getTime()` method allows copying the timestamp between points. + + +### Configure Time +Dealing with timestamps, and also validating server or CA certificate, requires that the device has correctly set the time. This can be done with one line of code: +```cpp +// Synchronize time with NTP servers and set timezone +// Accurate time is necessary for certificate validation and writing in batches +// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ +configTzTime("PST8PDT", "pool.ntp.org", "time.nis.gov"); +``` +The `configTzTime` function starts the time synchronization with NTP servers. The first parameter specifies the timezone information, which is important for distinguishing between UTC and a local timezone and for daylight saving changes. +The last two string parameters are the internet addresses of NTP servers. Check [pool.ntp.org](https://www.pool.ntp.org/zone) for address of some local NTP servers. + +Timezone string details are described at [https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html](https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html). +Values for some timezones: +- Central Europe: `CET-1CEST,M3.5.0,M10.5.0/3` +- Eastern: `EST5EDT` +- Japanese: `JST-9` +- Pacific Time: `PST8PDT` + +There is also another function for syncing the time, which takes timezone and DST offset. As DST info is set via static offset it will create local time problem when DST change occurs. +It's declaration is following: +```cpp +configTime(long gmtOffset_sec, int daylightOffset_sec, const char* server1, const char* server2 = nullptr, const char* server3 = nullptr); +``` + +In the example code it would be: +```cpp +// Synchronize time with NTP servers +// Accurate time is necessary for certificate validation and writing in batches +configTime(3600, 3600, "pool.ntp.org", "time.nis.gov"); +``` + +Both `configTzTime` and `configTime` functions are asynchronous. This means that calling the functions just starts the time synchronization. Time is often not synchronized yet upon returning from call. + +There is a helper function `timeSync` provided with the this library. The function starts time synchronization by calling the `configTzTime` and waits maximum 20 seconds for time to be synchronized. It prints progress info and final local time to the `Serial` console. +`timeSync` has the same signature as `configTzTime` and it is included with the main header file `InfluxDbClient.h`: +```cpp +// Synchronize time with NTP servers and waits for competition. Prints waiting progress and final synchronized time to the Serial. +// Accurate time is necessary for certificate validation and writing points in batch +// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ +void timeSync(const char *tzInfo, const char* ntpServer1, const char* ntpServer2 = nullptr, const char* ntpServer3 = nullptr); +``` + +### Batch Size +Setting batch size depends on data gathering and DB updating strategy. + +If data is written in short periods (seconds), the batch size should be set according to your expected write periods and update frequency requirements. +For example, if you would like to see updates (on the dashboard or in processing) each minute and you are measuring a single value (1 point) every 10s (6 points per minute), the batch size should be 6. If it is sufficient to update each hour and you are creating 1 point each minute, your batch size should be 60. + +In cases where the data should be written in longer periods and gathered data consists of several points, the batch size should be set to the expected number of points to be gathered. + +To set the batch size we use `WriteOptions` object and [setWriteOptions](#write-options) function: +```cpp +// Enable lines batching +client.setWriteOptions(WriteOptions().batchSize(10)); +``` +Writing the point will add a point to the underlying buffer until the batch size is reached: +```cpp +// Write first point to the buffer +// Buffered write always returns `true` +client.writePoint(point1); +// Write second point to the buffer +client.writePoint(point2); +.. +// Write ninth point to the buffer +client.writePoint(point9); +// Writing tenth point will cause flushing buffer and returns actual write result. +if(!client.writePoint(point10)) { + Serial.print("InfluxDB write failed: "); + Serial.println(client.getLastErrorMessage()); +} +``` + +In case cases where the number of points is not always the same, set the batch size to the maximum number of points and use the `flushBuffer()` function to force writing to the database. See [Buffer Handling](#buffer-handling-and-retrying) for more details. + +### Large batch size +The maximum batch size depends on the available RAM of the device (~45KB for ESP8266 and ~260KB for ESP32). Larger batch size, >100 for ESP8255, >2000 for ESP32, must be chosen carefully to not crash the app with out of memory error. The Stream write mode must be used, see [Write Modes](#write-modes) + +Always determine your typical line length using `client.pointToLineProtocol(point).length()`. For example, ESP32 can handle 2048 lines with an average length of 69. When the length of line or batch size is increased, the device becomes unstable, even there is more than 76k, it cannot send data or even crashes. ESP8266 handles successfully 330 of such lines. + +:warning: Thoroughly test your app when using large batch files. + +### Write Modes +Client has two modes of writing: + - Buffer (default) + - Stream + +Writing is performed the way that client keeps written lines (points) separately and when a batch is completed, it allocates a data buffer for sending to a server via WiFi Client. +This is the fastest way to write data but requires some amount of free memory. Thus a big batch size cannot be used. + +Another way of writing is *stream write*. +```cpp + // Enables stream write + client.setStreamWrite(true); +``` +In this mode client continuously streams lines from batch to WiFi Client. No buffer allocation. As lines are allocated separately, it avoids problems with max allocable block size. The downside is, that writing is about 50% slower than in the Buffer mode. + +## Buffer Handling and Retrying +InfluxDB contains an underlying buffer for handling writing in batches and automatic retrying on server back-pressure and connection failure. + +Its size is controlled by the `bufferSize` param of [WriteOptions](#write-options) object: +```cpp +// Increase buffer to allow caching of failed writes +client.setWriteOptions(WriteOptions().bufferSize(50)); +``` +The recommended size is at least 2 x batch size. + +The state of the buffer can be determined via two functions: + - `isBufferEmpty()` - Returns true if buffer is empty + - `isBufferFull()` - Returns true if buffer is full + + A full buffer can occur when there is a problem with the internet connection or the InfluxDB server is overloaded. In such cases, points to write remain in the buffer. When more points are added and connection problem remains, the buffer will reach the top and new points will overwrite older points. + + Each attempt to write a point will try to send older points in the buffer. So, the `isBufferFull()` function can be used to skip low priority points. + +The `flushBuffer()` function can be used to force writing, even if the number of points in the buffer is lower than the batch size. With the help of the `isBufferEmpty()` function a check can be made before a device goes to sleep: + + ```cpp + // Check whether buffer in not empty + if (!client.isBufferEmpty()) { + // Write all remaining points to db + client.flushBuffer(); + } +``` + +Other functions for dealing with buffer: + - `checkBuffer()` - Checks point buffer status and flushes if the number of points reaches batch size or flush interval runs out. This is the main function for controlling the buffer and it is used internally. + - `resetBuffer()` - Clears the buffer. + +Check [SecureBatchWrite example](examples/SecureBatchWrite/SecureBatchWrite.ino) for example code of buffer handling functions. + +## Write Options +Writing points can be controlled via `WriteOptions`, which is set in the `setWriteOptions` function: + +| Parameter | Default Value | Meaning | +|-----------|---------------|---------| +| writePrecision | `WritePrecision::NoTime` | Timestamp precision of written data | +| batchSize | `1` | Number of points that will be written to the database at once | +| bufferSize | `5` | Maximum number of points in buffer. Buffer contains new data that will be written to the database and also data that failed to be written due to network failure or server overloading | +| flushInterval | `60` | Maximum time(in seconds) data will be held in buffer before points are written to the db | +| retryInterval | `5` | Default retry interval in sec, if not sent by server. Value `0` disables retrying | +| maxRetryInterval | `300` | Maximum retry interval in sec | +| maxRetryAttempts | `3` | Maximum count of retry attempts of failed writes | + +## HTTP Options +`HTTPOptions` controls some aspects of HTTP communication and they are set via `setHTTPOptions` function: +| Parameter | Default Value | Meaning | +|-----------|---------------|---------| +| connectionReuse | `false` | Whether HTTP connection should be kept open after initial communication. Usable for frequent writes/queries. | +| httpReadTimeout | `5000` | Timeout (ms) for reading server response | + +## Secure Connection +Connecting to a secured server requires configuring the client to trust the server. This is achieved by providing the client with a server certificate, certificate authority certificate or certificate SHA1 fingerprint. + +:memo: In ESP32 arduino SDK (1.0.4), `WiFiClientSecure` doesn't support fingerprint to validate the server certificate. + +The certificate (in PEM format) or SHA1 fingerprint should be placed in flash memory to save RAM. +Code bellow is an example certificate in PEM format. Valid InfluxDB 2 Cloud CA certificate is included in the library in the constant `InfluxDbCloud2CACert`, located in the `InfluxDBCloud.h`. + +You can use a custom server certificate by exporting it, e.g. using a web browser: +```cpp +// Server certificate in PEM format, placed in the program (flash) memory to save RAM +const char ServerCert[] PROGMEM = R"EOF( +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- +)EOF"; + +// Alternatively, use a fingerprint of server certificate to set trust. Works only for ESP8266. +const char ServerCert[] PROGMEM = "cabd2a79a1076a31f21d253635cb039d4329a5e8"; +``` + +### InfluxDb 2 +There are two ways to set the certificate or fingerprint to trust a server: + - Use full param constructor +```cpp +// InfluxDB client instance with preconfigured InfluxCloud certificate +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert); +``` +- Use `setConnectionParams` function: +```cpp +// InfluxDB client instance +InfluxDBClient client; + +void setup() { + // configure client + client.setConnectionParams(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert); +} +``` +### InfluxDb 1 + +Use `setConnectionParamsV1` function: +```cpp +// InfluxDB client instance +InfluxDBClient client; + +void setup() { + // configure client + client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASSWORD, ServerCert); +} +``` +Another important prerequisite to successfully validate a server or CA certificate is to have properly synchronized time. More on this in [Configure Time](#configure-time). + +:information_source: Time synchronization is not required for validating server certificate via SHA1 fingerprint. + +### Skipping certificate validation +The CA certificate provided with the library is ISRG Root X1. This certificate lasts a very long time, until 2035. It is not necessary to update your device until then when using ISRG Root X1. + +If you are using your own certificate, plase keep in mind server certificates have limited validity period, often only a few months. It will be necessary to frequently change trusted certificate in the source code and reflashing the device. A solution could be using OTA update, but you will still need to care about certificate validity and updating it ahead of time to avoid connection failures. + +The best way to prevent frequent updates is to use a root certificate like the one provided with the library. If you are unable to use a root certificate from a trusted authority, you may want to use insecure mode instead. This is done with the help of `InfluxDBClient::setInsecure()` method. +You will also save space in flash (and RAM) by leaving certificate param empty when calling constructor or `setConnectionParams` method. + +:memo: The `InfluxDBClient::setInsecure()` method must be called before calling any function that will establish connection. The best place to call it is in the `setup` method: + +```cpp +// InfluxDB client instance without a server certificate +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN); + +void setup() { + // Set insecure connection to skip server certificate validation + client.setInsecure(); +} +``` + +:warning: Using untrusted connection is a security risk. + +## Querying +InfluxDB 2 and InfluxDB 1.7+ (with [enabled flux](https://docs.influxdata.com/influxdb/latest/administration/config/#flux-enabled-false)) uses [Flux](https://www.influxdata.com/products/flux/) to process and query data. InfluxDB client for Arduino offers a simple, but powerful, way how to query data with `query` function. It parses response line by line, so it can read a huge responses (thousands data lines), without consuming a lot device memory. + +The `query` returns `FluxQueryResult` object, which parses response and provides useful getters for accessing values from result set. + +The InfluxDB flux query result set is returned in CSV format. In the example below, the first line contains type information and the second column names, and the rest is data: +```CSV +#datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,long,string,string,string,string +,result,table,_start,_stop,_time,_value,SSID,_field,_measurement,device +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:13Z,-55,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:27Z,-54,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:40Z,-54,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:54Z,-54,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:08:07Z,-55,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:08:20Z,-56,667G,rssi,wifi_status,ESP32 +``` + +Accessing data using `FluxQueryResult` requires knowing the query result structure, especially the name and the type of the column. The best practice is to tune the query +in the `InfluxDB Data Explorer` and use the final query with this library. + + Browsing thought the result set is done by repeatedly calling the `next()` method, until it returns false. Unsuccessful reading is distinguished by a non empty value from the `getError()` method. + As a flux query result can contain several tables, differing by grouping key, use the `hasTableChanged()` method to determine when there is a new table. + Single values are returned using the `getValueByIndex()` or `getValueByName()` methods. + All row values at once are retrieved by the `getValues()` method. + Always call the `close()` method at the of reading. + +A value in the flux query result column, retrieved by the `getValueByIndex()` or `getValueByName()` methods, is represented by the `FluxValue` object. +It provides getter methods for supported flux types: + +| Flux type | Getter | C type | +| ----- | ------ | --- | +| long | getLong() | long | +| unsignedLong | getUnsignedLong() | unsigned long | +| dateTime:RFC3339, dateTime:RFC3339Nano | getDateTime() | [FluxDateTime](src/query/FluxTypes.h#L100) | +| bool | getBool() | bool | +| double | bool | double | +| string, base64binary, duration | getString() | String | + +Calling improper type getter will result in a zero (empty) value. + +Check for null (missing) value using the `isNull()` method. + +Use the `getRawValue()` method for getting the original string form. + +```cpp +// Construct a Flux query +// Query will find RSSI for last 24 hours for each connected WiFi network with this device computed by given selector function +String query = "from(bucket: \"my-bucket\") |> range(start: -24h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\""; +query += "and r.device == \"ESP32\")"; +query += "|> max()"; + +// Send query to the server and get result +FluxQueryResult result = client.query(query); + +// Iterate over rows. Even there is just one row, next() must be called at least once. +while (result.next()) { + // Get typed value for flux result column 'SSID' + String ssid = result.getValueByName("SSID").getString(); + Serial.print("SSID '"); + Serial.print(ssid); + + Serial.print("' with RSSI "); + + // Get converted value for flux result column '_value' where there is RSSI value + long value = result.getValueByName("_value").getLong(); + Serial.print(value); + + // Format date-time for printing + // Format string according to http://www.cplusplus.com/reference/ctime/strftime/ + String timeStr = time.format("%F %T"); + + Serial.print(" at "); + Serial.print(timeStr); + + Serial.println(); +} + +// Check if there was an error +if(result.getError() != "") { + Serial.print("Query result error: "); + Serial.println(result.getError()); +} +``` +Complete source code is available in [QueryAggregated example](examples/QueryAggregated/QueryAggregated.ino). + +### Parametrized Queries +InfluxDB Cloud supports [Parameterized Queries](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/) +that let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more +reusable and can also be used to help prevent injection attacks. + +InfluxDB Cloud inserts the params object into the Flux query as a Flux record named `params`. Use dot or bracket +notation to access parameters in the `params` record in your Flux query. Parameterized Flux queries support only `int` +, `float`, and `string` data types. To convert the supported data types into +other [Flux basic data types, use Flux type conversion functions](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/#supported-parameter-data-types). + +Parameterized query example: +> :warning: Parameterized Queries are supported only in InfluxDB Cloud. There is no support in InfluxDB OSS currently. + +```cpp +// Prepare query parameters +QueryParams params; +params.add("bucket", INFLUXDB_BUCKET); +params.add("since", "-5m"); +params.add("device", DEVICE); +params.add("rssiThreshold", -50); + +// Construct a Flux query using parameters +// Parameters are accessed via the 'params' Flux object +// Flux only supports only string, float and int as parameters. Duration can be converted from string. +// Query will find RSSI less than defined threshold +String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \ + |> filter(fn: (r) => r._measurement == \"wifi_status\") \ + |> filter(fn: (r) => r._field == \"rssi\") \ + |> filter(fn: (r) => r.device == params.device) \ + |> filter(fn: (r) => r._value < params.rssiThreshold)"; + +// Print ouput header +// Print composed query +Serial.print("Querying with: "); +Serial.println(query); + +// Send query to the server and get result +FluxQueryResult result = client.query(query, params); + +//Print header +Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI"); + +for(int i=0;i<37;i++) { + Serial.print('-'); +} +Serial.println(); + +// Iterate over rows. Even there is just one row, next() must be called at least once. +int c = 0; +while (result.next()) { + // Get converted value for flux result column 'SSID' + String ssid = result.getValueByName("SSID").getString(); + + // Get converted value for flux result column '_value' where there is RSSI value + long rssi = result.getValueByName("_value").getLong(); + + // Get converted value for the _time column + FluxDateTime time = result.getValueByName("_time").getDateTime(); + + // Format date-time for printing + // Format string according to http://www.cplusplus.com/reference/ctime/strftime/ + String timeStr = time.format("%F %T"); + // Print formatted row + Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi); + c++; +} +if(!c) { + Serial.println(" No data found"); +} + +// Check if there was an error +if(result.getError() != "") { + Serial.print("Query result error: "); + Serial.println(result.getError()); +} + +// Close the result +result.close(); +``` +Complete source code is available in [QueryParams example](examples/QueryParams/QueryParams.ino). + +## Original API + +### Initialization +```cpp + #define INFLUXDB_HOST "192.168.0.32" + #define INFLUXDB_PORT 1337 + #define INFLUXDB_DATABASE "test" + //if used with authentication + #define INFLUXDB_USER "user" + #define INFLUXDB_PASS "password" + + // connect to WiFi + + Influxdb influx(INFLUXDB_HOST); // port defaults to 8086 + // or to use a custom port + Influxdb influx(INFLUXDB_HOST, INFLUXDB_PORT); + + // set the target database + influx.setDb(INFLUXDB_DATABASE); + // or use a db with auth + influx.setDbAuth(INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASS) // with authentication + +// To use the v2.0 InfluxDB +influx.setVersion(2); +influx.setOrg("myOrganization"); +influx.setBucket("myBucket"); +influx.setToken("myToken"); +influx.setPort(8086); +``` + +### Sending a single measurement +**Using an InfluxData object:** +```cpp +// create a measurement object +InfluxData measurement ("temperature"); +measurement.addTag("device", d2); +measurement.addTag("sensor", "dht11"); +measurement.addValue("value", 24.0); + +// write it into db +influx.write(measurement); +``` + +**Using raw-data** +```cpp + influx.write("temperature,device=d2,sensor=dht11 value=24.0") +``` + +### Write multiple data points at once +Batching measurements and send them with a single request will result in a much higher performance. +```cpp + +InfluxData measurement1 = readTemperature() +influx.prepare(measurement1) + +InfluxData measurement2 = readLight() +influx.prepare(measurement2) + +InfluxData measurement3 = readVoltage() +influx.prepare(measurement3) + +// writes all prepared measurements with a single request into db. +boolean success = influx.write(); +``` + +## Troubleshooting +All db methods return status. Value `false` means something went wrong. Call `getLastErrorMessage()` to get the error message. + +When error message doesn't help to explain the bad behavior, go to the library sources and in the file `src/util/debug.h` uncomment line 33: +```cpp +// Uncomment bellow in case of a problem and rebuild sketch +#define INFLUXDB_CLIENT_DEBUG_ENABLE +``` +Then upload your sketch again and see the debug output in the Serial Monitor. + +If you couldn't solve a problem by yourself, please, post an issue including the debug output. + +## Contributing + +If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the `master` branch. + +## License + +The InfluxDB Arduino Client is released under the [MIT License](https://opensource.org/licenses/MIT). diff --git a/firmware/libraries/ESP8266_Influxdb/examples/BasicWrite/BasicWrite.ino b/firmware/libraries/ESP8266_Influxdb/examples/BasicWrite/BasicWrite.ino new file mode 100644 index 0000000..e9e1784 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/examples/BasicWrite/BasicWrite.ino @@ -0,0 +1,98 @@ +/** + * Basic Write Example code for InfluxDBClient library for Arduino + * Data can be immediately seen in a InfluxDB UI: wifi_status measurement + * Enter WiFi and InfluxDB parameters below + * + * Measures signal level of the actually connected WiFi network + * This example supports only InfluxDB running from unsecure (http://...) + * For secure (https://...) or Influx Cloud 2 use SecureWrite example + **/ + +#if defined(ESP32) +#include +WiFiMulti wifiMulti; +#define DEVICE "ESP32" +#elif defined(ESP8266) +#include +ESP8266WiFiMulti wifiMulti; +#define DEVICE "ESP8266" +#endif + +#include + +// WiFi AP SSID +#define WIFI_SSID "ssid" +// WiFi password +#define WIFI_PASSWORD "password" +// InfluxDB server url. Don't use localhost, always server name or ip address. +// E.g. http://192.168.1.48:8086 (In InfluxDB 2 UI -> Load Data -> Client Libraries), +#define INFLUXDB_URL "influxdb-url" +// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> ) +// This token must have all buckets permission +#define INFLUXDB_TOKEN "toked-id" +// InfluxDB 2 organization id (Use: InfluxDB UI -> Settings -> Profile -> ) +#define INFLUXDB_ORG "org" +// Bucket name that doesn't exist in the db yet +#define INFLUXDB_BUCKET "test-bucket" + +void setup() { + Serial.begin(74880); + + // Connect WiFi + Serial.println("Connecting to " WIFI_SSID); + WiFi.mode(WIFI_STA); + wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); + while (wifiMulti.run() != WL_CONNECTED) { + Serial.print("."); + delay(500); + } + Serial.println(); +} + +// Creates client, bucket, writes data, verifies data and deletes bucket +void testClient() { + // InfluxDB client instance + InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN); + + // Check server connection + if (client.validateConnection()) { + Serial.print("Connected to InfluxDB: "); + Serial.println(client.getServerUrl()); + } else { + Serial.print("InfluxDB connection failed: "); + Serial.println(client.getLastErrorMessage()); + return; + } + + // Get dedicated client for buckets management + BucketsClient buckets = client.getBucketsClient(); + + // Verify bucket does not exist, or delete it + if(buckets.checkBucketExists(INFLUXDB_BUCKET)) { + Serial.println("Bucket " INFLUXDB_BUCKET " already exists, deleting" ); + // get reference + Bucket b = buckets.findBucket(INFLUXDB_BUCKET); + // Delete bucket + buckets.deleteBucket(b.getID()); + } + + // create a bucket with retention policy one month. Leave out or set zero to infinity + uint32_t monthSec = 30*24*3600; + Bucket b = buckets.createBucket(INFLUXDB_BUCKET, monthSec); + if(!b) { + // some error occurred + Serial.print("Bucket creating error: "); + Serial.println(buckets.getLastErrorMessage()); + return; + } + Serial.print("Created bucket: "); + Serial.println(b.toString()); + + int numPoints = 10; + // Write some points + for(int i=0;i range(start: -1h) |> pivot(rowKey:[\"_time\"],columnKey: [\"_field\"],valueColumn: \"_value\") |> count(column: \"humidity\")"; + FluxQueryResult result = client.query(query); + // We expect one row + if(result.next()) { + // Get count value + FluxValue val = result.getValueByName("humidity"); + if(val.getLong() != numPoints) { + Serial.print("Test failure, expected "); + Serial.print(numPoints); + Serial.print(" got "); + Serial.println(val.getLong()); + } else { + Serial.println("Test successfull"); + } + // Advance to the end + result.next(); + } else { + Serial.print("Query error: "); + Serial.println(result.getError()); + }; + result.close(); + + buckets.deleteBucket(b.getID()); +} + +void loop() { + // Lets do an E2E test + // call a client test + testClient(); + + Serial.println("Stopping"); + // Stop here, don't loop + while(1) delay(1); +} diff --git a/firmware/libraries/ESP8266_Influxdb/examples/QueryAggregated/QueryAggregated.ino b/firmware/libraries/ESP8266_Influxdb/examples/QueryAggregated/QueryAggregated.ino new file mode 100644 index 0000000..d20913d --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/examples/QueryAggregated/QueryAggregated.ino @@ -0,0 +1,163 @@ +/** + * QueryAggregated Example code for InfluxDBClient library for Arduino. + * + * This example demonstrates querying basic aggregated statistic parameters of WiFi signal level measured and stored in BasicWrite and SecureWrite examples. + * + * Demonstrates connection to any InfluxDB instance accesible via: + * - unsecured http://... + * - secure https://... (appropriate certificate is required) + * - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured) + * + * Enter WiFi and InfluxDB parameters below + **/ + +#if defined(ESP32) +#include +WiFiMulti wifiMulti; +#define DEVICE "ESP32" +#elif defined(ESP8266) +#include +ESP8266WiFiMulti wifiMulti; +#define DEVICE "ESP8266" +#endif + +#include +#include + +// WiFi AP SSID +#define WIFI_SSID "SSID" +// WiFi password +#define WIFI_PASSWORD "PASSWORD" +// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries) +// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086 +#define INFLUXDB_URL "server-url" +// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> ) +// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass +#define INFLUXDB_TOKEN "server token" +// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> ) +// InfluxDB 1.8+ (v2 compatibility API) use any non empty string +#define INFLUXDB_ORG "org name/id" +// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets) +// InfluxDB 1.8+ (v2 compatibility API) use database name +#define INFLUXDB_BUCKET "bucket name" + +// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html +// Examples: +// Pacific Time: "PST8PDT" +// Eastern: "EST5EDT" +// Japanesse: "JST-9" +// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3" +#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3" + +// InfluxDB client instance with preconfigured InfluxCloud certificate +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); + +void setup() { + Serial.begin(115200); + + // Setup wifi + WiFi.mode(WIFI_STA); + wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); + + Serial.print("Connecting to wifi"); + while (wifiMulti.run() != WL_CONNECTED) { + Serial.print("."); + delay(500); + } + Serial.println(); + + + // Accurate time is necessary for certificate validation + // For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ + // Syncing progress and the time will be printed to Serial + timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov"); + + // Check server connection + if (client.validateConnection()) { + Serial.print("Connected to InfluxDB: "); + Serial.println(client.getServerUrl()); + } else { + Serial.print("InfluxDB connection failed: "); + Serial.println(client.getLastErrorMessage()); + } +} + + +// Queries WiFi signal level values bellow a certain threshold using parameters inserted into the Flux query +// Prints composed query and the result values. +void loop() { + // Prepare query parameters + QueryParams params; + params.add("bucket", INFLUXDB_BUCKET); + params.add("since", "-5m"); + params.add("device", DEVICE); + params.add("rssiTreshold", -50); + + // Construct a Flux query using parameters + // Parameters are accessed via the 'params' Flux object + // Flux only supports only string, float and int as parameters. Duration can be converted from string. + // Query will find RSSI less than defined treshold + String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \ + |> filter(fn: (r) => r._measurement == \"wifi_status\") \ + |> filter(fn: (r) => r._field == \"rssi\") \ + |> filter(fn: (r) => r.device == params.device) \ + |> filter(fn: (r) => r._value < params.rssiTreshold)"; + + // Print ouput header + // Print composed query + Serial.print("Querying with: "); + Serial.println(query); + + // Send query to the server and get result + FluxQueryResult result = client.query(query, params); + + //Print header + Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI"); + + for(int i=0;i<37;i++) { + Serial.print('-'); + } + Serial.println(); + + // Iterate over rows. Even there is just one row, next() must be called at least once. + int c = 0; + while (result.next()) { + // Get converted value for flux result column 'SSID' + String ssid = result.getValueByName("SSID").getString(); + + // Get converted value for flux result column '_value' where there is RSSI value + long rssi = result.getValueByName("_value").getLong(); + + // Get converted value for the _time column + FluxDateTime time = result.getValueByName("_time").getDateTime(); + + // Format date-time for printing + // Format string according to http://www.cplusplus.com/reference/ctime/strftime/ + String timeStr = time.format("%F %T"); + // Print formatted row + Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi); + c++; + } + if(!c) { + Serial.println(" No data found"); + } + + // Check if there was an error + if(result.getError() != "") { + Serial.print("Query result error: "); + Serial.println(result.getError()); + } + + // Close the result + result.close(); + // Wait 15s + delay(15000); +} diff --git a/firmware/libraries/ESP8266_Influxdb/examples/QueryTable/QueryTable.ino b/firmware/libraries/ESP8266_Influxdb/examples/QueryTable/QueryTable.ino new file mode 100644 index 0000000..adc7b38 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/examples/QueryTable/QueryTable.ino @@ -0,0 +1,148 @@ +/** + * QueryTable Example code for InfluxDBClient library for Arduino. + * + * This example demonstrates querying recent history of values of WiFi signal level measured and stored in BasicWrite and SecureWrite examples. + * + * Demonstrates connection to any InfluxDB instance accesible via: + * - unsecured http://... + * - secure https://... (appropriate certificate is required) + * - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured) + * + * Enter WiFi and InfluxDB parameters below + **/ + +#if defined(ESP32) +#include +WiFiMulti wifiMulti; +#define DEVICE "ESP32" +#elif defined(ESP8266) +#include +ESP8266WiFiMulti wifiMulti; +#define DEVICE "ESP8266" +#endif + +#include +#include + +// WiFi AP SSID +#define WIFI_SSID "SSID" +// WiFi password +#define WIFI_PASSWORD "PASSWORD" +// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries) +// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086 +#define INFLUXDB_URL "server-url" +// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> ) +#define INFLUXDB_TOKEN "server token" +// InfluxDB v2 organization id (Use: InfluxDB UI -> Settings -> Profile -> ) +#define INFLUXDB_ORG "org id" +// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets) +#define INFLUXDB_BUCKET "bucket name" +// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html +// Examples: +// Pacific Time: "PST8PDT" +// Eastern: "EST5EDT" +// Japanesse: "JST-9" +// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3" +#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3" +// NTP servers the for time synchronization. +// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ +#define NTP_SERVER1 "pool.ntp.org" +#define NTP_SERVER2 "time.nis.gov" +#define WRITE_PRECISION WritePrecision::S +#define MAX_BATCH_SIZE 10 +#define WRITE_BUFFER_SIZE 30 + +// InfluxDB client instance with preconfigured InfluxCloud certificate +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); +// InfluxDB client instance without preconfigured InfluxCloud certificate for insecure connection +//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN); + +// Data point +Point sensorStatus("wifi_status"); + +// Number for loops to sync time using NTP +int iterations = 0; + +void setup() { + Serial.begin(115200); + + // Setup wifi + WiFi.mode(WIFI_STA); + wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); + + Serial.print("Connecting to wifi"); + while (wifiMulti.run() != WL_CONNECTED) { + Serial.print("."); + delay(500); + } + Serial.println(); + + // Add tags + sensorStatus.addTag("device", DEVICE); + sensorStatus.addTag("SSID", WiFi.SSID()); + + // Alternatively, set insecure connection to skip server certificate validation + //client.setInsecure(); + + // Accurate time is necessary for certificate validation and writing in batches + // Syncing progress and the time will be printed to Serial. + timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2); + + // Check server connection + if (client.validateConnection()) { + Serial.print("Connected to InfluxDB: "); + Serial.println(client.getServerUrl()); + } else { + Serial.print("InfluxDB connection failed: "); + Serial.println(client.getLastErrorMessage()); + } + + // Enable messages batching and retry buffer + client.setWriteOptions(WriteOptions().writePrecision(WRITE_PRECISION).batchSize(MAX_BATCH_SIZE).bufferSize(WRITE_BUFFER_SIZE)); +} + +void loop() { + // Sync time for batching once per hour + if (iterations++ >= 360) { + timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2); + iterations = 0; + } + + // Report networks (low priority data) just in case we successfully wrote the previous batch + if (client.isBufferEmpty()) { + // Report all the detected wifi networks + int networks = WiFi.scanNetworks(); + // Set identical time for the whole network scan + time_t tnow = time(nullptr); + for (int i = 0; i < networks; i++) { + Point sensorNetworks("wifi_networks"); + sensorNetworks.addTag("device", DEVICE); + sensorNetworks.addTag("SSID", WiFi.SSID(i)); + sensorNetworks.addTag("channel", String(WiFi.channel(i))); + sensorNetworks.addTag("open", String(WiFi.encryptionType(i) == WIFI_AUTH_OPEN)); + sensorNetworks.addField("rssi", WiFi.RSSI(i)); + sensorNetworks.setTime(tnow); //set the time + + // Print what are we exactly writing + Serial.print("Writing: "); + Serial.println(client.pointToLineProtocol(sensorNetworks)); + + // Write point into buffer - low priority measures + client.writePoint(sensorNetworks); + } + } else + Serial.println("Wifi networks reporting skipped due to communication issues"); + + // Report RSSI of currently connected network + sensorStatus.setTime(time(nullptr)); + sensorStatus.addField("rssi", WiFi.RSSI()); + + // Print what are we exactly writing + Serial.print("Writing: "); + Serial.println(client.pointToLineProtocol(sensorStatus)); + + // Write point into buffer - high priority measure + client.writePoint(sensorStatus); + + // Clear fields for next usage. Tags remain the same. + sensorStatus.clearFields(); + + // If no Wifi signal, try to reconnect it + if (wifiMulti.run() != WL_CONNECTED) { + Serial.println("Wifi connection lost"); + } + + // End of the iteration - force write of all the values into InfluxDB as single transaction + Serial.println("Flushing data into InfluxDB"); + if (!client.flushBuffer()) { + Serial.print("InfluxDB flush failed: "); + Serial.println(client.getLastErrorMessage()); + Serial.print("Full buffer: "); + Serial.println(client.isBufferFull() ? "Yes" : "No"); + } + + // Wait 10s + Serial.println("Wait 10s"); + delay(10000); +} \ No newline at end of file diff --git a/firmware/libraries/ESP8266_Influxdb/examples/SecureWrite/SecureWrite.ino b/firmware/libraries/ESP8266_Influxdb/examples/SecureWrite/SecureWrite.ino new file mode 100644 index 0000000..4b49fea --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/examples/SecureWrite/SecureWrite.ino @@ -0,0 +1,113 @@ +/** + * Secure Write Example code for InfluxDBClient library for Arduino + * Enter WiFi and InfluxDB parameters below + * + * Demonstrates connection to any InfluxDB instance accesible via: + * - unsecured http://... + * - secure https://... (appropriate certificate is required) + * - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured) + * Measures signal level of the actually connected WiFi network + * This example demonstrates time handling, secure connection and measurement writing into InfluxDB + * Data can be immediately seen in a InfluxDB 2 Cloud UI - measurement wifi_status + **/ + +#if defined(ESP32) +#include +WiFiMulti wifiMulti; +#define DEVICE "ESP32" +#elif defined(ESP8266) +#include +ESP8266WiFiMulti wifiMulti; +#define DEVICE "ESP8266" +#endif + +#include +#include + +// WiFi AP SSID +#define WIFI_SSID "SSID" +// WiFi password +#define WIFI_PASSWORD "PASSWORD" +// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries) +#define INFLUXDB_URL "server-url" +// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> "; + // if no ID use customhtml for item, else generate from param string + if (_params[i]->getID() != NULL) { + if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); // T_I id number + if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); // T_i id name + if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); // T_n id name alias + if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); // T_p replace legacy placeholder token + if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getLabel()); // T_t title/label + snprintf(valLength, 5, "%d", _params[i]->getValueLength()); + if(tok_l)pitem.replace(FPSTR(T_l), valLength); // T_l value length + if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); // T_v value + if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // T_c meant for additional attributes, not html, but can stuff + } else { + pitem = _params[i]->getCustomHTML(); + } + + page += pitem; + } + } + + return page; +} + +void WiFiManager::handleWiFiStatus(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi status ")); + #endif + handleRequest(); + String page; + // String page = "{\"result\":true,\"count\":1}"; + #ifdef WM_JSTEST + page = FPSTR(HTTP_JS); + #endif + HTTPSend(page); +} + +/** + * HTTPD CALLBACK save form and redirect to WLAN config page again + */ +void WiFiManager::handleWifiSave() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); + DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + #endif + handleRequest(); + + //SAVE/connect here + _ssid = server->arg(F("s")).c_str(); + _pass = server->arg(F("p")).c_str(); + + // set static ips from server args + if (server->arg(FPSTR(S_ip)) != "") { + //_sta_static_ip.fromString(server->arg(FPSTR(S_ip)); + String ip = server->arg(FPSTR(S_ip)); + optionalIPFromString(&_sta_static_ip, ip.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("static ip:"),ip); + #endif + } + if (server->arg(FPSTR(S_gw)) != "") { + String gw = server->arg(FPSTR(S_gw)); + optionalIPFromString(&_sta_static_gw, gw.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("static gateway:"),gw); + #endif + } + if (server->arg(FPSTR(S_sn)) != "") { + String sn = server->arg(FPSTR(S_sn)); + optionalIPFromString(&_sta_static_sn, sn.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("static netmask:"),sn); + #endif + } + if (server->arg(FPSTR(S_dns)) != "") { + String dns = server->arg(FPSTR(S_dns)); + optionalIPFromString(&_sta_static_dns, dns.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("static DNS:"),dns); + #endif + } + + if (_presavewificallback != NULL) { + _presavewificallback(); // @CALLBACK + } + + if(_paramsInWifi) doParamSave(); + + String page; + + if(_ssid == ""){ + page = getHTTPHead(FPSTR(S_titlewifisettings)); // @token titleparamsaved + page += FPSTR(HTTP_PARAMSAVED); + } + else { + page = getHTTPHead(FPSTR(S_titlewifisaved)); // @token titlewifisaved + page += FPSTR(HTTP_SAVED); + } + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); // @HTTPHEAD send cors + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); + #endif + + connect = true; //signal ready to connect/reset process in processConfigPortal +} + +void WiFiManager::handleParamSave() { + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param save ")); + #endif + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + #endif + handleRequest(); + + doParamSave(); + + String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved + page += FPSTR(HTTP_PARAMSAVED); + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("Sent param save page")); + #endif +} + +void WiFiManager::doParamSave(){ + // @todo use new callback for before paramsaves, is this really needed? + if ( _presaveparamscallback != NULL) { + _presaveparamscallback(); // @CALLBACK + } + + //parameters + if(_paramsCount > 0){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + #endif + + for (int i = 0; i < _paramsCount; i++) { + if (_params[i] == NULL || _params[i]->_length == 0) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFiManagerParameter is out of scope")); + #endif + break; // @todo might not be needed anymore + } + //read parameter from server + String name = (String)FPSTR(S_parampre)+(String)i; + String value; + if(server->hasArg(name)) { + value = server->arg(name); + } else { + value = server->arg(_params[i]->getID()); + } + + //store it in params array + value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); + #endif + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + #endif + } + + if ( _saveparamscallback != NULL) { + _saveparamscallback(); // @CALLBACK + } + +} + +/** + * HTTPD CALLBACK info page + */ +void WiFiManager::handleInfo() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Info")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo + reportStatus(page); + + uint16_t infos = 0; + + //@todo convert to enum or refactor to strings + //@todo wrap in build flag to remove all info code for memory saving + #ifdef ESP8266 + infos = 28; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("fchipid"), + F("idesize"), + F("flashsize"), + F("corever"), + F("bootver"), + F("cpufreq"), + F("freeheap"), + F("memsketch"), + F("memsmeter"), + F("lastreset"), + F("wifihead"), + F("conx"), + F("stassid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("autoconx"), + F("wifiaphead"), + F("apssid"), + F("apip"), + F("apbssid"), + F("apmac") + }; + + #elif defined(ESP32) + // add esp_chip_info ? + infos = 26; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("chiprev"), + F("idesize"), + F("flashsize"), + F("cpufreq"), + F("freeheap"), + F("memsketch"), + F("memsmeter"), + F("lastreset"), + F("wifihead"), + F("conx"), + F("stassid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("apssid"), + F("wifiaphead"), + F("apip"), + F("apmac"), + F("aphost"), + F("apbssid") + // F("temp") + }; + #endif + + for(size_t i=0; i"); + + page += F("

About


"); + page += getInfoData("aboutver"); + page += getInfoData("aboutarduinover"); + page += getInfoData("aboutidfver"); + page += getInfoData("aboutdate"); + page += F("
"); + + if(_showInfoUpdate){ + page += HTTP_PORTAL_MENU[8]; + page += HTTP_PORTAL_MENU[9]; + } + if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); + if(_showBack) page += FPSTR(HTTP_BACKBTN); + page += FPSTR(HTTP_HELP); + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("Sent info page")); + #endif +} + +String WiFiManager::getInfoData(String id){ + + String p; + // @todo add WM versioning + if(id==F("esphead"))p = FPSTR(HTTP_INFO_esphead); + else if(id==F("wifihead"))p = FPSTR(HTTP_INFO_wifihead); + else if(id==F("uptime")){ + // subject to rollover! + p = FPSTR(HTTP_INFO_uptime); + p.replace(FPSTR(T_1),(String)(millis() / 1000 / 60)); + p.replace(FPSTR(T_2),(String)((millis() / 1000) % 60)); + } + else if(id==F("chipid")){ + p = FPSTR(HTTP_INFO_chipid); + p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); + } + #ifdef ESP32 + else if(id==F("chiprev")){ + p = FPSTR(HTTP_INFO_chiprev); + String rev = (String)ESP.getChipRevision(); + #ifdef _SOC_EFUSE_REG_H_ + String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S)&&EFUSE_RD_CHIP_VER_RESERVE_V); + p.replace(FPSTR(T_1),rev+"
"+revb); + #else + p.replace(FPSTR(T_1),rev); + #endif + } + #endif + #ifdef ESP8266 + else if(id==F("fchipid")){ + p = FPSTR(HTTP_INFO_fchipid); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipId()); + } + #endif + else if(id==F("idesize")){ + p = FPSTR(HTTP_INFO_idesize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipSize()); + } + else if(id==F("flashsize")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_flashsize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); + #elif defined ESP32 + p = FPSTR(HTTP_INFO_psrsize); + p.replace(FPSTR(T_1),(String)ESP.getPsramSize()); + #endif + } + else if(id==F("corever")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_corever); + p.replace(FPSTR(T_1),(String)ESP.getCoreVersion()); + #endif + } + #ifdef ESP8266 + else if(id==F("bootver")){ + p = FPSTR(HTTP_INFO_bootver); + p.replace(FPSTR(T_1),(String)system_get_boot_version()); + } + #endif + else if(id==F("cpufreq")){ + p = FPSTR(HTTP_INFO_cpufreq); + p.replace(FPSTR(T_1),(String)ESP.getCpuFreqMHz()); + } + else if(id==F("freeheap")){ + p = FPSTR(HTTP_INFO_freeheap); + p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); + } + else if(id==F("memsketch")){ + p = FPSTR(HTTP_INFO_memsketch); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + else if(id==F("memsmeter")){ + p = FPSTR(HTTP_INFO_memsmeter); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + else if(id==F("lastreset")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_lastreset); + p.replace(FPSTR(T_1),(String)ESP.getResetReason()); + #elif defined(ESP32) && defined(_ROM_RTC_H_) + // requires #include + p = FPSTR(HTTP_INFO_lastreset); + for(int i=0;i<2;i++){ + int reason = rtc_get_reset_reason(i); + String tok = (String)T_ss+(String)(i+1)+(String)T_es; + switch (reason) + { + //@todo move to array + case 1 : p.replace(tok,F("Vbat power on reset"));break; + case 3 : p.replace(tok,F("Software reset digital core"));break; + case 4 : p.replace(tok,F("Legacy watch dog reset digital core"));break; + case 5 : p.replace(tok,F("Deep Sleep reset digital core"));break; + case 6 : p.replace(tok,F("Reset by SLC module, reset digital core"));break; + case 7 : p.replace(tok,F("Timer Group0 Watch dog reset digital core"));break; + case 8 : p.replace(tok,F("Timer Group1 Watch dog reset digital core"));break; + case 9 : p.replace(tok,F("RTC Watch dog Reset digital core"));break; + case 10 : p.replace(tok,F("Instrusion tested to reset CPU"));break; + case 11 : p.replace(tok,F("Time Group reset CPU"));break; + case 12 : p.replace(tok,F("Software reset CPU"));break; + case 13 : p.replace(tok,F("RTC Watch dog Reset CPU"));break; + case 14 : p.replace(tok,F("for APP CPU, reseted by PRO CPU"));break; + case 15 : p.replace(tok,F("Reset when the vdd voltage is not stable"));break; + case 16 : p.replace(tok,F("RTC Watch dog reset digital core and rtc module"));break; + default : p.replace(tok,F("NO_MEAN")); + } + } + #endif + } + else if(id==F("apip")){ + p = FPSTR(HTTP_INFO_apip); + p.replace(FPSTR(T_1),WiFi.softAPIP().toString()); + } + else if(id==F("apmac")){ + p = FPSTR(HTTP_INFO_apmac); + p.replace(FPSTR(T_1),(String)WiFi.softAPmacAddress()); + } + #ifdef ESP32 + else if(id==F("aphost")){ + p = FPSTR(HTTP_INFO_aphost); + p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); + } + #endif + #ifndef WM_NOSOFTAPSSID + #ifdef ESP8266 + else if(id==F("apssid")){ + p = FPSTR(HTTP_INFO_apssid); + p.replace(FPSTR(T_1),htmlEntities(WiFi.softAPSSID())); + } + #endif + #endif + else if(id==F("apbssid")){ + p = FPSTR(HTTP_INFO_apbssid); + p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); + } + // softAPgetHostname // esp32 + // softAPSubnetCIDR + // softAPNetworkID + // softAPBroadcastIP + + else if(id==F("stassid")){ + p = FPSTR(HTTP_INFO_stassid); + p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); + } + else if(id==F("staip")){ + p = FPSTR(HTTP_INFO_staip); + p.replace(FPSTR(T_1),WiFi.localIP().toString()); + } + else if(id==F("stagw")){ + p = FPSTR(HTTP_INFO_stagw); + p.replace(FPSTR(T_1),WiFi.gatewayIP().toString()); + } + else if(id==F("stasub")){ + p = FPSTR(HTTP_INFO_stasub); + p.replace(FPSTR(T_1),WiFi.subnetMask().toString()); + } + else if(id==F("dnss")){ + p = FPSTR(HTTP_INFO_dnss); + p.replace(FPSTR(T_1),WiFi.dnsIP().toString()); + } + else if(id==F("host")){ + p = FPSTR(HTTP_INFO_host); + #ifdef ESP32 + p.replace(FPSTR(T_1),WiFi.getHostname()); + #else + p.replace(FPSTR(T_1),WiFi.hostname()); + #endif + } + else if(id==F("stamac")){ + p = FPSTR(HTTP_INFO_stamac); + p.replace(FPSTR(T_1),WiFi.macAddress()); + } + else if(id==F("conx")){ + p = FPSTR(HTTP_INFO_conx); + p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); + } + #ifdef ESP8266 + else if(id==F("autoconx")){ + p = FPSTR(HTTP_INFO_autoconx); + p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); + } + #endif + #if defined(ESP32) && !defined(WM_NOTEMP) + else if(id==F("temp")){ + // temperature is not calibrated, varying large offsets are present, use for relative temp changes only + p = FPSTR(HTTP_INFO_temp); + p.replace(FPSTR(T_1),(String)temperatureRead()); + p.replace(FPSTR(T_2),(String)((temperatureRead()+32)*1.8)); + // p.replace(FPSTR(T_3),(String)hallRead()); + p.replace(FPSTR(T_3),"NA"); + } + #endif + else if(id==F("aboutver")){ + p = FPSTR(HTTP_INFO_aboutver); + p.replace(FPSTR(T_1),FPSTR(WM_VERSION_STR)); + } + else if(id==F("aboutarduinover")){ + #ifdef VER_ARDUINO_STR + p = FPSTR(HTTP_INFO_aboutarduino); + p.replace(FPSTR(T_1),String(VER_ARDUINO_STR)); + #endif + } + // else if(id==F("aboutidfver")){ + // #ifdef VER_IDF_STR + // p = FPSTR(HTTP_INFO_aboutidf); + // p.replace(FPSTR(T_1),String(VER_IDF_STR)); + // #endif + // } + else if(id==F("aboutsdkver")){ + p = FPSTR(HTTP_INFO_sdkver); + #ifdef ESP32 + p.replace(FPSTR(T_1),(String)esp_get_idf_version()); + // p.replace(FPSTR(T_1),(String)system_get_sdk_version()); // deprecated + #else + p.replace(FPSTR(T_1),(String)system_get_sdk_version()); + #endif + } + else if(id==F("aboutdate")){ + p = FPSTR(HTTP_INFO_aboutdate); + p.replace(FPSTR(T_1),String(__DATE__ " " __TIME__)); + } + return p; +} + +/** + * HTTPD CALLBACK exit, closes configportal if blocking, if non blocking undefined + */ +void WiFiManager::handleExit() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Exit")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit + page += FPSTR(S_exiting); // @token exiting + // ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'}) + server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); // @HTTPHEAD send cache + HTTPSend(page); + delay(2000); + abort = true; +} + +/** + * HTTPD CALLBACK reset page + */ +void WiFiManager::handleReset() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Reset")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset + page += FPSTR(S_resetting); //@token resetting + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("RESETTING ESP")); + #endif + delay(1000); + reboot(); +} + +/** + * HTTPD CALLBACK erase page + */ + +// void WiFiManager::handleErase() { +// handleErase(false); +// } +void WiFiManager::handleErase(boolean opt) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_NOTIFY,F("<- HTTP Erase")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase + + bool ret = erase(opt); + + if(ret) page += FPSTR(S_resetting); // @token resetting + else { + page += FPSTR(S_error); // @token erroroccur + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); + #endif + } + + page += FPSTR(HTTP_END); + HTTPSend(page); + + if(ret){ + delay(2000); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("RESETTING ESP")); + #endif + reboot(); + } +} + +/** + * HTTPD CALLBACK 404 + */ +void WiFiManager::handleNotFound() { + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + handleRequest(); + String message = FPSTR(S_notfound); // @token notfound + message += FPSTR(S_uri); // @token uri + message += server->uri(); + message += FPSTR(S_method); // @token method + message += ( server->method() == HTTP_GET ) ? FPSTR(S_GET) : FPSTR(S_POST); + message += FPSTR(S_args); // @token args + message += server->args(); + message += F("\n"); + + for ( uint8_t i = 0; i < server->args(); i++ ) { + message += " " + server->argName ( i ) + ": " + server->arg ( i ) + "\n"; + } + server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); // @HTTPHEAD send cache + server->sendHeader(F("Pragma"), F("no-cache")); + server->sendHeader(F("Expires"), F("-1")); + server->send ( 404, FPSTR(HTTP_HEAD_CT2), message ); +} + +/** + * HTTPD redirector + * 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. + */ +boolean WiFiManager::captivePortal() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,"-> " + server->hostHeader()); + #endif + + if(!_enableCaptivePortal) return false; // skip redirections, @todo maybe allow redirection even when no cp ? might be useful + + String serverLoc = toStringIp(server->client().localIP()); + if(_httpPort != 80) serverLoc += ":" + (String)_httpPort; // add port if not default + bool doredirect = serverLoc != server->hostHeader(); // redirect if hostheader not server ip, prevent redirect loops + // doredirect = !isIp(server->hostHeader()) // old check + + if (doredirect) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- Request redirected to captive portal")); + #endif + server->sendHeader(F("Location"), (String)F("http://") + serverLoc, true); // @HTTPHEAD send redirect + server->send ( 302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server->client().stop(); // Stop is needed because we sent no content length + return true; + } + return false; +} + +void WiFiManager::stopCaptivePortal(){ + _enableCaptivePortal= false; + // @todo maybe disable configportaltimeout(optional), or just provide callback for user +} + +// HTTPD CALLBACK, handle close, stop captive portal, if not enabled undefined +void WiFiManager::handleClose(){ + DEBUG_WM(DEBUG_VERBOSE,F("Disabling Captive Portal")); + stopCaptivePortal(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP close")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose + page += FPSTR(S_closing); // @token closing + HTTPSend(page); +} + +void WiFiManager::reportStatus(String &page){ + // updateConxResult(WiFi.status()); // @todo: this defeats the purpose of last result, update elsewhere or add logic here + DEBUG_WM(DEBUG_DEV,F("[WIFI] reportStatus prev:"),getWLStatusString(_lastconxresult)); + DEBUG_WM(DEBUG_DEV,F("[WIFI] reportStatus current:"),getWLStatusString(WiFi.status())); + String str; + if (WiFi_SSID() != ""){ + if (WiFi.status()==WL_CONNECTED){ + str = FPSTR(HTTP_STATUS_ON); + str.replace(FPSTR(T_i),WiFi.localIP().toString()); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + } + else { + str = FPSTR(HTTP_STATUS_OFF); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + if(_lastconxresult == WL_STATION_WRONG_PASSWORD){ + // wrong password + str.replace(FPSTR(T_c),"D"); // class + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFPW)); + } + else if(_lastconxresult == WL_NO_SSID_AVAIL){ + // connect failed, or ap not found + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFNOAP)); + } + else if(_lastconxresult == WL_CONNECT_FAILED){ + // connect failed + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); + } + else{ + str.replace(FPSTR(T_c),""); + str.replace(FPSTR(T_r),""); + } + } + } + else { + str = FPSTR(HTTP_STATUS_NONE); + } + page += str; +} + +// PUBLIC + +// METHODS + +/** + * reset wifi settings, clean stored ap password + */ + +/** + * [stopConfigPortal description] + * @return {[type]} [description] + */ +bool WiFiManager::stopConfigPortal(){ + if(_configPortalIsBlocking){ + abort = true; + return true; + } + return shutdownConfigPortal(); +} + +/** + * disconnect + * @access public + * @since $dev + * @return bool success + */ +bool WiFiManager::disconnect(){ + if(WiFi.status() != WL_CONNECTED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Disconnecting: Not connected")); + #endif + return false; + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Disconnecting")); + #endif + return WiFi_Disconnect(); +} + +/** + * reboot the device + * @access public + */ +void WiFiManager::reboot(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Restarting")); + #endif + ESP.restart(); +} + +/** + * reboot the device + * @access public + */ +bool WiFiManager::erase(){ + return erase(false); +} + +bool WiFiManager::erase(bool opt){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM("Erasing"); + #endif + + #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) + // if opt true, do nvs erase + if(opt){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing NVS")); + #endif + esp_err_t err; + err = nvs_flash_init(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("nvs_flash_init: "),err!=ESP_OK ? (String)err : "Success"); + #endif + err = nvs_flash_erase(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("nvs_flash_erase: "), err!=ESP_OK ? (String)err : "Success"); + #endif + return err == ESP_OK; + } + #elif defined(ESP8266) && defined(spiffs_api_h) + if(opt){ + bool ret = false; + if(SPIFFS.begin()){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing SPIFFS")); + #endif + bool ret = SPIFFS.format(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("spiffs erase: "),ret ? "Success" : "ERROR"); + #endif + } else{ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("[ERROR] Could not start SPIFFS")); + #endif + } + return ret; + } + #else + (void)opt; + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing WiFi Config")); + #endif + return WiFi_eraseConfig(); +} + +/** + * [resetSettings description] + * ERASES STA CREDENTIALS + * @access public + */ +void WiFiManager::resetSettings() { +#ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("resetSettings")); + #endif + WiFi_enableSTA(true,true); // must be sta to disconnect erase + delay(500); // ensure sta is enabled + if (_resetcallback != NULL){ + _resetcallback(); // @CALLBACK + } + + #ifdef ESP32 + WiFi.disconnect(true,true); + #else + WiFi.persistent(true); + WiFi.disconnect(true); + WiFi.persistent(false); + #endif + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("SETTINGS ERASED")); + #endif +} + +// SETTERS + +/** + * [setTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setTimeout(unsigned long seconds) { + setConfigPortalTimeout(seconds); +} + +/** + * [setConfigPortalTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { + _configPortalTimeout = seconds * 1000; +} + +/** + * [setConnectTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConnectTimeout(unsigned long seconds) { + _connectTimeout = seconds * 1000; +} + +/** + * [setConnectRetries description] + * @access public + * @param {[type]} uint8_t numRetries [description] + */ +void WiFiManager::setConnectRetries(uint8_t numRetries){ + _connectRetries = constrain(numRetries,1,10); +} + +/** + * toggle _cleanconnect, always disconnect before connecting + * @param {[type]} bool enable [description] + */ +void WiFiManager::setCleanConnect(bool enable){ + _cleanConnect = enable; +} + +/** + * [setConnectTimeout description + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { + _saveTimeout = seconds * 1000; +} + +/** + * Set save portal connect on save option, + * if false, will only save credentials not connect + * @access public + * @param {[type]} bool connect [description] + */ +void WiFiManager::setSaveConnect(bool connect) { + _connectonsave = connect; +} + +/** + * [setDebugOutput description] + * @access public + * @param {[type]} boolean debug [description] + */ +void WiFiManager::setDebugOutput(boolean debug) { + _debug = debug; + if(_debug && _debugLevel == DEBUG_DEV) debugPlatformInfo(); +} + +void WiFiManager::setDebugOutput(boolean debug, String prefix) { + _debugPrefix = prefix; + setDebugOutput(debug); +} + +/** + * [setAPStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _ap_static_ip = ip; + _ap_static_gw = gw; + _ap_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _sta_static_ip = ip; + _sta_static_gw = gw; + _sta_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @since $dev + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + * @param {[type]} IPAddress dns [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) { + setSTAStaticIPConfig(ip,gw,sn); + _sta_static_dns = dns; +} + +/** + * [setMinimumSignalQuality description] + * @access public + * @param {[type]} int quality [description] + */ +void WiFiManager::setMinimumSignalQuality(int quality) { + _minimumQuality = quality; +} + +/** + * [setBreakAfterConfig description] + * @access public + * @param {[type]} boolean shouldBreak [description] + */ +void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { + _shouldBreakAfterConfig = shouldBreak; +} + +/** + * setAPCallback, set a callback when softap is started + * @access public + * @param {[type]} void (*func)(WiFiManager* wminstance) + */ +void WiFiManager::setAPCallback( std::function func ) { + _apcallback = func; +} + +/** + * setWebServerCallback, set a callback after webserver is reset, and before routes are setup + * if we set webserver handlers before wm, they are used and wm is not by esp webserver + * on events cannot be overrided once set, and are not mutiples + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setWebServerCallback( std::function func ) { + _webservercallback = func; +} + +/** + * setSaveConfigCallback, set a save config callback after closing configportal + * @note calls only if wifi is saved or changed, or setBreakAfterConfig(true) + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveConfigCallback( std::function func ) { + _savewificallback = func; +} + +/** + * setPreSaveConfigCallback, set a callback to fire before saving wifi or params + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreSaveConfigCallback( std::function func ) { + _presavewificallback = func; +} + +/** + * setConfigResetCallback, set a callback to occur when a resetSettings() occurs + * @access public + * @param {[type]} void(*func)(void) + */ +void WiFiManager::setConfigResetCallback( std::function func ) { + _resetcallback = func; +} + +/** + * setSaveParamsCallback, set a save params callback on params save in wifi or params pages + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveParamsCallback( std::function func ) { + _saveparamscallback = func; +} + +/** + * setPreSaveParamsCallback, set a pre save params callback on params save prior to anything else + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreSaveParamsCallback( std::function func ) { + _presaveparamscallback = func; +} + +/** + * setPreOtaUpdateCallback, set a callback to fire before OTA update + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreOtaUpdateCallback( std::function func ) { + _preotaupdatecallback = func; +} + +/** + * set custom head html + * custom element will be added to head, eg. new meta,style,script tag etc. + * @access public + * @param char element + */ +void WiFiManager::setCustomHeadElement(const char* html) { + _customHeadElement = html; +} + +/** + * set custom menu html + * custom element will be added to menu under custom menu item. + * @access public + * @param char element + */ +void WiFiManager::setCustomMenuHTML(const char* html) { + _customMenuHTML = html; +} + +/** + * toggle wifiscan hiding of duplicate ssid names + * if this is false, wifiscan will remove duplicat Access Points - defaut true + * @access public + * @param boolean removeDuplicates [true] + */ +void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { + _removeDuplicateAPs = removeDuplicates; +} + +/** + * toggle configportal blocking loop + * if enabled, then the configportal will enter a blocking loop and wait for configuration + * if disabled use with process() to manually process webserver + * @since $dev + * @access public + * @param boolean shoudlBlock [false] + */ +void WiFiManager::setConfigPortalBlocking(boolean shouldBlock) { + _configPortalIsBlocking = shouldBlock; +} + +/** + * toggle restore persistent, track internally + * sets ESP wifi.persistent so we can remember it and restore user preference on destruct + * there is no getter in esp8266 platform prior to https://github.com/esp8266/Arduino/pull/3857 + * @since $dev + * @access public + * @param boolean persistent [true] + */ +void WiFiManager::setRestorePersistent(boolean persistent) { + _userpersistent = persistent; + if(!persistent){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("persistent is off")); + #endif + } +} + +/** + * toggle showing static ip form fields + * if enabled, then the static ip, gateway, subnet fields will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowStaticFields(boolean alwaysShow){ + if(_disableIpFields) _staShowStaticFields = alwaysShow ? 1 : -1; + else _staShowStaticFields = alwaysShow ? 1 : 0; +} + +/** + * toggle showing dns fields + * if enabled, then the dns1 field will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowDnsFields(boolean alwaysShow){ + if(_disableIpFields) _staShowDns = alwaysShow ? 1 : -1; + _staShowDns = alwaysShow ? 1 : 0; +} + +/** + * toggle showing password in wifi password field + * if not enabled, placeholder will be S_passph + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowPassword(boolean show){ + _showPassword = show; +} + +/** + * toggle captive portal + * if enabled, then devices that use captive portal checks will be redirected to root + * if not you will automatically have to navigate to ip [192.168.4.1] + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setCaptivePortalEnable(boolean enabled){ + _enableCaptivePortal = enabled; +} + +/** + * toggle wifi autoreconnect policy + * if enabled, then wifi will autoreconnect automatically always + * On esp8266 we force this on when autoconnect is called, see notes + * On esp32 this is handled on SYSTEM_EVENT_STA_DISCONNECTED since it does not exist in core yet + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWiFiAutoReconnect(boolean enabled){ + _wifiAutoReconnect = enabled; +} + +/** + * toggle configportal timeout wait for station client + * if enabled, then the configportal will start timeout when no stations are connected to softAP + * disabled by default as rogue stations can keep it open if there is no auth + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setAPClientCheck(boolean enabled){ + _apClientCheck = enabled; +} + +/** + * toggle configportal timeout wait for web client + * if enabled, then the configportal will restart timeout when client requests come in + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWebPortalClientCheck(boolean enabled){ + _webClientCheck = enabled; +} + +/** + * toggle wifiscan percentages or quality icons + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setScanDispPerc(boolean enabled){ + _scanDispOptions = enabled; +} + +/** + * toggle configportal if autoconnect failed + * if enabled, then the configportal will be activated on autoconnect failure + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setEnableConfigPortal(boolean enable) +{ + _enableConfigPortal = enable; +} + +/** + * toggle configportal if autoconnect failed + * if enabled, then the configportal will be de-activated on wifi save + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setDisableConfigPortal(boolean enable) +{ + _disableConfigPortal = enable; +} + +/** + * set the hostname (dhcp client id) + * @since $dev + * @access public + * @param char* hostname 32 character hostname to use for sta+ap in esp32, sta in esp8266 + * @return bool false if hostname is not valid + */ +bool WiFiManager::setHostname(const char * hostname){ + //@todo max length 32 + _hostname = String(hostname); + return true; +} + +bool WiFiManager::setHostname(String hostname){ + //@todo max length 32 + _hostname = hostname; + return true; +} + +/** + * set the soft ao channel, ignored if channelsync is true and connected + * @param int32_t wifi channel, 0 to disable + */ +void WiFiManager::setWiFiAPChannel(int32_t channel){ + _apChannel = channel; +} + +/** + * set the soft ap hidden + * @param bool wifi ap hidden, default is false + */ +void WiFiManager::setWiFiAPHidden(bool hidden){ + _apHidden = hidden; +} + + +/** + * toggle showing erase wifi config button on info page + * @param boolean enabled + */ +void WiFiManager::setShowInfoErase(boolean enabled){ + _showInfoErase = enabled; +} + +/** + * toggle showing update upload web ota button on info page + * @param boolean enabled + */ +void WiFiManager::setShowInfoUpdate(boolean enabled){ + _showInfoUpdate = enabled; +} + +/** + * check if the config portal is running + * @return bool true if active + */ +bool WiFiManager::getConfigPortalActive(){ + return configPortalActive; +} + +/** + * [getConfigPortalActive description] + * @return bool true if active + */ +bool WiFiManager::getWebPortalActive(){ + return webPortalActive; +} + + +String WiFiManager::getWiFiHostname(){ + #ifdef ESP32 + return (String)WiFi.getHostname(); + #else + return (String)WiFi.hostname(); + #endif +} + +/** + * [setTitle description] + * @param String title, set app title + */ +void WiFiManager::setTitle(String title){ + _title = title; +} + +/** + * set menu items and order + * if param is present in menu , params will be removed from wifi page automatically + * eg. + * const char * menu[] = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * @since $dev + * @param uint8_t menu[] array of menu ids + */ +void WiFiManager::setMenu(const char * menu[], uint8_t size){ +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,"setmenu array"); + #endif + _menuIds.clear(); + for(size_t i = 0; i < size; i++){ + for(size_t j = 0; j < _nummenutokens; j++){ + if(menu[i] == _menutokens[j]){ + if((String)menu[i] == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + } + } + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(getMenuOut()); + #endif +} + +/** + * setMenu with vector + * eg. + * std::vector menu = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * tokens can be found in _menutokens array in strings_en.h + * @shiftIncrement $dev + * @param {[type]} std::vector& menu [description] + */ +void WiFiManager::setMenu(std::vector& menu){ +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,"setmenu vector"); + #endif + _menuIds.clear(); + for(auto menuitem : menu ){ + for(size_t j = 0; j < _nummenutokens; j++){ + if(menuitem == _menutokens[j]){ + if((String)menuitem == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + } + } + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,getMenuOut()); + #endif +} + + +/** + * set params as sperate page not in wifi + * NOT COMPATIBLE WITH setMenu! + * @todo scan menuids and insert param after wifi or something, same for ota + * @param bool enable + * @since $dev + */ +void WiFiManager::setParamsPage(bool enable){ + _paramsInWifi = !enable; + setMenu(enable ? _menuIdsParams : _menuIdsDefault); +} + +// GETTERS + +/** + * get config portal AP SSID + * @since 0.0.1 + * @access public + * @return String the configportal ap name + */ +String WiFiManager::getConfigPortalSSID() { + return _apName; +} + +/** + * return the last known connection result + * logged on autoconnect and wifisave, can be used to check why failed + * get as readable string with getWLStatusString(getLastConxResult); + * @since $dev + * @access public + * @return bool return wl_status codes + */ +uint8_t WiFiManager::getLastConxResult(){ + return _lastconxresult; +} + +/** + * check if wifi has a saved ap or not + * @since $dev + * @access public + * @return bool true if a saved ap config exists + */ +bool WiFiManager::getWiFiIsSaved(){ + return WiFi_hasAutoConnect(); +} + +/** + * getDefaultAPName + * @since $dev + * @return string + */ +String WiFiManager::getDefaultAPName(){ + String hostString = String(WIFI_getChipId(),HEX); + hostString.toUpperCase(); + // char hostString[16] = {0}; + // sprintf(hostString, "%06X", ESP.getChipId()); + return _wifissidprefix + "_" + hostString; +} + +/** + * setCountry + * @since $dev + * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN + */ +void WiFiManager::setCountry(String cc){ + _wificountry = cc; +} + +/** + * setClass + * @param String str body class string + */ +void WiFiManager::setClass(String str){ + _bodyClass = str; +} + +/** + * setDarkMode + * @param bool enable, enable dark mode via invert class + */ +void WiFiManager::setDarkMode(bool enable){ + _bodyClass = enable ? "invert" : ""; +} + +/** + * setHttpPort + * @param uint16_t port webserver port number default 80 + */ +void WiFiManager::setHttpPort(uint16_t port){ + _httpPort = port; +} + + +bool WiFiManager::preloadWiFi(String ssid, String pass){ + _defaultssid = ssid; + _defaultpass = pass; + return true; +} + +// HELPERS + +/** + * getWiFiSSID + * @since $dev + * @param bool persistent + * @return String + */ +String WiFiManager::getWiFiSSID(bool persistent){ + return WiFi_SSID(persistent); +} + +/** + * getWiFiPass + * @since $dev + * @param bool persistent + * @return String + */ +String WiFiManager::getWiFiPass(bool persistent){ + return WiFi_psk(persistent); +} + +// DEBUG +// @todo fix DEBUG_WM(0,0); +template +void WiFiManager::DEBUG_WM(Generic text) { + DEBUG_WM(DEBUG_NOTIFY,text,""); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) { + if(_debugLevel >= level) DEBUG_WM(level,text,""); +} + +template +void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { + DEBUG_WM(DEBUG_NOTIFY,text,textb); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { + if(!_debug || _debugLevel < level) return; + + if(_debugLevel >= DEBUG_MAX){ + #ifdef ESP8266 + // uint32_t free; + // uint16_t max; + // uint8_t frag; + // ESP.getHeapStats(&free, &max, &frag);// @todo Does not exist in 2.3.0 + // _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); + #elif defined ESP32 + // total_free_bytes; ///< Total free bytes in the heap. Equivalent to multi_free_heap_size(). + // total_allocated_bytes; ///< Total bytes allocated to data in the heap. + // largest_free_block; ///< Size of largest free block in the heap. This is the largest malloc-able size. + // minimum_free_bytes; ///< Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size(). + // allocated_blocks; ///< Number of (variable size) blocks allocated in the heap. + // free_blocks; ///< Number of (variable size) free blocks in the heap. + // total_blocks; ///< Total number of (variable size) blocks in the heap. + multi_heap_info_t info; + heap_caps_get_info(&info, MALLOC_CAP_INTERNAL); + uint32_t free = info.total_free_bytes; + uint16_t max = info.largest_free_block; + uint8_t frag = 100 - (max * 100) / free; + _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); + #endif + } + _debugPort.print(_debugPrefix); + if(_debugLevel >= debugLvlShow) _debugPort.print("["+(String)level+"] "); + _debugPort.print(text); + if(textb){ + _debugPort.print(" "); + _debugPort.print(textb); + } + _debugPort.println(); +} + +/** + * [debugSoftAPConfig description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::debugSoftAPConfig(){ + + #ifdef ESP8266 + softap_config config; + wifi_softap_get_config(&config); + #if !defined(WM_NOCOUNTRY) + wifi_country_t country; + wifi_get_country(&country); + #endif + #elif defined(ESP32) + wifi_country_t country; + wifi_config_t conf_config; + esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK + wifi_ap_config_t config = conf_config.ap; + esp_wifi_get_country(&country); + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("SoftAP Configuration")); + DEBUG_WM(FPSTR(D_HR)); + DEBUG_WM(F("ssid: "),(char *) config.ssid); + DEBUG_WM(F("password: "),(char *) config.password); + DEBUG_WM(F("ssid_len: "),config.ssid_len); + DEBUG_WM(F("channel: "),config.channel); + DEBUG_WM(F("authmode: "),config.authmode); + DEBUG_WM(F("ssid_hidden: "),config.ssid_hidden); + DEBUG_WM(F("max_connection: "),config.max_connection); + #endif + #if !defined(WM_NOCOUNTRY) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("country: "),(String)country.cc); + #endif + DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); + DEBUG_WM(FPSTR(D_HR)); + #endif +} + +/** + * [debugPlatformInfo description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::debugPlatformInfo(){ + #ifdef ESP8266 + system_print_meminfo(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("getCoreVersion(): "),ESP.getCoreVersion()); + DEBUG_WM(F("system_get_sdk_version(): "),system_get_sdk_version()); + DEBUG_WM(F("system_get_boot_version():"),system_get_boot_version()); + DEBUG_WM(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); + #endif + #elif defined(ESP32) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Free heap: "), ESP.getFreeHeap()); + DEBUG_WM(F("ESP SDK version: "), ESP.getSdkVersion()); + #endif + // esp_chip_info_t chipInfo; + // esp_chip_info(&chipInfo); + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM("Chip Info: Model: ",chipInfo.model); + // DEBUG_WM("Chip Info: Cores: ",chipInfo.cores); + // DEBUG_WM("Chip Info: Rev: ",chipInfo.revision); + // DEBUG_WM(printf("Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model.c_str(), chipInfo.cores, chipInfo.revision)); + // DEBUG_WM("Chip Rev: ",(String)ESP.getChipRevision()); + #endif + // core version is not avail + #endif +} + +int WiFiManager::getRSSIasQuality(int RSSI) { + int quality = 0; + + if (RSSI <= -100) { + quality = 0; + } else if (RSSI >= -50) { + quality = 100; + } else { + quality = 2 * (RSSI + 100); + } + return quality; +} + +/** Is this an IP? */ +boolean WiFiManager::isIp(String str) { + for (size_t i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (c != '.' && (c < '0' || c > '9')) { + return false; + } + } + return true; +} + +/** IP to String? */ +String WiFiManager::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; +} + +boolean WiFiManager::validApPassword(){ + // check that ap password is valid, return false + if (_apPassword == NULL) _apPassword = ""; + if (_apPassword != "") { + if (_apPassword.length() < 8 || _apPassword.length() > 63) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); + #endif + _apPassword = ""; + return false; // @todo FATAL or fallback to empty , currently fatal, fail secure. + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("AccessPoint set password is VALID")); + DEBUG_WM(DEBUG_DEV,"ap pass",_apPassword); + #endif + } + return true; +} + +/** + * encode htmlentities + * @since $dev + * @param string str string to replace entities + * @return string encoded string + */ +String WiFiManager::htmlEntities(String str, bool whitespace) { + str.replace("&","&"); + str.replace("<","<"); + str.replace(">",">"); + str.replace("'","'"); + if(whitespace) str.replace(" "," "); + // str.replace("-","–"); + // str.replace("\"","""); + // str.replace("/": "/"); + // str.replace("`": "`"); + // str.replace("=": "="); +return str; +} + +/** + * [getWLStatusString description] + * @access public + * @param {[type]} uint8_t status [description] + * @return {[type]} [description] + */ +String WiFiManager::getWLStatusString(uint8_t status){ + if(status <= 7) return WIFI_STA_STATUS[status]; + return FPSTR(S_NA); +} + +String WiFiManager::getWLStatusString(){ + uint8_t status = WiFi.status(); + if(status <= 7) return WIFI_STA_STATUS[status]; + return FPSTR(S_NA); +} + +String WiFiManager::encryptionTypeStr(uint8_t authmode) { +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM("enc_tye: ",authmode); + #endif + return AUTH_MODE_NAMES[authmode]; +} + +String WiFiManager::getModeString(uint8_t mode){ + if(mode <= 3) return WIFI_MODES[mode]; + return FPSTR(S_NA); +} + +bool WiFiManager::WiFiSetCountry(){ + if(_wificountry == "") return false; // skip not set + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("WiFiSetCountry to"),_wificountry); + #endif + +/* + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by eps_wifi_init + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_WIFI_ARG: invalid argument + * - others: refer to error codes in esp_err.h + */ + + // @todo move these definitions, and out of cpp `esp_wifi_set_country(&WM_COUNTRY_US)` + bool ret = true; + // ret = esp_wifi_set_bandwidth(WIFI_IF_AP,WIFI_BW_HT20); // WIFI_BW_HT40 + #ifdef ESP32 + esp_err_t err = ESP_OK; + // @todo check if wifi is init, no idea how, doesnt seem to be exposed atm ( check again it might be now! ) + if(WiFi.getMode() == WIFI_MODE_NULL){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] cannot set country, wifi not init"); + } // exception if wifi not init! + // Assumes that _wificountry is set to one of the supported country codes : "01"(world safe mode) "AT","AU","BE","BG","BR", + // "CA","CH","CN","CY","CZ","DE","DK","EE","ES","FI","FR","GB","GR","HK","HR","HU", + // "IE","IN","IS","IT","JP","KR","LI","LT","LU","LV","MT","MX","NL","NO","NZ","PL","PT", + // "RO","SE","SI","SK","TW","US" + // If an invalid country code is passed, ESP_ERR_WIFI_ARG will be returned + // This also uses 802.11d mode, which matches the STA to the country code of the AP it connects to (meaning + // that the country code will be overridden if connecting to a "foreign" AP) + else { + #ifndef WM_NOCOUNTRY + err = esp_wifi_set_country_code(_wificountry.c_str(), true); + #else + DEBUG_WM(DEBUG_ERROR,"[ERROR] esp wifi set country is not available"); + err = true; + #endif + } + #ifdef WM_DEBUG_LEVEL + if(err){ + if(err == ESP_ERR_WIFI_NOT_INIT) DEBUG_WM(DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_NOT_INIT"); + else if(err == ESP_ERR_INVALID_ARG) DEBUG_WM(DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_ARG (invalid country code)"); + else if(err != ESP_OK)DEBUG_WM(DEBUG_ERROR,"[ERROR] unknown error",(String)err); + } + #endif + ret = err == ESP_OK; + + #elif defined(ESP8266) && !defined(WM_NOCOUNTRY) + // if(WiFi.getMode() == WIFI_OFF); // exception if wifi not init! + if(_wificountry == "US") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_US); + else if(_wificountry == "JP") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_JP); + else if(_wificountry == "CN") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_CN); + #ifdef WM_DEBUG_LEVEL + else DEBUG_WM(DEBUG_ERROR,F("[ERROR] country code not found")); + #endif + #endif + + #ifdef WM_DEBUG_LEVEL + if(ret) DEBUG_WM(DEBUG_VERBOSE,F("[OK] esp_wifi_set_country: "),_wificountry); + else DEBUG_WM(DEBUG_ERROR,F("[ERROR] esp_wifi_set_country failed")); + #endif + return ret; +} + +// set mode ignores WiFi.persistent +bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { + bool ret; + #ifdef ESP8266 + if((wifi_get_opmode() == (uint8) m ) && !persistent) { + return true; + } + ETS_UART_INTR_DISABLE(); + if(persistent) ret = wifi_set_opmode(m); + else ret = wifi_set_opmode_current(m); + ETS_UART_INTR_ENABLE(); + return ret; + #elif defined(ESP32) + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.mode(m); // @todo persistent check persistant mode, was eventually added to esp lib, but have to add version checking probably + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} +bool WiFiManager::WiFi_Mode(WiFiMode_t m) { + return WiFi_Mode(m,false); +} + +// sta disconnect without persistent +bool WiFiManager::WiFi_Disconnect() { + #ifdef ESP8266 + if((WiFi.getMode() & WIFI_STA) != 0) { + bool ret; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi station disconnect")); + #endif + ETS_UART_INTR_DISABLE(); // @todo possibly not needed + ret = wifi_station_disconnect(); + ETS_UART_INTR_ENABLE(); + return ret; + } + #elif defined(ESP32) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi station disconnect")); + #endif + return WiFi.disconnect(); // not persistent atm + #endif + return false; +} + +// toggle STA without persistent +bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { +#ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi_enableSTA"),(String) enable? "enable" : "disable"); + #endif + #ifdef ESP8266 + WiFiMode_t newMode; + WiFiMode_t currentMode = WiFi.getMode(); + bool isEnabled = (currentMode & WIFI_STA) != 0; + if(enable) newMode = (WiFiMode_t)(currentMode | WIFI_STA); + else newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); + + if((isEnabled != enable) || persistent) { + if(enable) { + #ifdef WM_DEBUG_LEVEL + if(persistent) DEBUG_WM(DEBUG_DEV,F("enableSTA PERSISTENT ON")); + #endif + return WiFi_Mode(newMode,persistent); + } + else { + return WiFi_Mode(newMode,persistent); + } + } else { + return true; + } + #elif defined(ESP32) + bool ret; + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} + +bool WiFiManager::WiFi_enableSTA(bool enable) { + return WiFi_enableSTA(enable,false); +} + +bool WiFiManager::WiFi_eraseConfig() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi_eraseConfig")); + #endif + + #ifdef ESP8266 + #ifndef WM_FIXERASECONFIG + return ESP.eraseConfig(); + #else + // erase config BUG replacement + // https://github.com/esp8266/Arduino/pull/3635 + const size_t cfgSize = 0x4000; + size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; + + for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { + if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { + return false; + } + } + return true; + #endif + #elif defined(ESP32) + + bool ret; + WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! + WiFi.persistent(true); + ret = WiFi.disconnect(true,true); + delay(500); + WiFi.persistent(false); + return ret; + #endif +} + +uint8_t WiFiManager::WiFi_softap_num_stations(){ + #ifdef ESP8266 + return wifi_softap_get_station_num(); + #elif defined(ESP32) + return WiFi.softAPgetStationNum(); + #endif +} + +bool WiFiManager::WiFi_hasAutoConnect(){ + return WiFi_SSID(true) != ""; +} + +String WiFiManager::WiFi_SSID(bool persistent) const{ + + #ifdef ESP8266 + struct station_config conf; + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[33]; //ssid can be up to 32chars, => plus null term + memcpy(tmp, conf.ssid, sizeof(conf.ssid)); + tmp[32] = 0; //nullterm in case of 32 char ssid + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + if(persistent){ + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.ssid)); + } + else { + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_ap_record_t info; + if(!esp_wifi_sta_get_ap_info(&info)) { + return String(reinterpret_cast(info.ssid)); + } + return String(); + } + #endif +} + +String WiFiManager::WiFi_psk(bool persistent) const { + #ifdef ESP8266 + struct station_config conf; + + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[65]; //psk is 64 bytes hex => plus null term + memcpy(tmp, conf.password, sizeof(conf.password)); + tmp[64] = 0; //null term in case of 64 byte psk + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + // only if wifi is init + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.password)); + #endif +} + +#ifdef ESP32 + #ifdef WM_ARDUINOEVENTS + void WiFiManager::WiFiEvent(WiFiEvent_t event,arduino_event_info_t info){ + #else + void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ + #define wifi_sta_disconnected disconnected + #define ARDUINO_EVENT_WIFI_STA_DISCONNECTED SYSTEM_EVENT_STA_DISCONNECTED + #define ARDUINO_EVENT_WIFI_SCAN_DONE SYSTEM_EVENT_SCAN_DONE + #endif + if(!_hasBegun){ + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_VERBOSE,"[ERROR] WiFiEvent, not ready"); + #endif + // Serial.println(F("\n[EVENT] WiFiEvent logging (wm debug not available)")); + // Serial.print(F("[EVENT] ID: ")); + // Serial.println(event); + return; + } + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_VERBOSE,"[EVENT]",event); + #endif + if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: "),info.wifi_sta_disconnected.reason); + #endif + if(info.wifi_sta_disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.wifi_sta_disconnected.reason == WIFI_REASON_AUTH_FAIL){ + _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail + } else _lastconxresulttmp = WiFi.status(); + #ifdef WM_DEBUG_LEVEL + if(info.wifi_sta_disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: NO_AP_FOUND")); + if(info.wifi_sta_disconnected.reason == WIFI_REASON_ASSOC_FAIL){ + if(_aggresiveReconn) _connectRetries+=4; + DEBUG_WM(DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: AUTH FAIL")); + } + #endif + #ifdef esp32autoreconnect + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting")); + #endif + WiFi.reconnect(); + #endif + } + else if(event == ARDUINO_EVENT_WIFI_SCAN_DONE){ + uint16_t scans = WiFi.scanComplete(); + WiFi_scanComplete(scans); + } +} +#endif + +void WiFiManager::WiFi_autoReconnect(){ + #ifdef ESP8266 + WiFi.setAutoReconnect(_wifiAutoReconnect); + #elif defined(ESP32) + // if(_wifiAutoReconnect){ + // @todo move to seperate method, used for event listener now + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("ESP32 event handler enabled")); + #endif + using namespace std::placeholders; + if(wm_event_id == 0) wm_event_id = WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + // } + #endif +} + +// Called when /update is requested +void WiFiManager::handleUpdate() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- Handle update")); + #endif + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + String page = getHTTPHead(_title); // @token options + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_t), _title); + str.replace(FPSTR(T_v), configPortalActive ? _apName : (getWiFiHostname() + " - " + WiFi.localIP().toString())); // use ip if ap is not active for heading + page += str; + + page += FPSTR(HTTP_UPDATE); + page += FPSTR(HTTP_END); + + HTTPSend(page); + +} + +// upload via /u POST +void WiFiManager::handleUpdating(){ + // @todo + // cannot upload files in captive portal, file select is not allowed, show message with link or hide + // cannot upload if softreset after upload, maybe check for hard reset at least for dev, ERROR[11]: Invalid bootstrapping state, reset ESP8266 before updating + // add upload status to webpage somehow + // abort upload if error detected ? + // [x] supress cp timeout on upload, so it doesnt keep uploading? + // add progress handler for debugging + // combine route handlers into one callback and use argument or post checking instead of mutiple functions maybe, if POST process else server upload page? + // [x] add upload checking, do we need too check file? + // convert output to debugger if not moving to example + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + bool error = false; + unsigned long _configPortalTimeoutSAV = _configPortalTimeout; // store cp timeout + _configPortalTimeout = 0; // disable timeout + + // handler for the file upload, get's the sketch bytes, and writes + // them through the Update object + HTTPUpload& upload = server->upload(); + + // UPLOAD START + if (upload.status == UPLOAD_FILE_START) { + if(_debug) Serial.setDebugOutput(true); + uint32_t maxSketchSpace; + + // Use new callback for before OTA update + if (_preotaupdatecallback != NULL) { + _preotaupdatecallback(); // @CALLBACK + } + #ifdef ESP8266 + WiFiUDP::stopAll(); + maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; + #elif defined(ESP32) + // Think we do not need to stop WiFIUDP because we haven't started a listener + // maxSketchSpace = (ESP.getFlashChipSize() - 0x1000) & 0xFFFFF000; + // #define UPDATE_SIZE_UNKNOWN 0xFFFFFFFF // include update.h + maxSketchSpace = UPDATE_SIZE_UNKNOWN; + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,"Update file: ", upload.filename.c_str()); + #endif + + // Update.onProgress(THandlerFunction_Progress fn); + // Update.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + // }); + + if (!Update.begin(maxSketchSpace)) { // start with max available size + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] OTA Update ERROR"), Update.getError()); + #endif + error = true; + Update.end(); // Not sure the best way to abort, I think client will keep sending.. + } + } + // UPLOAD WRITE + else if (upload.status == UPLOAD_FILE_WRITE) { + // Serial.print("."); + if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] OTA Update WRITE ERROR"), Update.getError()); + //Update.printError(Serial); // write failure + #endif + error = true; + } + } + // UPLOAD FILE END + else if (upload.status == UPLOAD_FILE_END) { + if (Update.end(true)) { // true to set the size to the current progress + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("\n\n[OTA] OTA FILE END bytes: "), upload.totalSize); + // Serial.printf("Updated: %u bytes\r\nRebooting...\r\n", upload.totalSize); + #endif + } + else { + Update.printError(Serial); + error = true; + } + } + // UPLOAD ABORT + else if (upload.status == UPLOAD_FILE_ABORTED) { + Update.end(); + DEBUG_WM(F("[OTA] Update was aborted")); + error = true; + } + if(error) _configPortalTimeout = _configPortalTimeoutSAV; + delay(0); +} + +// upload and ota done, show status +void WiFiManager::handleUpdateDone() { + DEBUG_WM(DEBUG_VERBOSE, F("<- Handle update done")); + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + + String page = getHTTPHead(FPSTR(S_options)); // @token options + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_t),_title); + str.replace(FPSTR(T_v), configPortalActive ? _apName : WiFi.localIP().toString()); // use ip if ap is not active for heading + page += str; + + if (Update.hasError()) { + page += FPSTR(HTTP_UPDATE_FAIL); + #ifdef ESP32 + page += "OTA Error: " + (String)Update.errorString(); + #else + page += "OTA Error: " + (String)Update.getError(); + #endif + DEBUG_WM(F("[OTA] update failed")); + } + else { + page += FPSTR(HTTP_UPDATE_SUCCESS); + DEBUG_WM(F("[OTA] update ok")); + } + page += FPSTR(HTTP_END); + + HTTPSend(page); + + delay(1000); // send page + if (!Update.hasError()) { + ESP.restart(); + } +} + +#endif diff --git a/firmware/libraries/WiFiManager/WiFiManager.h b/firmware/libraries/WiFiManager/WiFiManager.h new file mode 100644 index 0000000..4c057ee --- /dev/null +++ b/firmware/libraries/WiFiManager/WiFiManager.h @@ -0,0 +1,765 @@ +/** + * WiFiManager.h + * + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + + +#ifndef WiFiManager_h +#define WiFiManager_h + +#if defined(ESP8266) || defined(ESP32) + +#ifdef ESP8266 +#include +#endif + +#include + +// #define WM_MDNS // includes MDNS, also set MDNS with sethostname +// #define WM_FIXERASECONFIG // use erase flash fix +// #define WM_ERASE_NVS // esp32 erase(true) will erase NVS +// #define WM_RTC // esp32 info page will include reset reasons + +// #define WM_JSTEST // build flag for enabling js xhr tests +// #define WIFI_MANAGER_OVERRIDE_STRINGS // build flag for using own strings include + +#ifdef ARDUINO_ESP8266_RELEASE_2_3_0 +#warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" +// @todo check failing on platform = espressif8266@1.7.3 +#define WM_NOASYNC // esp8266 no async scan wifi +#define WM_NOCOUNTRY // esp8266 no country +#define WM_NOAUTH // no httpauth +#define WM_NOSOFTAPSSID // no softapssid() @todo shim +#endif + +#ifdef ARDUINO_ESP32S3_DEV +#define WM_NOTEMP +#endif + +// #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. + +// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, @DEPRECATED +// autoreconnect is WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 + +#define WM_WEBSERVERSHIM // use webserver shim lib + +#define WM_G(string_literal) (String(FPSTR(string_literal)).c_str()) + +#define WM_STRING2(x) #x +#define WM_STRING(x) STRING2(x) + +// #include +#ifdef ESP_IDF_VERSION + // #pragma message "ESP_IDF_VERSION_MAJOR = " WM_STRING(ESP_IDF_VERSION_MAJOR) + // #pragma message "ESP_IDF_VERSION_MINOR = " WM_STRING(ESP_IDF_VERSION_MINOR) + // #pragma message "ESP_IDF_VERSION_PATCH = " WM_STRING(ESP_IDF_VERSION_PATCH) + #define VER_IDF_STR WM_STRING(ESP_IDF_VERSION_MAJOR) "." WM_STRING(ESP_IDF_VERSION_MINOR) "." WM_STRING(ESP_IDF_VERSION_PATCH) +#endif + +// #include "esp_arduino_version.h" +#ifdef ESP_ARDUINO_VERSION + // #pragma message "ESP_ARDUINO_VERSION_MAJOR = " WM_STRING(ESP_ARDUINO_VERSION_MAJOR) + // #pragma message "ESP_ARDUINO_VERSION_MINOR = " WM_STRING(ESP_ARDUINO_VERSION_MINOR) + // #pragma message "ESP_ARDUINO_VERSION_PATCH = " WM_STRING(ESP_ARDUINO_VERSION_PATCH) + #define VER_ARDUINO_STR WM_STRING(ESP_ARDUINO_VERSION_MAJOR) "." WM_STRING(ESP_ARDUINO_VERSION_MINOR) "." WM_STRING(ESP_ARDUINO_VERSION_PATCH) +#else + // #include + // #pragma message "ESP_ARDUINO_VERSION_GIT = " WM_STRING(ARDUINO_ESP32_GIT_VER)// 0x46d5afb1 + // #pragma message "ESP_ARDUINO_VERSION_DESC = " WM_STRING(ARDUINO_ESP32_GIT_DESC) // 1.0.6 + #define VER_ARDUINO_STR "Unknown" + // #pragma message "ESP_ARDUINO_VERSION_REL = " WM_STRING(ARDUINO_ESP32_RELEASE) //"1_0_6" +#endif + +#ifdef ESP8266 + + extern "C" { + #include "user_interface.h" + } + #include + #include + + #ifdef WM_MDNS + #include + #endif + + #define WIFI_getChipId() ESP.getChipId() + #define WM_WIFIOPEN ENC_TYPE_NONE + +#elif defined(ESP32) + + #include + #include + #include + + #define WIFI_getChipId() (uint32_t)ESP.getEfuseMac() + #define WM_WIFIOPEN WIFI_AUTH_OPEN + + #ifndef WEBSERVER_H + #ifdef WM_WEBSERVERSHIM + #include + #else + #include + // Forthcoming official ? probably never happening + // https://github.com/esp8266/ESPWebServer + #endif + #endif + + #ifdef WM_ERASE_NVS + #include + #include + #endif + + #ifdef WM_MDNS + #include + #endif + + #ifdef WM_RTC + #include + #endif + +#else +#endif + +#include +#include +#include "strings_en.h" + +#ifndef WIFI_MANAGER_MAX_PARAMS + #define WIFI_MANAGER_MAX_PARAMS 5 // params will autoincrement and realloc by this amount when max is reached +#endif + +#define WFM_LABEL_BEFORE 1 +#define WFM_LABEL_AFTER 2 +#define WFM_NO_LABEL 0 +#define WFM_LABEL_DEFAULT 1 + +class WiFiManagerParameter { + public: + /** + Create custom parameters that can be added to the WiFiManager setup web page + @id is used for HTTP queries and must not contain spaces nor other special characters + */ + WiFiManagerParameter(); + WiFiManagerParameter(const char *custom); + WiFiManagerParameter(const char *id, const char *label); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); + ~WiFiManagerParameter(); + // WiFiManagerParameter& operator=(const WiFiManagerParameter& rhs); + + const char *getID() const; + const char *getValue() const; + const char *getLabel() const; + const char *getPlaceholder() const; // @deprecated, use getLabel + int getValueLength() const; + int getLabelPlacement() const; + virtual const char *getCustomHTML() const; + void setValue(const char *defaultValue, int length); + + protected: + void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); + + private: + WiFiManagerParameter& operator=(const WiFiManagerParameter&); + const char *_id; + const char *_label; + char *_value; + int _length; + int _labelPlacement; + protected: + const char *_customHTML; + friend class WiFiManager; +}; + + +class WiFiManager +{ + public: + WiFiManager(Print& consolePort); + WiFiManager(); + ~WiFiManager(); + void WiFiManagerInit(); + + // auto connect to saved wifi, or custom, and start config portal on failures + boolean autoConnect(); + boolean autoConnect(char const *apName, char const *apPassword = NULL); + + //manually start the config portal, autoconnect does this automatically on connect failure + boolean startConfigPortal(); // auto generates apname + boolean startConfigPortal(char const *apName, char const *apPassword = NULL); + + //manually stop the config portal if started manually, stop immediatly if non blocking, flag abort if blocking + bool stopConfigPortal(); + + //manually start the web portal, autoconnect does this automatically on connect failure + void startWebPortal(); + + //manually stop the web portal if started manually + void stopWebPortal(); + + // Run webserver processing, if setConfigPortalBlocking(false) + boolean process(); + + // get the AP name of the config portal, so it can be used in the callback + String getConfigPortalSSID(); + int getRSSIasQuality(int RSSI); + + // erase wifi credentials + void resetSettings(); + + // reboot esp + void reboot(); + + // disconnect wifi, without persistent saving or erasing + bool disconnect(); + + // erase esp + bool erase(); + bool erase(bool opt); + + //adds a custom parameter, returns false on failure + bool addParameter(WiFiManagerParameter *p); + + //returns the list of Parameters + WiFiManagerParameter** getParameters(); + + // returns the Parameters Count + int getParametersCount(); + + // SET CALLBACKS + + //called after AP mode and config portal has started + void setAPCallback( std::function func ); + + //called after webserver has started + void setWebServerCallback( std::function func ); + + //called when settings reset have been triggered + void setConfigResetCallback( std::function func ); + + //called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) + void setSaveConfigCallback( std::function func ); + + //called when saving params-in-wifi or params before anything else happens (eg wifi) + void setPreSaveConfigCallback( std::function func ); + + //called when saving params before anything else happens + void setPreSaveParamsCallback( std::function func ); + + //called when saving either params-in-wifi or params page + void setSaveParamsCallback( std::function func ); + + //called just before doing OTA update + void setPreOtaUpdateCallback( std::function func ); + + //sets timeout before AP,webserver loop ends and exits even if there has been no setup. + //useful for devices that failed to connect at some point and got stuck in a webserver loop + //in seconds setConfigPortalTimeout is a new name for setTimeout, ! not used if setConfigPortalBlocking + void setConfigPortalTimeout(unsigned long seconds); + void setTimeout(unsigned long seconds); // @deprecated, alias + + //sets timeout for which to attempt connecting, useful if you get a lot of failed connects + void setConnectTimeout(unsigned long seconds); + + // sets number of retries for autoconnect, force retry after wait failure exit + void setConnectRetries(uint8_t numRetries); // default 1 + + //sets timeout for which to attempt connecting on saves, useful if there are bugs in esp waitforconnectloop + void setSaveConnectTimeout(unsigned long seconds); + + // lets you disable automatically connecting after save from webportal + void setSaveConnect(bool connect = true); + + // toggle debug output + void setDebugOutput(boolean debug); + void setDebugOutput(boolean debug, String prefix); // log line prefix, default "*wm:" + + //set min quality percentage to include in scan, defaults to 8% if not specified + void setMinimumSignalQuality(int quality = 8); + + //sets a custom ip /gateway /subnet configuration + void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + + //sets config for a static IP + void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + + //sets config for a static IP with DNS + void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); + + //if this is set, it will exit after config, even if connection is unsuccessful. + void setBreakAfterConfig(boolean shouldBreak); + + // if this is set, portal will be blocking and wait until save or exit, + // is false user must manually `process()` to handle config portal, + // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal + void setConfigPortalBlocking(boolean shouldBlock); + + //add custom html at inside for all pages + void setCustomHeadElement(const char* html); + + //if this is set, customise style + void setCustomMenuHTML(const char* html); + + //if this is true, remove duplicated Access Points - defaut true + void setRemoveDuplicateAPs(boolean removeDuplicates); + + //setter for ESP wifi.persistent so we can remember it and restore user preference, as WIFi._persistent is protected + void setRestorePersistent(boolean persistent); + + //if true, always show static net inputs, IP, subnet, gateway, else only show if set via setSTAStaticIPConfig + void setShowStaticFields(boolean alwaysShow); + + //if true, always show static dns, esle only show if set via setSTAStaticIPConfig + void setShowDnsFields(boolean alwaysShow); + + // toggle showing the saved wifi password in wifi form, could be a security issue. + void setShowPassword(boolean show); + + //if false, disable captive portal redirection + void setCaptivePortalEnable(boolean enabled); + + //if false, timeout captive portal even if a STA client connected to softAP (false), suggest disabling if captiveportal is open + void setAPClientCheck(boolean enabled); + + //if true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open + void setWebPortalClientCheck(boolean enabled); + + // if true, enable autoreconnecting + void setWiFiAutoReconnect(boolean enabled); + + // if true, wifiscan will show percentage instead of quality icons, until we have better templating + void setScanDispPerc(boolean enabled); + + // if true (default) then start the config portal from autoConnect if connection failed + void setEnableConfigPortal(boolean enable); + + // if true (default) then stop the config portal from autoConnect when wifi is saved + void setDisableConfigPortal(boolean enable); + + // set a custom hostname, sets sta and ap dhcp client id for esp32, and sta for esp8266 + bool setHostname(const char * hostname); + bool setHostname(String hostname); + + // show erase wifi onfig button on info page, true + void setShowInfoErase(boolean enabled); + + // show OTA upload button on info page + void setShowInfoUpdate(boolean enabled); + + // set ap channel + void setWiFiAPChannel(int32_t channel); + + // set ap hidden + void setWiFiAPHidden(bool hidden); // default false + + // clean connect, always disconnect before connecting + void setCleanConnect(bool enable); // default false + + // set custom menu items and order, vector or arr + // see _menutokens for ids + void setMenu(std::vector& menu); + void setMenu(const char* menu[], uint8_t size); + + // set the webapp title, default WiFiManager + void setTitle(String title); + + // add params to its own menu page and remove from wifi, NOT TO BE COMBINED WITH setMenu! + void setParamsPage(bool enable); + + // get last connection result, includes autoconnect and wifisave + uint8_t getLastConxResult(); + + // get a status as string + String getWLStatusString(uint8_t status); + String getWLStatusString(); + + // get wifi mode as string + String getModeString(uint8_t mode); + + // check if the module has a saved ap to connect to + bool getWiFiIsSaved(); + + // helper to get saved password, if persistent get stored, else get current if connected + String getWiFiPass(bool persistent = true); + + // helper to get saved ssid, if persistent get stored, else get current if connected + String getWiFiSSID(bool persistent = true); + + // debug output the softap config + void debugSoftAPConfig(); + + // debug output platform info and versioning + void debugPlatformInfo(); + + // helper for html + String htmlEntities(String str, bool whitespace = false); + + // set the country code for wifi settings, CN + void setCountry(String cc); + + // set body class (invert), may be used for hacking in alt classes + void setClass(String str); + + // set dark mode via invert class + void setDarkMode(bool enable); + + // get default ap esp uses , esp_chipid etc + String getDefaultAPName(); + + // set port of webserver, 80 + void setHttpPort(uint16_t port); + + // check if config portal is active (true) + bool getConfigPortalActive(); + + // check if web portal is active (true) + bool getWebPortalActive(); + + // to preload autoconnect for test fixtures or other uses that skip esp sta config + bool preloadWiFi(String ssid, String pass); + + // get hostname helper + String getWiFiHostname(); + + + std::unique_ptr dnsServer; + + #if defined(ESP32) && defined(WM_WEBSERVERSHIM) + using WM_WebServer = WebServer; + #else + using WM_WebServer = ESP8266WebServer; + #endif + + std::unique_ptr server; + + private: + // vars + std::vector _menuIds; + std::vector _menuIdsParams = {"wifi","param","info","exit"}; + std::vector _menuIdsUpdate = {"wifi","param","info","update","exit"}; + std::vector _menuIdsDefault = {"wifi","info","exit","sep","update"}; + + // ip configs @todo struct ? + IPAddress _ap_static_ip; + IPAddress _ap_static_gw; + IPAddress _ap_static_sn; + IPAddress _sta_static_ip; + IPAddress _sta_static_gw; + IPAddress _sta_static_sn; + IPAddress _sta_static_dns; + + unsigned long _configPortalStart = 0; // ms config portal start time (updated for timeouts) + unsigned long _webPortalAccessed = 0; // ms last web access time + uint8_t _lastconxresult = WL_IDLE_STATUS; // store last result when doing connect operations + int _numNetworks = 0; // init index for numnetworks wifiscans + unsigned long _lastscan = 0; // ms for timing wifi scans + unsigned long _startscan = 0; // ms for timing wifi scans + unsigned long _startconn = 0; // ms for timing wifi connects + + // defaults + const byte DNS_PORT = 53; + String _apName = "no-net"; + String _apPassword = ""; + String _ssid = ""; // var temp ssid + String _pass = ""; // var temp psk + String _defaultssid = ""; // preload ssid + String _defaultpass = ""; // preload pass + + // options flags + unsigned long _configPortalTimeout = 0; // ms close config portal loop if set (depending on _cp/webClientCheck options) + unsigned long _connectTimeout = 0; // ms stop trying to connect to ap if set + unsigned long _saveTimeout = 0; // ms stop trying to connect to ap on saves, in case bugs in esp waitforconnectresult + + WiFiMode_t _usermode = WIFI_STA; // Default user mode + String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid + int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. + bool _cleanConnect = false; // disconnect before connect in connectwifi, increases stability on connects + bool _connectonsave = true; // connect to wifi when saving creds + bool _disableSTA = false; // disable sta when starting ap, always + bool _disableSTAConn = true; // disable sta when starting ap, if sta is not connected ( stability ) + bool _channelSync = false; // use same wifi sta channel when starting ap + int32_t _apChannel = 0; // default channel to use for ap, 0 for auto + bool _apHidden = false; // store softap hidden value + uint16_t _httpPort = 80; // port for webserver + // uint8_t _retryCount = 0; // counter for retries, probably not needed if synchronous + uint8_t _connectRetries = 1; // number of sta connect retries, force reconnect, wait loop (connectimeout) does not always work and first disconnect bails + bool _aggresiveReconn = true; // use an agrressive reconnect strategy, WILL delay conxs + // on some conn failure modes will add delays and many retries to work around esp and ap bugs, ie, anti de-auth protections + // https://github.com/tzapu/WiFiManager/issues/1067 + bool _allowExit = true; // allow exit in nonblocking, else user exit/abort calls will be ignored including cptimeout + + #ifdef ESP32 + wifi_event_id_t wm_event_id = 0; + static uint8_t _lastconxresulttmp; // tmp var for esp32 callback + #endif + + #ifndef WL_STATION_WRONG_PASSWORD + uint8_t WL_STATION_WRONG_PASSWORD = 7; // @kludge define a WL status for wrong password + #endif + + // parameter options + int _minimumQuality = -1; // filter wifiscan ap by this rssi + int _staShowStaticFields = 0; // ternary 1=always show static ip fields, 0=only if set, -1=never(cannot change ips via web!) + int _staShowDns = 0; // ternary 1=always show dns, 0=only if set, -1=never(cannot change dns via web!) + boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan + boolean _showPassword = false; // show or hide saved password on wifi form, might be a security issue! + boolean _shouldBreakAfterConfig = false; // stop configportal on save failure + boolean _configPortalIsBlocking = true; // configportal enters blocking loop + boolean _enableCaptivePortal = true; // enable captive portal redirection + boolean _userpersistent = true; // users preffered persistence to restore + boolean _wifiAutoReconnect = true; // there is no platform getter for this, we must assume its true and make it so + boolean _apClientCheck = false; // keep cp alive if ap have station + boolean _webClientCheck = true; // keep cp alive if web have client + boolean _scanDispOptions = false; // show percentage in scans not icons + boolean _paramsInWifi = true; // show custom parameters on wifi page + boolean _showInfoErase = true; // info page erase button + boolean _showInfoUpdate = true; // info page update button + boolean _showBack = false; // show back button + boolean _enableConfigPortal = true; // FOR autoconnect - start config portal if autoconnect failed + boolean _disableConfigPortal = true; // FOR autoconnect - stop config portal if cp wifi save + String _hostname = ""; // hostname for esp8266 for dhcp, and or MDNS + + const char* _customHeadElement = ""; // store custom head element html from user isnide + const char* _customMenuHTML = ""; // store custom head element html from user inside <> + String _bodyClass = ""; // class to add to body + String _title = FPSTR(S_brand); // app title - default WiFiManager + + // internal options + + // wifiscan notes + // currently disabled due to issues with caching, sometimes first scan is empty esp32 wifi not init yet race, or portals hit server nonstop flood + // The following are background wifi scanning optimizations + // experimental to make scans faster, preload scans after starting cp, and visiting home page, so when you click wifi its already has your list + // ideally we would add async and xhr here but I am holding off on js requirements atm + // might be slightly buggy since captive portals hammer the home page, @todo workaround this somehow. + // cache time helps throttle this + // async enables asyncronous scans, so they do not block anything + // the refresh button bypasses cache + // no aps found is problematic as scans are always going to want to run, leading to page load delays + boolean _preloadwifiscan = false; // preload wifiscan if true + boolean _asyncScan = false; // perform wifi network scan async + unsigned int _scancachetime = 30000; // ms cache time for background scans + + boolean _disableIpFields = false; // modify function of setShow_X_Fields(false), forces ip fields off instead of default show if set, eg. _staShowStaticFields=-1 + + String _wificountry = ""; // country code, @todo define in strings lang + + // wrapper functions for handling setting and unsetting persistent for now. + bool esp32persistent = false; + bool _hasBegun = false; // flag wm loaded,unloaded + void _begin(); + void _end(); + + void setupConfigPortal(); + bool shutdownConfigPortal(); + bool setupHostname(bool restart); + +#ifdef NO_EXTRA_4K_HEAP + boolean _tryWPS = false; // try WPS on save failure, unsupported + void startWPS(); +#endif + + bool startAP(); + void setupDNSD(); + void setupHTTPServer(); + + uint8_t connectWifi(String ssid, String pass, bool connect = true); + bool setSTAConfig(); + bool wifiConnectDefault(); + bool wifiConnectNew(String ssid, String pass,bool connect = true); + + uint8_t waitForConnectResult(); + uint8_t waitForConnectResult(uint32_t timeout); + void updateConxResult(uint8_t status); + + // webserver handlers + void HTTPSend(String content); + void handleRoot(); + void handleWifi(boolean scan); + void handleWifiSave(); + void handleInfo(); + void handleReset(); + void handleNotFound(); + void handleExit(); + void handleClose(); + // void handleErase(); + void handleErase(boolean opt); + void handleParam(); + void handleWiFiStatus(); + void handleRequest(); + void handleParamSave(); + void doParamSave(); + + boolean captivePortal(); + boolean configPortalHasTimeout(); + uint8_t processConfigPortal(); + void stopCaptivePortal(); + // OTA Update handler + void handleUpdate(); + void handleUpdating(); + void handleUpdateDone(); + + + // wifi platform abstractions + bool WiFi_Mode(WiFiMode_t m); + bool WiFi_Mode(WiFiMode_t m,bool persistent); + bool WiFi_Disconnect(); + bool WiFi_enableSTA(bool enable); + bool WiFi_enableSTA(bool enable,bool persistent); + bool WiFi_eraseConfig(); + uint8_t WiFi_softap_num_stations(); + bool WiFi_hasAutoConnect(); + void WiFi_autoReconnect(); + String WiFi_SSID(bool persistent = true) const; + String WiFi_psk(bool persistent = true) const; + bool WiFi_scanNetworks(); + bool WiFi_scanNetworks(bool force,bool async); + bool WiFi_scanNetworks(unsigned int cachetime,bool async); + bool WiFi_scanNetworks(unsigned int cachetime); + void WiFi_scanComplete(int networksFound); + bool WiFiSetCountry(); + + #ifdef ESP32 + + // check for arduino or system event system, handle esp32 arduino v2 and IDF + #if defined(ESP_ARDUINO_VERSION) && defined(ESP_ARDUINO_VERSION_VAL) + + #define WM_ARDUINOVERCHECK ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0) + + #ifdef WM_ARDUINOVERCHECK + #define WM_ARDUINOEVENTS + #else + #define WM_NOSOFTAPSSID + #define WM_NOCOUNTRY + #endif + + #else + #define WM_NOCOUNTRY + #endif + + #ifdef WM_NOCOUNTRY + #warning "ESP32 set country unavailable" + #endif + + + #ifdef WM_ARDUINOEVENTS + void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info); + #else + void WiFiEvent(WiFiEvent_t event, system_event_info_t info); + #endif + #endif + + // output helpers + String getParamOut(); + String getIpForm(String id, String title, String value); + String getScanItemOut(); + String getStaticOut(); + String getHTTPHead(String title); + String getMenuOut(); + //helpers + boolean isIp(String str); + String toStringIp(IPAddress ip); + boolean validApPassword(); + String encryptionTypeStr(uint8_t authmode); + void reportStatus(String &page); + String getInfoData(String id); + + // flags + boolean connect = false; + boolean abort = false; + boolean reset = false; + boolean configPortalActive = false; + boolean webPortalActive = false; + boolean portalTimeoutResult = false; + boolean portalAbortResult = false; + boolean storeSTAmode = true; // option store persistent STA mode in connectwifi + int timer = 0; // timer for debug throttle for numclients, and portal timeout messages + + // WiFiManagerParameter + int _paramsCount = 0; + int _max_params; + WiFiManagerParameter** _params = NULL; + + // debugging + typedef enum { + DEBUG_ERROR = 0, + DEBUG_NOTIFY = 1, // default stable + DEBUG_VERBOSE = 2, + DEBUG_DEV = 3, // default dev + DEBUG_MAX = 4 + } wm_debuglevel_t; + + boolean _debug = true; + String _debugPrefix = FPSTR(S_debugPrefix); + + wm_debuglevel_t debugLvlShow = DEBUG_VERBOSE; // at which level start showing [n] level tags + + // build debuglevel support + // @todo use DEBUG_ESP_x? + + // Set default debug level + #ifndef WM_DEBUG_LEVEL + #define WM_DEBUG_LEVEL DEBUG_VERBOSE // development default, not release + #endif + + // override debug level OFF + #ifdef WM_NODEBUG + #undef WM_DEBUG_LEVEL + #endif + + #ifdef WM_DEBUG_LEVEL + uint8_t _debugLevel = (uint8_t)WM_DEBUG_LEVEL; + #else + uint8_t _debugLevel = DEBUG_VERBOSE; // default debug level + #endif + + // @todo use DEBUG_ESP_PORT ? + #ifdef WM_DEBUG_PORT + Print& _debugPort = WM_DEBUG_PORT; + #else + Print& _debugPort = Serial; // debug output stream ref + #endif + + template + void DEBUG_WM(Generic text); + + template + void DEBUG_WM(wm_debuglevel_t level,Generic text); + template + void DEBUG_WM(Generic text,Genericb textb); + template + void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); + + // callbacks + // @todo use cb list (vector) maybe event ids, allow no return value + std::function _apcallback; + std::function _webservercallback; + std::function _savewificallback; + std::function _presavewificallback; + std::function _presaveparamscallback; + std::function _saveparamscallback; + std::function _resetcallback; + std::function _preotaupdatecallback; + + template + auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { + return obj->fromString(s); + } + auto optionalIPFromString(...) -> bool { + // DEBUG_WM("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work."); + return false; + } + +}; + +#endif + +#endif diff --git a/firmware/libraries/WiFiManager/examples/Advanced/Advanced.ino b/firmware/libraries/WiFiManager/examples/Advanced/Advanced.ino new file mode 100644 index 0000000..3834e56 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Advanced/Advanced.ino @@ -0,0 +1,141 @@ +/** + * WiFiManager advanced demo, contains advanced configurartion options + * Implements TRIGGEN_PIN button press, press for ondemand configportal, hold for 3 seconds for reset settings. + */ +#include // https://github.com/tzapu/WiFiManager + +#define TRIGGER_PIN 0 + +// wifimanager can run in a blocking mode or a non blocking mode +// Be sure to know how to process loops with no delay() if using non blocking +bool wm_nonblocking = false; // change to true to use non blocking + +WiFiManager wm; // global wm instance +WiFiManagerParameter custom_field; // global param ( for non blocking w params ) + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(3000); + Serial.println("\n Starting"); + + pinMode(TRIGGER_PIN, INPUT); + + // wm.resetSettings(); // wipe settings + + if(wm_nonblocking) wm.setConfigPortalBlocking(false); + + // add a custom input field + int customFieldLength = 40; + + + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\""); + + // test custom html input type(checkbox) + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type + + // test custom html(radio) + const char* custom_radio_str = "
One
Two
Three"; + new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input + + wm.addParameter(&custom_field); + wm.setSaveParamsCallback(saveParamCallback); + + // custom menu via array or vector + // + // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!) + // const char* menu[] = {"wifi","info","param","sep","restart","exit"}; + // wm.setMenu(menu,6); + std::vector menu = {"wifi","info","param","sep","restart","exit"}; + wm.setMenu(menu); + + // set dark theme + wm.setClass("invert"); + + + //set static ip + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn + // wm.setShowStaticFields(true); // force show static ip fields + // wm.setShowDnsFields(true); // force show dns field always + + // wm.setConnectTimeout(20); // how long to try to connect for before continuing + wm.setConfigPortalTimeout(30); // auto close configportal after n seconds + // wm.setCaptivePortalEnable(false); // disable captive portal redirection + // wm.setAPClientCheck(true); // avoid timeout if client connected to softap + + // wifi scan settings + // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) + // wm.setMinimumSignalQuality(20); // set min RSSI (percentage) to show in scans, null = 8% + // wm.setShowInfoErase(false); // do not show erase button on info page + // wm.setScanDispPerc(true); // show RSSI as percentage not graph icons + + // wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap + + if(!res) { + Serial.println("Failed to connect or hit timeout"); + // ESP.restart(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } +} + +void checkButton(){ + // check for button press + if ( digitalRead(TRIGGER_PIN) == LOW ) { + // poor mans debounce/press-hold, code not ideal for production + delay(50); + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Button Pressed"); + // still holding button for 3000 ms, reset settings, code not ideaa for production + delay(3000); // reset delay hold + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Button Held"); + Serial.println("Erasing Config, restarting"); + wm.resetSettings(); + ESP.restart(); + } + + // start portal w delay + Serial.println("Starting config portal"); + wm.setConfigPortalTimeout(120); + + if (!wm.startConfigPortal("OnDemandAP","password")) { + Serial.println("failed to connect or hit timeout"); + delay(3000); + // ESP.restart(); + } else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + } + } +} + + +String getParam(String name){ + //read parameter from server, for customhmtl input + String value; + if(wm.server->hasArg(name)) { + value = wm.server->arg(name); + } + return value; +} + +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); + Serial.println("PARAM customfieldid = " + getParam("customfieldid")); +} + +void loop() { + if(wm_nonblocking) wm.process(); // avoid delays() in loop when non-blocking and other long running code + checkButton(); + // put your main code here, to run repeatedly: +} diff --git a/firmware/libraries/WiFiManager/examples/Basic/Basic.ino b/firmware/libraries/WiFiManager/examples/Basic/Basic.ino new file mode 100644 index 0000000..59c95d9 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Basic/Basic.ino @@ -0,0 +1,41 @@ +#include // https://github.com/tzapu/WiFiManager + + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // it is a good practice to make sure your code sets wifi mode how you want it. + + // put your setup code here, to run once: + Serial.begin(115200); + + //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + // reset settings - wipe stored credentials for testing + // these are stored by the esp library + wm.resetSettings(); + + // Automatically connect using saved credentials, + // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"), + // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect()) + // then goes into a blocking loop awaiting configuration and will return success result + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap + + if(!res) { + Serial.println("Failed to connect"); + // ESP.restart(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + +} + +void loop() { + // put your main code here, to run repeatedly: +} diff --git a/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino b/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino new file mode 100644 index 0000000..ab52396 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino @@ -0,0 +1,27 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + wm.setConfigPortalBlocking(false); + wm.setConfigPortalTimeout(60); + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} diff --git a/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino b/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino new file mode 100644 index 0000000..3af79f0 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino @@ -0,0 +1,36 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; +WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + wm.addParameter(&custom_mqtt_server); + wm.setConfigPortalBlocking(false); + wm.setSaveParamsCallback(saveParamsCallback); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} + +void saveParamsCallback () { + Serial.println("Get Params:"); + Serial.print(custom_mqtt_server.getID()); + Serial.print(" : "); + Serial.println(custom_mqtt_server.getValue()); +} diff --git a/firmware/libraries/WiFiManager/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/firmware/libraries/WiFiManager/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino new file mode 100644 index 0000000..0bc3992 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino @@ -0,0 +1,85 @@ +/** + * OnDemandNonBlocking.ino + * example of running the webportal or configportal manually and non blocking + * trigger pin will start a webportal for 120 seconds then turn it off. + * startAP = true will start both the configportal AP and webportal + */ +#include // https://github.com/tzapu/WiFiManager + +// include MDNS +#ifdef ESP8266 +#include +#elif defined(ESP32) +#include +#endif + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +unsigned int timeout = 120; // seconds to run for +unsigned int startTime = millis(); +bool portalRunning = false; +bool startAP = false; // start AP and webserver if true, else start only webserver + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(1000); + Serial.println("\n Starting"); + + pinMode(TRIGGER_PIN, INPUT_PULLUP); + + // wm.resetSettings(); + wm.setHostname("MDNSEXAMPLE"); + // wm.setEnableConfigPortal(false); + // wm.setConfigPortalBlocking(false); + wm.autoConnect(); +} + +void loop() { + #ifdef ESP8266 + MDNS.update(); + #endif + doWiFiManager(); + // put your main code here, to run repeatedly: +} + +void doWiFiManager(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); // do processing + + // check for timeout + if((millis()-startTime) > (timeout*1000)){ + Serial.println("portaltimeout"); + portalRunning = false; + if(startAP){ + wm.stopConfigPortal(); + } + else{ + wm.stopWebPortal(); + } + } + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) { + if(startAP){ + Serial.println("Button Pressed, Starting Config Portal"); + wm.setConfigPortalBlocking(false); + wm.startConfigPortal(); + } + else{ + Serial.println("Button Pressed, Starting Web Portal"); + wm.startWebPortal(); + } + portalRunning = true; + startTime = millis(); + } +} + + diff --git a/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino new file mode 100644 index 0000000..d3c4ed8 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino @@ -0,0 +1,42 @@ +#include // https://github.com/tzapu/WiFiManager + +void configModeCallback (WiFiManager *myWiFiManager) { + Serial.println("Entered config mode"); + Serial.println(WiFi.softAPIP()); + //if you used auto generated SSID, print it + Serial.println(myWiFiManager->getConfigPortalSSID()); +} + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + //reset settings - for testing + //wifiManager.resetSettings(); + + //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode + wifiManager.setAPCallback(configModeCallback); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + if(!wifiManager.autoConnect()) { + Serial.println("failed to connect and hit timeout"); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(1000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + +} + +void loop() { + // put your main code here, to run repeatedly: + +} diff --git a/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino new file mode 100644 index 0000000..53a0d13 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino @@ -0,0 +1,43 @@ +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + + //exit after config instead of connecting + wifiManager.setBreakAfterConfig(true); + + //reset settings - for testing + //wifiManager.resetSettings(); + + + //tries to connect to last known settings + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" with password "password" + //and goes into a blocking loop awaiting configuration + if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + Serial.println("failed to connect, we should reset as see if it connects"); + delay(3000); + ESP.restart(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); +} + +void loop() { + // put your main code here, to run repeatedly: + + +} diff --git a/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino new file mode 100644 index 0000000..9f88e47 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino @@ -0,0 +1,71 @@ +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager + +/************************************************************************************** + * this example shows how to set a static IP configuration for the ESP + * although the IP shows in the config portal, the changes will revert + * to the IP set in the source file. + * if you want the ability to configure and persist the new IP configuration + * look at the FS examples, which save the config to file + *************************************************************************************/ + +//default custom static IP +//char static_ip[16] = "10.0.1.59"; +//char static_gw[16] = "10.0.1.1"; +//char static_sn[16] = "255.255.255.0"; + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + + //reset settings - for testing + //wifiManager.resetSettings(); + + //set static ip + //block1 should be used for ESP8266 core 2.1.0 or newer, otherwise use block2 + + //start-block1 + //IPAddress _ip,_gw,_sn; + //_ip.fromString(static_ip); + //_gw.fromString(static_gw); + //_sn.fromString(static_sn); + //end-block1 + + //start-block2 + IPAddress _ip = IPAddress(10, 0, 1, 78); + IPAddress _gw = IPAddress(10, 0, 1, 1); + IPAddress _sn = IPAddress(255, 255, 255, 0); + //end-block2 + + wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); + + + //tries to connect to last known settings + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" with password "password" + //and goes into a blocking loop awaiting configuration + if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + Serial.println("failed to connect, we should reset as see if it connects"); + delay(3000); + ESP.restart(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); +} + +void loop() { + // put your main code here, to run repeatedly: + + +} diff --git a/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino new file mode 100644 index 0000000..9df428d --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino @@ -0,0 +1,38 @@ +#include // https://github.com/tzapu/WiFiManager + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + //reset settings - for testing + //wifiManager.resetSettings(); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep + //in seconds + wifiManager.setConfigPortalTimeout(180); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + if(!wifiManager.autoConnect("AutoConnectAP")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + +} + +void loop() { + // put your main code here, to run repeatedly: + +} diff --git a/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino b/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 0000000..a45122a --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,47 @@ +/** + * OnDemandConfigPortal.ino + * example of running the configPortal AP manually, independantly from the captiveportal + * trigger pin will start a configPortal AP for 120 seconds then turn it off. + * + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +int timeout = 120; // seconds to run for + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + // is configuration portal requested? + if ( digitalRead(TRIGGER_PIN) == LOW) { + WiFiManager wm; + + //reset settings - for testing + //wm.resetSettings(); + + // set configportal timeout + wm.setConfigPortalTimeout(timeout); + + if (!wm.startConfigPortal("OnDemandAP")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + } + + // put your main code here, to run repeatedly: +} diff --git a/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino b/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino new file mode 100644 index 0000000..33fa384 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino @@ -0,0 +1,51 @@ +/** + * OnDemandWebPortal.ino + * example of running the webportal (always NON blocking) + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +bool portalRunning = false; + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + checkButton(); + // put your main code here, to run repeatedly: +} + +void checkButton(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW) { + delay(50); + if(digitalRead(TRIGGER_PIN) == LOW) { + if(!portalRunning){ + Serial.println("Button Pressed, Starting Portal"); + wm.startWebPortal(); + portalRunning = true; + } + else{ + Serial.println("Button Pressed, Stopping Portal"); + wm.stopWebPortal(); + portalRunning = false; + } + } + } +} + + diff --git a/firmware/libraries/WiFiManager/examples/Parameters/LittleFS/LittleFSParameters.ino b/firmware/libraries/WiFiManager/examples/Parameters/LittleFS/LittleFSParameters.ino new file mode 100644 index 0000000..188b3c1 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Parameters/LittleFS/LittleFSParameters.ino @@ -0,0 +1,79 @@ +/** + * Basic example using LittleFS to store data + */ + +#include +#include +#include + +String readFile(fs::FS &fs, const char * path){ + Serial.printf("Reading file: %s\r\n", path); + File file = fs.open(path, "r"); + if(!file || file.isDirectory()){ + Serial.println("- empty file or failed to open file"); + return String(); + } + Serial.println("- read from file:"); + String fileContent; + while(file.available()){ + fileContent+=String((char)file.read()); + } + file.close(); + Serial.println(fileContent); + return fileContent; +} +void writeFile(fs::FS &fs, const char * path, const char * message){ + Serial.printf("Writing file: %s\r\n", path); + File file = fs.open(path, "w"); + if(!file){ + Serial.println("- failed to open file for writing"); + return; + } + if(file.print(message)){ + Serial.println("- file written"); + } else { + Serial.println("- write failed"); + } + file.close(); +} + +int data = 4; + +#include +#define TRIGGER_PIN 2 +int timeout = 120; // seconds to run for + +void setup() { +if (!LittleFS.begin()) { //to start littlefs +Serial.println("LittleFS mount failed"); +return; +} +data = readFile(LittleFS, "/data.txt").toInt(); +WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + pinMode(TRIGGER_PIN, INPUT_PULLUP); + WiFiManager wm; + //wm.resetSettings(); + bool res; + res = wm.autoConnect("Setup"); + if(!res) { + Serial.println("Failed to connect"); + // ESP.restart(); + } + +} + +void loop() { +if ( digitalRead(TRIGGER_PIN) == LOW) { + WiFiManager wm; + //wm.resetSettings(); + wm.setConfigPortalTimeout(timeout); + if (!wm.startConfigPortal("Sharmander")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + ESP.restart(); + delay(5000); + } + Serial.println("connected...yeey :)"); +} +} \ No newline at end of file diff --git a/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino new file mode 100644 index 0000000..a9c7b79 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -0,0 +1,169 @@ +#include //this needs to be first, or it all crashes and burns... +#include //https://github.com/tzapu/WiFiManager + +#ifdef ESP32 + #include +#endif + +#include //https://github.com/bblanchon/ArduinoJson + +//define your default values here, if there are different values in config.json, they are overwritten. +char mqtt_server[40]; +char mqtt_port[6] = "8080"; +char api_token[34] = "YOUR_API_TOKEN"; + +//flag for saving data +bool shouldSaveConfig = false; + +//callback notifying us of the need to save config +void saveConfigCallback () { + Serial.println("Should save config"); + shouldSaveConfig = true; +} + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + //clean FS, for testing + //SPIFFS.format(); + + //read configuration from FS json + Serial.println("mounting FS..."); + + if (SPIFFS.begin()) { + Serial.println("mounted file system"); + if (SPIFFS.exists("/config.json")) { + //file exists, reading and loading + Serial.println("reading config file"); + File configFile = SPIFFS.open("/config.json", "r"); + if (configFile) { + Serial.println("opened config file"); + size_t size = configFile.size(); + // Allocate a buffer to store contents of the file. + std::unique_ptr buf(new char[size]); + + configFile.readBytes(buf.get(), size); + + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + DynamicJsonDocument json(1024); + auto deserializeError = deserializeJson(json, buf.get()); + serializeJson(json, Serial); + if ( ! deserializeError ) { +#else + DynamicJsonBuffer jsonBuffer; + JsonObject& json = jsonBuffer.parseObject(buf.get()); + json.printTo(Serial); + if (json.success()) { +#endif + Serial.println("\nparsed json"); + strcpy(mqtt_server, json["mqtt_server"]); + strcpy(mqtt_port, json["mqtt_port"]); + strcpy(api_token, json["api_token"]); + } else { + Serial.println("failed to load json config"); + } + configFile.close(); + } + } + } else { + Serial.println("failed to mount FS"); + } + //end read + + // The extra parameters to be configured (can be either global or just in the setup) + // After connecting, parameter.getValue() will get you the configured value + // id/name placeholder/prompt default length + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); + WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 32); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + + //set config save notify callback + wifiManager.setSaveConfigCallback(saveConfigCallback); + + //set static ip + wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0)); + + //add all your parameters here + wifiManager.addParameter(&custom_mqtt_server); + wifiManager.addParameter(&custom_mqtt_port); + wifiManager.addParameter(&custom_api_token); + + //reset settings - for testing + //wifiManager.resetSettings(); + + //set minimu quality of signal so it ignores AP's under that quality + //defaults to 8% + //wifiManager.setMinimumSignalQuality(); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep + //in seconds + //wifiManager.setTimeout(120); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + //read updated parameters + strcpy(mqtt_server, custom_mqtt_server.getValue()); + strcpy(mqtt_port, custom_mqtt_port.getValue()); + strcpy(api_token, custom_api_token.getValue()); + Serial.println("The values in the file are: "); + Serial.println("\tmqtt_server : " + String(mqtt_server)); + Serial.println("\tmqtt_port : " + String(mqtt_port)); + Serial.println("\tapi_token : " + String(api_token)); + + //save the custom parameters to FS + if (shouldSaveConfig) { + Serial.println("saving config"); + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + DynamicJsonDocument json(1024); +#else + DynamicJsonBuffer jsonBuffer; + JsonObject& json = jsonBuffer.createObject(); +#endif + json["mqtt_server"] = mqtt_server; + json["mqtt_port"] = mqtt_port; + json["api_token"] = api_token; + + File configFile = SPIFFS.open("/config.json", "w"); + if (!configFile) { + Serial.println("failed to open config file for writing"); + } + +#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + serializeJson(json, Serial); + serializeJson(json, configFile); +#else + json.printTo(Serial); + json.printTo(configFile); +#endif + configFile.close(); + //end save + } + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); +} + +void loop() { + // put your main code here, to run repeatedly: + +} diff --git a/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino new file mode 100644 index 0000000..63523e9 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino @@ -0,0 +1,194 @@ +#include //this needs to be first, or it all crashes and burns... + +#include //https://github.com/tzapu/WiFiManager + +#ifdef ESP32 + #include +#endif + +#include //https://github.com/bblanchon/ArduinoJson + +//define your default values here, if there are different values in config.json, they are overwritten. +//length should be max size + 1 +char mqtt_server[40]; +char mqtt_port[6] = "8080"; +char api_token[34] = "YOUR_APITOKEN"; +//default custom static IP +char static_ip[16] = "10.0.1.56"; +char static_gw[16] = "10.0.1.1"; +char static_sn[16] = "255.255.255.0"; + +//flag for saving data +bool shouldSaveConfig = false; + +//callback notifying us of the need to save config +void saveConfigCallback () { + Serial.println("Should save config"); + shouldSaveConfig = true; +} + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + //clean FS, for testing + //SPIFFS.format(); + + //read configuration from FS json + Serial.println("mounting FS..."); + + if (SPIFFS.begin()) { + Serial.println("mounted file system"); + if (SPIFFS.exists("/config.json")) { + //file exists, reading and loading + Serial.println("reading config file"); + File configFile = SPIFFS.open("/config.json", "r"); + if (configFile) { + Serial.println("opened config file"); + size_t size = configFile.size(); + // Allocate a buffer to store contents of the file. + std::unique_ptr buf(new char[size]); + + configFile.readBytes(buf.get(), size); + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + DynamicJsonDocument json(1024); + auto deserializeError = deserializeJson(json, buf.get()); + serializeJson(json, Serial); + if ( ! deserializeError ) { +#else + DynamicJsonBuffer jsonBuffer; + JsonObject& json = jsonBuffer.parseObject(buf.get()); + json.printTo(Serial); + if (json.success()) { +#endif + Serial.println("\nparsed json"); + + strcpy(mqtt_server, json["mqtt_server"]); + strcpy(mqtt_port, json["mqtt_port"]); + strcpy(api_token, json["api_token"]); + + if (json["ip"]) { + Serial.println("setting custom ip from config"); + strcpy(static_ip, json["ip"]); + strcpy(static_gw, json["gateway"]); + strcpy(static_sn, json["subnet"]); + Serial.println(static_ip); + } else { + Serial.println("no custom ip in config"); + } + } else { + Serial.println("failed to load json config"); + } + } + } + } else { + Serial.println("failed to mount FS"); + } + //end read + Serial.println(static_ip); + Serial.println(api_token); + Serial.println(mqtt_server); + + + // The extra parameters to be configured (can be either global or just in the setup) + // After connecting, parameter.getValue() will get you the configured value + // id/name placeholder/prompt default length + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5); + WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 34); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + + //set config save notify callback + wifiManager.setSaveConfigCallback(saveConfigCallback); + + //set static ip + IPAddress _ip, _gw, _sn; + _ip.fromString(static_ip); + _gw.fromString(static_gw); + _sn.fromString(static_sn); + + wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); + + //add all your parameters here + wifiManager.addParameter(&custom_mqtt_server); + wifiManager.addParameter(&custom_mqtt_port); + wifiManager.addParameter(&custom_api_token); + + //reset settings - for testing + //wifiManager.resetSettings(); + + //set minimu quality of signal so it ignores AP's under that quality + //defaults to 8% + wifiManager.setMinimumSignalQuality(); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep + //in seconds + //wifiManager.setTimeout(120); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + //read updated parameters + strcpy(mqtt_server, custom_mqtt_server.getValue()); + strcpy(mqtt_port, custom_mqtt_port.getValue()); + strcpy(api_token, custom_api_token.getValue()); + + //save the custom parameters to FS + if (shouldSaveConfig) { + Serial.println("saving config"); + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + DynamicJsonDocument json(1024); +#else + DynamicJsonBuffer jsonBuffer; + JsonObject& json = jsonBuffer.createObject(); +#endif + json["mqtt_server"] = mqtt_server; + json["mqtt_port"] = mqtt_port; + json["api_token"] = api_token; + + json["ip"] = WiFi.localIP().toString(); + json["gateway"] = WiFi.gatewayIP().toString(); + json["subnet"] = WiFi.subnetMask().toString(); + + File configFile = SPIFFS.open("/config.json", "w"); + if (!configFile) { + Serial.println("failed to open config file for writing"); + } + + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + serializeJson(json, Serial); + serializeJson(json, configFile); +#else + json.printTo(Serial); + json.printTo(configFile); +#endif + configFile.close(); + //end save + } + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); + Serial.println(WiFi.gatewayIP()); + Serial.println(WiFi.subnetMask()); +} + +void loop() { + // put your main code here, to run repeatedly: +} diff --git a/firmware/libraries/WiFiManager/examples/ParamsChildClass/ParamsChildClass.ino b/firmware/libraries/WiFiManager/examples/ParamsChildClass/ParamsChildClass.ino new file mode 100644 index 0000000..8739a05 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/ParamsChildClass/ParamsChildClass.ino @@ -0,0 +1,143 @@ +/** + * WiFiManagerParameter child class example + */ +#include // https://github.com/tzapu/WiFiManager +#include +#include + +#define SETUP_PIN 0 + +class IPAddressParameter : public WiFiManagerParameter { +public: + IPAddressParameter(const char *id, const char *placeholder, IPAddress address) + : WiFiManagerParameter("") { + init(id, placeholder, address.toString().c_str(), 16, "", WFM_LABEL_BEFORE); + } + + bool getValue(IPAddress &ip) { + return ip.fromString(WiFiManagerParameter::getValue()); + } +}; + +class IntParameter : public WiFiManagerParameter { +public: + IntParameter(const char *id, const char *placeholder, long value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + long getValue() { + return String(WiFiManagerParameter::getValue()).toInt(); + } +}; + +class FloatParameter : public WiFiManagerParameter { +public: + FloatParameter(const char *id, const char *placeholder, float value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + float getValue() { + return String(WiFiManagerParameter::getValue()).toFloat(); + } +}; + +struct Settings { + float f; + int i; + char s[20]; + uint32_t ip; +} sett; + + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + pinMode(SETUP_PIN, INPUT_PULLUP); + Serial.begin(115200); + + //Delay to push SETUP button + Serial.println("Press setup button"); + for (int sec = 3; sec > 0; sec--) { + Serial.print(sec); + Serial.print(".."); + delay(1000); + } + + // warning for example only, this will initialize empty memory into your vars + // always init flash memory or add some checksum bits + EEPROM.begin( 512 ); + EEPROM.get(0, sett); + Serial.println("Settings loaded"); + + if (digitalRead(SETUP_PIN) == LOW) { + // Button pressed + Serial.println("SETUP"); + + WiFiManager wm; + + sett.s[19] = '\0'; //add null terminator at the end cause overflow + WiFiManagerParameter param_str( "str", "param_string", sett.s, 20); + FloatParameter param_float( "float", "param_float", sett.f); + IntParameter param_int( "int", "param_int", sett.i); + + IPAddress ip(sett.ip); + IPAddressParameter param_ip("ip", "param_ip", ip); + + wm.addParameter( ¶m_str ); + wm.addParameter( ¶m_float ); + wm.addParameter( ¶m_int ); + wm.addParameter( ¶m_ip ); + + //SSID & password parameters already included + wm.startConfigPortal(); + + strncpy(sett.s, param_str.getValue(), 20); + sett.s[19] = '\0'; + sett.f = param_float.getValue(); + sett.i = param_int.getValue(); + + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + + if (param_ip.getValue(ip)) { + sett.ip = ip; + + Serial.print("IP param: "); + Serial.println(ip); + } else { + Serial.println("Incorrect IP"); + } + + EEPROM.put(0, sett); + if (EEPROM.commit()) { + Serial.println("Settings saved"); + } else { + Serial.println("EEPROM error"); + } + } + else { + Serial.println("WORK"); + + //connect to saved SSID + WiFi.begin(); + + //do smth + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + Serial.print("IP param: "); + IPAddress ip(sett.ip); + Serial.println(ip); + } +} + +void loop() { +} diff --git a/firmware/libraries/WiFiManager/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino b/firmware/libraries/WiFiManager/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 0000000..e627b06 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,417 @@ +/** + * This is a kind of unit test for DEV for now + * It contains many of the public methods + * + */ +#include // https://github.com/tzapu/WiFiManager +#include +#include + +#define USEOTA +// enable OTA +#ifdef USEOTA +#include +#include +#endif + +const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; + +unsigned long mtime = 0; + + +WiFiManager wm; + + +// TEST OPTION FLAGS +bool TEST_CP = false; // always start the configportal, even if ap found +int TESP_CP_TIMEOUT = 90; // test cp timeout + +bool TEST_NET = true; // do a network test after connect, (gets ntp time) +bool ALLOWONDEMAND = true; // enable on demand +int ONDDEMANDPIN = 0; // gpio for button +bool WMISBLOCKING = true; // use blocking or non blocking mode, non global params wont work in non blocking + +// char ssid[] = "*************"; // your network SSID (name) +// char pass[] = "********"; // your network password + + +//callbacks + // called after AP mode and config portal has started + // setAPCallback( std::function func ); + // called after webserver has started + // setWebServerCallback( std::function func ); + // called when settings reset have been triggered + // setConfigResetCallback( std::function func ); + // called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) + // setSaveConfigCallback( std::function func ); + // called when saving either params-in-wifi or params page + // setSaveParamsCallback( std::function func ); + // called when saving params-in-wifi or params before anything else happens (eg wifi) + // setPreSaveConfigCallback( std::function func ); + // called just before doing OTA update + // setPreOtaUpdateCallback( std::function func ); + +void saveWifiCallback(){ + Serial.println("[CALLBACK] saveCallback fired"); +} + +//gets called when WiFiManager enters configuration mode +void configModeCallback (WiFiManager *myWiFiManager) { + Serial.println("[CALLBACK] configModeCallback fired"); + // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // Serial.println(WiFi.softAPIP()); + //if you used auto generated SSID, print it + // Serial.println(myWiFiManager->getConfigPortalSSID()); + // + // esp_wifi_set_bandwidth(WIFI_IF_AP, WIFI_BW_HT20); +} + +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); + // wm.stopConfigPortal(); +} + +void bindServerCallback(){ + wm.server->on("/custom",handleRoute); // this is now crashing esp32 for some reason + // wm.server->on("/info",handleRoute); // you can override wm! +} + +void handleRoute(){ + Serial.println("[HTTP] handle route"); + wm.server->send(200, "text/plain", "hello from user code"); +} + +void handlePreOtaUpdateCallback(){ + Update.onProgress([](unsigned int progress, unsigned int total) { + Serial.printf("CUSTOM Progress: %u%%\r", (progress / (total / 100))); + }); +} + +void setup() { + // WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + + // put your setup code here, to run once: + Serial.begin(115200); + // Serial1.begin(115200); + + // Serial.setDebugOutput(true); + + Serial.println("\n Starting"); + // WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability + + Serial.println("Error - TEST"); + Serial.println("Information- - TEST"); + + Serial.println("[ERROR] TEST"); + Serial.println("[INFORMATION] TEST"); + + + wm.setDebugOutput(true); + wm.debugPlatformInfo(); + + //reset settings - for testing + // wm.resetSettings(); + // wm.erase(); + + // setup some parameters + + WiFiManagerParameter custom_html("

This Is Custom HTML

"); // only custom html + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); + WiFiManagerParameter custom_token("api_token", "api token", "", 16); + WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces + WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask) + WiFiManagerParameter custom_input_type("input_pwd", "input pass", "", 15,"type='password'"); // custom input attrs (ip mask) + + const char _customHtml_checkbox[] = "type=\"checkbox\""; + WiFiManagerParameter custom_checkbox("my_checkbox", "My Checkbox", "T", 2, _customHtml_checkbox,WFM_LABEL_AFTER); + + const char *bufferStr = R"( + +
+

Select Choice

+ +
+ +
+ + +
+ + + )"; + + WiFiManagerParameter custom_html_inputs(bufferStr); + + // callbacks + wm.setAPCallback(configModeCallback); + wm.setWebServerCallback(bindServerCallback); + wm.setSaveConfigCallback(saveWifiCallback); + wm.setSaveParamsCallback(saveParamCallback); + wm.setPreOtaUpdateCallback(handlePreOtaUpdateCallback); + + // add all your parameters here + wm.addParameter(&custom_html); + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_token); + wm.addParameter(&custom_tokenb); + wm.addParameter(&custom_ipaddress); + wm.addParameter(&custom_checkbox); + wm.addParameter(&custom_input_type); + + wm.addParameter(&custom_html_inputs); + + // set values later if you want + custom_html.setValue("test",4); + custom_token.setValue("test",4); + + // const char* icon = " + // "; + + + // set custom html head content , inside + // examples of favicon, or meta tags etc + // const char* headhtml = ""; + // const char* headhtml = ""; + // wm.setCustomHeadElement(headhtml); + + // set custom html menu content , inside menu item "custom", see setMenu() + const char* menuhtml = "

\n"; + wm.setCustomMenuHTML(menuhtml); + + // invert theme, dark + wm.setDarkMode(true); + + // show scan RSSI as percentage, instead of signal stength graphic + // wm.setScanDispPerc(true); + +/* + Set cutom menu via menu[] or vector + const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + wm.setMenu(menu,9); // custom menu array must provide length +*/ + + std::vector menu = {"wifi","wifinoscan","info","param","custom","close","sep","erase","update","restart","exit"}; + wm.setMenu(menu); // custom menu, pass vector + + // wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu! + + // set STA static ip + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setShowStaticFields(false); + // wm.setShowDnsFields(false); + + // set AP static ip + // wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + + // set country + // setting wifi country seems to improve OSX soft ap connectivity, + // may help others as well, default is CN which has different channels + + wm.setCountry("US"); // crashing on esp32 2.0 + + // set Hostname + + // wm.setHostname(("WM_"+wm.getDefaultAPName()).c_str()); + // wm.setHostname("WM_RANDO_1234"); + + // set custom channel + // wm.setWiFiAPChannel(13); + + // set AP hidden + // wm.setAPHidden(true); + + // show password publicly in form + // wm.setShowPassword(true); + + // sets wether wm configportal is a blocking loop(legacy) or not, use wm.process() in loop if false + // wm.setConfigPortalBlocking(false); + + if(!WMISBLOCKING){ + wm.setConfigPortalBlocking(false); + } + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep in seconds + wm.setConfigPortalTimeout(120); + + // set min quality to show in web list, default 8% + // wm.setMinimumSignalQuality(50); + + // set connection timeout + // wm.setConnectTimeout(20); + + // set wifi connect retries + // wm.setConnectRetries(2); + + // connect after portal save toggle + // wm.setSaveConnect(false); // do not connect, only save + + // show static ip fields + // wm.setShowStaticFields(true); + + // wm.startConfigPortal("AutoConnectAP", "password"); + + // This is sometimes necessary, it is still unknown when and why this is needed but it may solve some race condition or bug in esp SDK/lib + // wm.setCleanConnect(true); // disconnect before connect, clean connect + + wm.setBreakAfterConfig(true); // needed to use saveWifiCallback + + // set custom webserver port, automatic captive portal does not work with custom ports! + // wm.setHttpPort(8080); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + + // use autoconnect, but prevent configportal from auto starting + // wm.setEnableConfigPortal(false); + + wifiInfo(); + + // to preload autoconnect with credentials + // wm.preloadWiFi("ssid","password"); + + if(!wm.autoConnect("WM_AutoConnectAP","12345678")) { + Serial.println("failed to connect and hit timeout"); + } + else if(TEST_CP) { + // start configportal always + delay(1000); + Serial.println("TEST_CP ENABLED"); + wm.setConfigPortalTimeout(TESP_CP_TIMEOUT); + wm.startConfigPortal("WM_ConnectAP","12345678"); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + + wifiInfo(); + pinMode(ONDDEMANDPIN, INPUT_PULLUP); + + #ifdef USEOTA + ArduinoOTA.begin(); + #endif + +} + +void wifiInfo(){ + // can contain gargbage on esp32 if wifi is not ready yet + Serial.println("[WIFI] WIFI INFO DEBUG"); + // WiFi.printDiag(Serial); + Serial.println("[WIFI] SAVED: " + (String)(wm.getWiFiIsSaved() ? "YES" : "NO")); + Serial.println("[WIFI] SSID: " + (String)wm.getWiFiSSID()); + Serial.println("[WIFI] PASS: " + (String)wm.getWiFiPass()); + Serial.println("[WIFI] HOSTNAME: " + (String)WiFi.getHostname()); +} + +void loop() { + + if(!WMISBLOCKING){ + wm.process(); + } + + #ifdef USEOTA + ArduinoOTA.handle(); + #endif + // is configuration portal requested? + if (ALLOWONDEMAND && digitalRead(ONDDEMANDPIN) == LOW ) { + delay(100); + if ( digitalRead(ONDDEMANDPIN) == LOW ){ + Serial.println("BUTTON PRESSED"); + + // button reset/reboot + // wm.resetSettings(); + // wm.reboot(); + // delay(200); + // return; + + wm.setConfigPortalTimeout(140); + wm.setParamsPage(false); // move params to seperate page, not wifi, do not combine with setmenu! + + // disable captive portal redirection + // wm.setCaptivePortalEnable(false); + + if (!wm.startConfigPortal("OnDemandAP","12345678")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + } + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + getTime(); + } + } + + // every 10 seconds + if(millis()-mtime > 10000 ){ + if(WiFi.status() == WL_CONNECTED){ + getTime(); + } + else Serial.println("No Wifi"); + mtime = millis(); + } + // put your main code here, to run repeatedly: + delay(100); +} + +void getTime() { + int tz = -5; + int dst = 0; + time_t now = time(nullptr); + unsigned timeout = 5000; // try for timeout + unsigned start = millis(); + configTime(tz * 3600, dst * 3600, "pool.ntp.org", "time.nist.gov"); + Serial.print("Waiting for NTP time sync: "); + while (now < 8 * 3600 * 2 ) { // what is this ? + delay(100); + Serial.print("."); + now = time(nullptr); + if((millis() - start) > timeout){ + Serial.println("\n[ERROR] Failed to get NTP time."); + return; + } + } + Serial.println(""); + struct tm timeinfo; + gmtime_r(&now, &timeinfo); // @NOTE doesnt work in esp2.3.0 + Serial.print("Current time: "); + Serial.print(asctime(&timeinfo)); +} + +void debugchipid(){ + // WiFi.mode(WIFI_STA); + // WiFi.printDiag(Serial); + // Serial.println(modes[WiFi.getMode()]); + + // ESP.eraseConfig(); + // wm.resetSettings(); + // wm.erase(true); + WiFi.mode(WIFI_AP); + // WiFi.softAP(); + WiFi.enableAP(true); + delay(500); + // esp_wifi_start(); + delay(1000); + WiFi.printDiag(Serial); + delay(60000); + ESP.restart(); + + // AP esp_267751 + // 507726A4AE30 + // ESP32 Chip ID = 507726A4AE30 +} diff --git a/firmware/libraries/WiFiManager/examples/Unique/cb/AnonymousCB.ino b/firmware/libraries/WiFiManager/examples/Unique/cb/AnonymousCB.ino new file mode 100644 index 0000000..f34d80f --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Unique/cb/AnonymousCB.ino @@ -0,0 +1,26 @@ +#include // https://github.com/tzapu/WiFiManager + +bool _enteredConfigMode = false; + +void setup(){ + Serial.begin(115200); + WiFiManager wifiManager; + + // wifiManager.setAPCallback([this](WiFiManager* wifiManager) { + wifiManager.setAPCallback([&](WiFiManager* wifiManager) { + Serial.printf("Entered config mode:ip=%s, ssid='%s'\n", + WiFi.softAPIP().toString().c_str(), + wifiManager->getConfigPortalSSID().c_str()); + _enteredConfigMode = true; + }); + wifiManager.resetSettings(); + if (!wifiManager.autoConnect()) { + Serial.printf("*** Failed to connect and hit timeout\n"); + ESP.restart(); + delay(1000); + } +} + +void loop(){ + +} diff --git a/firmware/libraries/WiFiManager/extras/WiFiManager.template.html b/firmware/libraries/WiFiManager/extras/WiFiManager.template.html new file mode 100644 index 0000000..d928a8c --- /dev/null +++ b/firmware/libraries/WiFiManager/extras/WiFiManager.template.html @@ -0,0 +1,395 @@ + + + + + + {v} + + + + + + + + + + +
+ + + +

/


+ + + + +

+

+

+

+

+

+

+

+

+

+ + +

/wifi


+ + + + + + + + + + + + + + + + + + + + +


Show Password
+ + +

custom parameter


+
+
+ + +
+ + +
+ + +
+ + +
+ + +

Saving Credentials

Trying to connect ESP to network.
If it fails reconnect to AP to try again
+ + +
Connected to {v}
with IP {i}
+ + +
Not Connected to {v}{r}
+ + +
Not Connected to apname + + +
Authentication Failure + + +
AP not found + + +
Could not Connect + +
+ +
No AP set
+ + +

H4 Color Header P

content
+ + +

H4 Color Header S

content
+ + +

/info


+
+
Chip ID
123456
+
Flash Chip ID
1234556
+
IDE Flash Size
4194304 bytes
+
Real Flash Size
4194304 bytes
+
Empty
+
Soft AP IP
192.168.4.1
+
Soft AP MAC
00:00:00:00:00:00
+
Station MAC
00:00:00:00:00:00
+
+ + +

Available Pages


+ + + + + + + + + + + + + + + + + + + + +
PageFunction
/Menu page.
/wifiShow WiFi scan results and enter WiFi configuration.(/0wifi noscan)
/wifisaveSave WiFi configuration information and configure device. Needs variables supplied.
/closeClose the configuration server and configuration WiFi network.
/infoInformation page
/closeClose the captiveportal popup,configportal will remain active
/exitExit Config Portal, configportal will close
/restartReboot the device
/eraseErase WiFi configuration and reboot Device. Device will not reconnect to a network until new WiFi configuration data is entered.
+

About


+ Version v1.x.x-xxxxx
+ Build_date
+ Build_file
+ Arduino_version
+

Github https://github.com/tzapu/WiFiManager + + +

Form UPLOAD
+

+ + + * Upload may not function inside captive portal, Open in browser - http://192.168.4.1 + + + + +



+
+ +
+ +
+ + + + + +
+ + +

Select Choice

+ +
+ +
+ + +
+ + + +
+ + + + +
+ + + diff --git a/firmware/libraries/WiFiManager/extras/parse.js b/firmware/libraries/WiFiManager/extras/parse.js new file mode 100644 index 0000000..97a3e38 --- /dev/null +++ b/firmware/libraries/WiFiManager/extras/parse.js @@ -0,0 +1,60 @@ +'use strict'; + +const fs = require('fs'); + +console.log('starting'); + +const inFile = 'WiFiManager.template.html'; +const outFile = 'template.h'; + +const defineRegEx = //gm; +console.log('parsing', inFile); + +fs.readFile(inFile, 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + //console.log(data); + + let defines = data.match(defineRegEx); + + //console.log(defines); + var stream = fs.createWriteStream(outFile); + stream.once('open', function(fd) { + for (const i in defines) { + + const start = defines[i]; + const end = start.replace(' + + + + diff --git a/firmware/libraries/WiFiManager/keywords.txt b/firmware/libraries/WiFiManager/keywords.txt new file mode 100644 index 0000000..7159e74 --- /dev/null +++ b/firmware/libraries/WiFiManager/keywords.txt @@ -0,0 +1,39 @@ +####################################### +# Syntax Coloring Map For WifiManager +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +WiFiManager KEYWORD1 +WiFiManagerParameter KEYWORD1 + + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +autoConnect KEYWORD2 +getSSID KEYWORD2 +getPassword KEYWORD2 +getConfigPortalSSID KEYWORD2 +resetSettings KEYWORD2 +setConfigPortalTimeout KEYWORD2 +setConnectTimeout KEYWORD2 +setDebugOutput KEYWORD2 +setMinimumSignalQuality KEYWORD2 +setAPStaticIPConfig KEYWORD2 +setSTAStaticIPConfig KEYWORD2 +setAPCallback KEYWORD2 +setSaveConfigCallback KEYWORD2 +addParameter KEYWORD2 +getID KEYWORD2 +getValue KEYWORD2 +getPlaceholder KEYWORD2 +getValueLength KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +# LITERAL1 diff --git a/firmware/libraries/WiFiManager/library.json b/firmware/libraries/WiFiManager/library.json new file mode 100644 index 0000000..e77262e --- /dev/null +++ b/firmware/libraries/WiFiManager/library.json @@ -0,0 +1,29 @@ +{ + "name": "WiFiManager", + "version": "2.0.12-beta", + "keywords": "wifi,wi-fi,esp,esp8266,esp32,espressif8266,espressif32,nodemcu,wemos,arduino", + "description": "WiFi Configuration manager with web configuration portal for ESP boards", + "authors": + [ + { + "name": "tzapu", + "url": "https://github.com/tzapu" + }, + { + "name": "tablatronix", + "url": "https://github.com/tablatronix", + "maintainer": true + } + ], + "repository": + { + "type": "git", + "url": "https://github.com/tzapu/WiFiManager.git" + }, + "frameworks": "arduino", + "platforms": + [ + "espressif8266", + "espressif32" + ] +} \ No newline at end of file diff --git a/firmware/libraries/WiFiManager/library.properties b/firmware/libraries/WiFiManager/library.properties new file mode 100644 index 0000000..db9faad --- /dev/null +++ b/firmware/libraries/WiFiManager/library.properties @@ -0,0 +1,9 @@ +name=WiFiManager +version=2.0.12-beta +author=tzapu +maintainer=tablatronix +sentence=WiFi Configuration manager with web configuration portal for Espressif ESPx boards, by tzapu +paragraph=Library for configuring ESP8266/ESP32 modules WiFi credentials and custom parameters at runtime with captive portal. +category=Communication +url=https://github.com/tzapu/WiFiManager.git +architectures=esp8266,esp32 diff --git a/firmware/libraries/WiFiManager/strings_en.h b/firmware/libraries/WiFiManager/strings_en.h new file mode 100644 index 0000000..386571d --- /dev/null +++ b/firmware/libraries/WiFiManager/strings_en.h @@ -0,0 +1,501 @@ +/** + * strings_en.h + * engligh strings for + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + +#ifndef _WM_STRINGS_H_ +#define _WM_STRINGS_H_ + + +#ifndef WIFI_MANAGER_OVERRIDE_STRINGS +// !!! ABOVE WILL NOT WORK if you define in your sketch, must be build flag, if anyone one knows how to order includes to be able to do this it would be neat.. I have seen it done.. + +const char WM_VERSION_STR[] PROGMEM = "v2.0.12-beta"; + +const char HTTP_HEAD_START[] PROGMEM = "" +"" +"" +"" +"" +"{v}"; + +const char HTTP_SCRIPT[] PROGMEM = ""; // @todo add button states, disable on click , show ack , spinner etc + +const char HTTP_HEAD_END[] PROGMEM = "
"; // {c} = _bodyclass +// example of embedded logo, base64 encoded inline, No styling here +// const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; +const char HTTP_ROOT_MAIN[] PROGMEM = "

{t}

{v}

"; + +const char * const HTTP_PORTAL_MENU[] PROGMEM = { +"

\n", // MENU_WIFI +"

\n", // MENU_WIFINOSCAN +"

\n", // MENU_INFO +"

\n",//MENU_PARAM +"

\n", // MENU_CLOSE +"

\n",// MENU_RESTART +"

\n", // MENU_EXIT +"

\n", // MENU_ERASE +"

\n",// MENU_UPDATE +"

" // MENU_SEP +}; + +// const char HTTP_PORTAL_OPTIONS[] PROGMEM = strcat(HTTP_PORTAL_MENU[0] , HTTP_PORTAL_MENU[3] , HTTP_PORTAL_MENU[7]); +const char HTTP_PORTAL_OPTIONS[] PROGMEM = ""; +const char HTTP_ITEM_QI[] PROGMEM = ""; // rssi icons +const char HTTP_ITEM_QP[] PROGMEM = "
{r}%
"; // rssi percentage {h} = hidden showperc pref +const char HTTP_ITEM[] PROGMEM = "
{v}{qi}{qp}
"; // {q} = HTTP_ITEM_QI, {r} = HTTP_ITEM_QP +// const char HTTP_ITEM[] PROGMEM = "
{v} {R} {r}% {q} {e}
"; // test all tokens + +const char HTTP_FORM_START[] PROGMEM = "
"; +const char HTTP_FORM_WIFI[] PROGMEM = "
Show Password"; +const char HTTP_FORM_WIFI_END[] PROGMEM = ""; +const char HTTP_FORM_STATIC_HEAD[] PROGMEM = "

"; +const char HTTP_FORM_END[] PROGMEM = "

"; +const char HTTP_FORM_LABEL[] PROGMEM = ""; +const char HTTP_FORM_PARAM_HEAD[] PROGMEM = "

"; +const char HTTP_FORM_PARAM[] PROGMEM = "
\n"; // do not remove newline! + +const char HTTP_SCAN_LINK[] PROGMEM = "
"; +const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; +const char HTTP_PARAMSAVED[] PROGMEM = "
Saved
"; +const char HTTP_END[] PROGMEM = "
"; +const char HTTP_ERASEBTN[] PROGMEM = "
"; +const char HTTP_UPDATEBTN[] PROGMEM = "
"; +const char HTTP_BACKBTN[] PROGMEM = "

"; + +const char HTTP_STATUS_ON[] PROGMEM = "
Connected to {v}
with IP {i}
"; +const char HTTP_STATUS_OFF[] PROGMEM = "
Not Connected to {v}{r}
"; // {c=class} {v=ssid} {r=status_off} +const char HTTP_STATUS_OFFPW[] PROGMEM = "
Authentication Failure"; // STATION_WRONG_PASSWORD, no eps32 +const char HTTP_STATUS_OFFNOAP[] PROGMEM = "
AP not found"; // WL_NO_SSID_AVAIL +const char HTTP_STATUS_OFFFAIL[] PROGMEM = "
Could not Connect"; // WL_CONNECT_FAILED +const char HTTP_STATUS_NONE[] PROGMEM = "
No AP set
"; +const char HTTP_BR[] PROGMEM = "
"; + +const char HTTP_STYLE[] PROGMEM = ""; + +#ifndef WM_NOHELP +const char HTTP_HELP[] PROGMEM = + "

Available Pages


" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "
PageFunction
/Menu page.
/wifiShow WiFi scan results and enter WiFi configuration.(/0wifi noscan)
/wifisaveSave WiFi configuration information and configure device. Needs variables supplied.
/paramParameter page
/infoInformation page
/uOTA Update
/closeClose the captiveportal popup,configportal will remain active
/exitExit Config Portal, configportal will close
/restartReboot the device
/eraseErase WiFi configuration and reboot Device. Device will not reconnect to a network until new WiFi configuration data is entered.
" + "

Github https://github.com/tzapu/WiFiManager."; +#else +const char HTTP_HELP[] PROGMEM = ""; +#endif + +const char HTTP_UPDATE[] PROGMEM = "Upload New Firmware

* May not function inside captive portal, Open in browser http://192.168.4.1"; +const char HTTP_UPDATE_FAIL[] PROGMEM = "
Update Failed!
Reboot device and try again
"; +const char HTTP_UPDATE_SUCCESS[] PROGMEM = "
Update Successful.
Device Rebooting now...
"; + +#ifdef WM_JSTEST +const char HTTP_JS[] PROGMEM = +""; +#endif + +// Info html +// @todo remove html elements from progmem, repetetive strings +#ifdef ESP32 + const char HTTP_INFO_esphead[] PROGMEM = "

esp32


"; + const char HTTP_INFO_chiprev[] PROGMEM = "
Chip Rev
{1}
"; + const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
CPU0: {1}
CPU1: {2}
"; + const char HTTP_INFO_aphost[] PROGMEM = "
Access Point Hostname
{1}
"; + const char HTTP_INFO_psrsize[] PROGMEM = "
PSRAM Size
{1} bytes
"; + const char HTTP_INFO_temp[] PROGMEM = "
Temperature
{1} C° / {2} F°
Hall
{3}
"; +#else + const char HTTP_INFO_esphead[] PROGMEM = "

esp8266


"; + const char HTTP_INFO_fchipid[] PROGMEM = "
Flash Chip ID
{1}
"; + const char HTTP_INFO_corever[] PROGMEM = "
Core Version
{1}
"; + const char HTTP_INFO_bootver[] PROGMEM = "
Boot Version
{1}
"; + const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
{1}
"; + const char HTTP_INFO_flashsize[] PROGMEM = "
Real Flash Size
{1} bytes
"; +#endif + +const char HTTP_INFO_memsmeter[] PROGMEM = "
"; +const char HTTP_INFO_memsketch[] PROGMEM = "
Memory - Sketch Size
Used / Total bytes
{1} / {2}"; +const char HTTP_INFO_freeheap[] PROGMEM = "
Memory - Free Heap
{1} bytes available
"; +const char HTTP_INFO_wifihead[] PROGMEM = "

WiFi


"; +const char HTTP_INFO_uptime[] PROGMEM = "
Uptime
{1} Mins {2} Secs
"; +const char HTTP_INFO_chipid[] PROGMEM = "
Chip ID
{1}
"; +const char HTTP_INFO_idesize[] PROGMEM = "
Flash Size
{1} bytes
"; +const char HTTP_INFO_sdkver[] PROGMEM = "
SDK Version
{1}
"; +const char HTTP_INFO_cpufreq[] PROGMEM = "
CPU Frequency
{1}MHz
"; +const char HTTP_INFO_apip[] PROGMEM = "
Access Point IP
{1}
"; +const char HTTP_INFO_apmac[] PROGMEM = "
Access Point MAC
{1}
"; +const char HTTP_INFO_apssid[] PROGMEM = "
Access Point SSID
{1}
"; +const char HTTP_INFO_apbssid[] PROGMEM = "
BSSID
{1}
"; +const char HTTP_INFO_stassid[] PROGMEM = "
Station SSID
{1}
"; +const char HTTP_INFO_staip[] PROGMEM = "
Station IP
{1}
"; +const char HTTP_INFO_stagw[] PROGMEM = "
Station Gateway
{1}
"; +const char HTTP_INFO_stasub[] PROGMEM = "
Station Subnet
{1}
"; +const char HTTP_INFO_dnss[] PROGMEM = "
DNS Server
{1}
"; +const char HTTP_INFO_host[] PROGMEM = "
Hostname
{1}
"; +const char HTTP_INFO_stamac[] PROGMEM = "
Station MAC
{1}
"; +const char HTTP_INFO_conx[] PROGMEM = "
Connected
{1}
"; +const char HTTP_INFO_autoconx[] PROGMEM = "
Autoconnect
{1}
"; + +const char HTTP_INFO_aboutver[] PROGMEM = "
WiFiManager
{1}
"; +const char HTTP_INFO_aboutarduino[] PROGMEM = "
Arduino
{1}
"; +const char HTTP_INFO_aboutsdk[] PROGMEM = "
ESP-SDK/IDF
{1}
"; +const char HTTP_INFO_aboutdate[] PROGMEM = "
Build Date
{1}
"; + +const char S_brand[] PROGMEM = "WiFiManager"; +const char S_debugPrefix[] PROGMEM = "*wm:"; +const char S_y[] PROGMEM = "Yes"; +const char S_n[] PROGMEM = "No"; +const char S_enable[] PROGMEM = "Enabled"; +const char S_disable[] PROGMEM = "Disabled"; +const char S_GET[] PROGMEM = "GET"; +const char S_POST[] PROGMEM = "POST"; +const char S_NA[] PROGMEM = "Unknown"; +const char S_passph[] PROGMEM = "********"; +const char S_titlewifisaved[] PROGMEM = "Credentials Saved"; +const char S_titlewifisettings[] PROGMEM = "Settings Saved"; +const char S_titlewifi[] PROGMEM = "Config ESP"; +const char S_titleinfo[] PROGMEM = "Info"; +const char S_titleparam[] PROGMEM = "Setup"; +const char S_titleparamsaved[] PROGMEM = "Setup Saved"; +const char S_titleexit[] PROGMEM = "Exit"; +const char S_titlereset[] PROGMEM = "Reset"; +const char S_titleerase[] PROGMEM = "Erase"; +const char S_titleclose[] PROGMEM = "Close"; +const char S_options[] PROGMEM = "options"; +const char S_nonetworks[] PROGMEM = "No networks found. Refresh to scan again."; +const char S_staticip[] PROGMEM = "Static IP"; +const char S_staticgw[] PROGMEM = "Static Gateway"; +const char S_staticdns[] PROGMEM = "Static DNS"; +const char S_subnet[] PROGMEM = "Subnet"; +const char S_exiting[] PROGMEM = "Exiting"; +const char S_resetting[] PROGMEM = "Module will reset in a few seconds."; +const char S_closing[] PROGMEM = "You can close the page, portal will continue to run"; +const char S_error[] PROGMEM = "An Error Occured"; +const char S_notfound[] PROGMEM = "File Not Found\n\n"; +const char S_uri[] PROGMEM = "URI: "; +const char S_method[] PROGMEM = "\nMethod: "; +const char S_args[] PROGMEM = "\nArguments: "; +const char S_parampre[] PROGMEM = "param_"; + +// debug strings +const char D_HR[] PROGMEM = "--------------------"; + +// END WIFI_MANAGER_OVERRIDE_STRINGS +#endif + +// ----------------------------------------------------------------------------------------------- +// DO NOT EDIT BELOW THIS LINE + +const uint8_t _nummenutokens = 11; +const char * const _menutokens[_nummenutokens] PROGMEM = { + "wifi", + "wifinoscan", + "info", + "param", + "close", + "restart", + "exit", + "erase", + "update", + "sep", + "custom" +}; + +const char R_root[] PROGMEM = "/"; +const char R_wifi[] PROGMEM = "/wifi"; +const char R_wifinoscan[] PROGMEM = "/0wifi"; +const char R_wifisave[] PROGMEM = "/wifisave"; +const char R_info[] PROGMEM = "/info"; +const char R_param[] PROGMEM = "/param"; +const char R_paramsave[] PROGMEM = "/paramsave"; +const char R_restart[] PROGMEM = "/restart"; +const char R_exit[] PROGMEM = "/exit"; +const char R_close[] PROGMEM = "/close"; +const char R_erase[] PROGMEM = "/erase"; +const char R_status[] PROGMEM = "/status"; +const char R_update[] PROGMEM = "/update"; +const char R_updatedone[] PROGMEM = "/u"; + + +//Strings +const char S_ip[] PROGMEM = "ip"; +const char S_gw[] PROGMEM = "gw"; +const char S_sn[] PROGMEM = "sn"; +const char S_dns[] PROGMEM = "dns"; + +// softap ssid default prefix +#ifdef ESP8266 + const char S_ssidpre[] PROGMEM = "ESP"; +#elif defined(ESP32) + const char S_ssidpre[] PROGMEM = "ESP32"; +#else + const char S_ssidpre[] PROGMEM = "WM"; +#endif + +//Tokens +//@todo consolidate and reduce +const char T_ss[] PROGMEM = "{"; // token start sentinel +const char T_es[] PROGMEM = "}"; // token end sentinel +const char T_1[] PROGMEM = "{1}"; // @token 1 +const char T_2[] PROGMEM = "{2}"; // @token 2 +const char T_3[] PROGMEM = "{3}"; // @token 2 +const char T_v[] PROGMEM = "{v}"; // @token v +const char T_V[] PROGMEM = "{V}"; // @token v +const char T_I[] PROGMEM = "{I}"; // @token I +const char T_i[] PROGMEM = "{i}"; // @token i +const char T_n[] PROGMEM = "{n}"; // @token n +const char T_p[] PROGMEM = "{p}"; // @token p +const char T_t[] PROGMEM = "{t}"; // @token t +const char T_l[] PROGMEM = "{l}"; // @token l +const char T_c[] PROGMEM = "{c}"; // @token c +const char T_e[] PROGMEM = "{e}"; // @token e +const char T_q[] PROGMEM = "{q}"; // @token q +const char T_r[] PROGMEM = "{r}"; // @token r +const char T_R[] PROGMEM = "{R}"; // @token R +const char T_h[] PROGMEM = "{h}"; // @token h + +// http +const char HTTP_HEAD_CL[] PROGMEM = "Content-Length"; +const char HTTP_HEAD_CT[] PROGMEM = "text/html"; +const char HTTP_HEAD_CT2[] PROGMEM = "text/plain"; +const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; +const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; + +const char * const WIFI_STA_STATUS[] PROGMEM +{ + "WL_IDLE_STATUS", // 0 STATION_IDLE + "WL_NO_SSID_AVAIL", // 1 STATION_NO_AP_FOUND + "WL_SCAN_COMPLETED", // 2 + "WL_CONNECTED", // 3 STATION_GOT_IP + "WL_CONNECT_FAILED", // 4 STATION_CONNECT_FAIL, STATION_WRONG_PASSWORD(NI) + "WL_CONNECTION_LOST", // 5 + "WL_DISCONNECTED", // 6 + "WL_STATION_WRONG_PASSWORD" // 7 KLUDGE +}; + +#ifdef ESP32 +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "OPEN", + "WEP", + "WPA_PSK", + "WPA2_PSK", + "WPA_WPA2_PSK", + "WPA2_ENTERPRISE", + "MAX" +}; +#elif defined(ESP8266) +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "", + "", + "WPA_PSK", // 2 ENC_TYPE_TKIP + "", + "WPA2_PSK", // 4 ENC_TYPE_CCMP + "WEP", // 5 ENC_TYPE_WEP + "", + "OPEN", //7 ENC_TYPE_NONE + "WPA_WPA2_PSK", // 8 ENC_TYPE_AUTO +}; +#endif + +const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; + + +#ifdef ESP32 +// as 2.5.2 +// typedef struct { +// char cc[3]; /**< country code string */ +// uint8_t schan; /**< start channel */ +// uint8_t nchan; /**< total channel number */ +// int8_t max_tx_power; /**< This field is used for getting WiFi maximum transmitting power, call esp_wifi_set_max_tx_power to set the maximum transmitting power. */ +// wifi_country_policy_t policy; /**< country policy */ +// } wifi_country_t; +const wifi_country_t WM_COUNTRY_US{"US",1,11,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +#elif defined(ESP8266) && !defined(WM_NOCOUNTRY) +// typedef struct { +// char cc[3]; /**< country code string */ +// uint8_t schan; /**< start channel */ +// uint8_t nchan; /**< total channel number */ +// uint8_t policy; /**< country policy */ +// } wifi_country_t; +const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; +#endif + + +/* +* ESP32 WiFi Events + +0 SYSTEM_EVENT_WIFI_READY < ESP32 WiFi ready +1 SYSTEM_EVENT_SCAN_DONE < ESP32 finish scanning AP +2 SYSTEM_EVENT_STA_START < ESP32 station start +3 SYSTEM_EVENT_STA_STOP < ESP32 station stop +4 SYSTEM_EVENT_STA_CONNECTED < ESP32 station connected to AP +5 SYSTEM_EVENT_STA_DISCONNECTED < ESP32 station disconnected from AP +6 SYSTEM_EVENT_STA_AUTHMODE_CHANGE < the auth mode of AP connected by ESP32 station changed +7 SYSTEM_EVENT_STA_GOT_IP < ESP32 station got IP from connected AP +8 SYSTEM_EVENT_STA_LOST_IP < ESP32 station lost IP and the IP is reset to 0 +9 SYSTEM_EVENT_STA_WPS_ER_SUCCESS < ESP32 station wps succeeds in enrollee mode +10 SYSTEM_EVENT_STA_WPS_ER_FAILED < ESP32 station wps fails in enrollee mode +11 SYSTEM_EVENT_STA_WPS_ER_TIMEOUT < ESP32 station wps timeout in enrollee mode +12 SYSTEM_EVENT_STA_WPS_ER_PIN < ESP32 station wps pin code in enrollee mode +13 SYSTEM_EVENT_AP_START < ESP32 soft-AP start +14 SYSTEM_EVENT_AP_STOP < ESP32 soft-AP stop +15 SYSTEM_EVENT_AP_STACONNECTED < a station connected to ESP32 soft-AP +16 SYSTEM_EVENT_AP_STADISCONNECTED < a station disconnected from ESP32 soft-AP +17 SYSTEM_EVENT_AP_STAIPASSIGNED < ESP32 soft-AP assign an IP to a connected station +18 SYSTEM_EVENT_AP_PROBEREQRECVED < Receive probe request packet in soft-AP interface +19 SYSTEM_EVENT_GOT_IP6 < ESP32 station or ap or ethernet interface v6IP addr is preferred +20 SYSTEM_EVENT_ETH_START < ESP32 ethernet start +21 SYSTEM_EVENT_ETH_STOP < ESP32 ethernet stop +22 SYSTEM_EVENT_ETH_CONNECTED < ESP32 ethernet phy link up +23 SYSTEM_EVENT_ETH_DISCONNECTED < ESP32 ethernet phy link down +24 SYSTEM_EVENT_ETH_GOT_IP < ESP32 ethernet got IP from connected AP +25 SYSTEM_EVENT_MAX + + +typedef enum { + ARDUINO_EVENT_WIFI_READY = 0, + ARDUINO_EVENT_WIFI_SCAN_DONE, + ARDUINO_EVENT_WIFI_STA_START, + ARDUINO_EVENT_WIFI_STA_STOP, + ARDUINO_EVENT_WIFI_STA_CONNECTED, + ARDUINO_EVENT_WIFI_STA_DISCONNECTED, + ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE, + ARDUINO_EVENT_WIFI_STA_GOT_IP, + ARDUINO_EVENT_WIFI_STA_GOT_IP6, + ARDUINO_EVENT_WIFI_STA_LOST_IP, + ARDUINO_EVENT_WIFI_AP_START, + ARDUINO_EVENT_WIFI_AP_STOP, + ARDUINO_EVENT_WIFI_AP_STACONNECTED, + ARDUINO_EVENT_WIFI_AP_STADISCONNECTED, + ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED, + ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED, + ARDUINO_EVENT_WIFI_AP_GOT_IP6, + ARDUINO_EVENT_WIFI_FTM_REPORT, + ARDUINO_EVENT_ETH_START, + ARDUINO_EVENT_ETH_STOP, + ARDUINO_EVENT_ETH_CONNECTED, + ARDUINO_EVENT_ETH_DISCONNECTED, + ARDUINO_EVENT_ETH_GOT_IP, + ARDUINO_EVENT_ETH_GOT_IP6, + ARDUINO_EVENT_WPS_ER_SUCCESS, + ARDUINO_EVENT_WPS_ER_FAILED, + ARDUINO_EVENT_WPS_ER_TIMEOUT, + ARDUINO_EVENT_WPS_ER_PIN, + ARDUINO_EVENT_WPS_ER_PBC_OVERLAP, + ARDUINO_EVENT_SC_SCAN_DONE, + ARDUINO_EVENT_SC_FOUND_CHANNEL, + ARDUINO_EVENT_SC_GOT_SSID_PSWD, + ARDUINO_EVENT_SC_SEND_ACK_DONE, + ARDUINO_EVENT_PROV_INIT, + ARDUINO_EVENT_PROV_DEINIT, + ARDUINO_EVENT_PROV_START, + ARDUINO_EVENT_PROV_END, + ARDUINO_EVENT_PROV_CRED_RECV, + ARDUINO_EVENT_PROV_CRED_FAIL, + ARDUINO_EVENT_PROV_CRED_SUCCESS, + ARDUINO_EVENT_MAX +} arduino_event_id_t; + +typedef union { + wifi_event_sta_scan_done_t wifi_scan_done; + wifi_event_sta_authmode_change_t wifi_sta_authmode_change; + wifi_event_sta_connected_t wifi_sta_connected; + wifi_event_sta_disconnected_t wifi_sta_disconnected; + wifi_event_sta_wps_er_pin_t wps_er_pin; + wifi_event_sta_wps_fail_reason_t wps_fail_reason; + wifi_event_ap_probe_req_rx_t wifi_ap_probereqrecved; + wifi_event_ap_staconnected_t wifi_ap_staconnected; + wifi_event_ap_stadisconnected_t wifi_ap_stadisconnected; + wifi_event_ftm_report_t wifi_ftm_report; + ip_event_ap_staipassigned_t wifi_ap_staipassigned; + ip_event_got_ip_t got_ip; + ip_event_got_ip6_t got_ip6; + smartconfig_event_got_ssid_pswd_t sc_got_ssid_pswd; + esp_eth_handle_t eth_connected; + wifi_sta_config_t prov_cred_recv; + wifi_prov_sta_fail_reason_t prov_fail_reason; +} arduino_event_info_t; + +*/ +#endif diff --git a/firmware/libraries/WiFiManager/travis/common.sh b/firmware/libraries/WiFiManager/travis/common.sh new file mode 100644 index 0000000..4b3e655 --- /dev/null +++ b/firmware/libraries/WiFiManager/travis/common.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +function build_examples() +{ + excludes=("$@") + # track the exit code for this platform + local exit_code=0 + # loop through results and add them to the array + examples=($(find $PWD/examples/ -name "*.pde" -o -name "*.ino")) + + # get the last example in the array + local last="${examples[@]:(-1)}" + + # loop through example sketches + for example in "${examples[@]}"; do + + # store the full path to the example's sketch directory + local example_dir=$(dirname $example) + + # store the filename for the example without the path + local example_file=$(basename $example) + + # skip files listed as excludes + for exclude in "${excludes[@]}"; do + if [ "${example_file}" == "${exclude}" ] ; then + echo ">>>>>>>>>>>>>>>>>>>>>>>> Skipping ${example_file} <<<<<<<<<<<<<<<<<<<<<<<<<<" + continue 2 + fi + done + + echo "$example_file: " + local sketch="$example_dir/$example_file" + echo "$sketch" + #arduino -v --verbose-build --verify $sketch + + # verify the example, and save stdout & stderr to a variable + # we have to avoid reading the exit code of local: + # "when declaring a local variable in a function, the local acts as a command in its own right" + local build_stdout + build_stdout=$(arduino --verify $sketch 2>&1) + + # echo output if the build failed + if [ $? -ne 0 ]; then + # heavy X + echo -e "\xe2\x9c\x96" + echo -e "----------------------------- DEBUG OUTPUT -----------------------------\n" + echo "$build_stdout" + echo -e "\n------------------------------------------------------------------------\n" + + # mark as fail + exit_code=1 + + else + # heavy checkmark + echo -e "\xe2\x9c\x93" + fi + done + + return $exit_code +}