diff --git a/.gitignore b/.gitignore index b86a8611d8..fc6d8c40cf 100644 --- a/.gitignore +++ b/.gitignore @@ -75,3 +75,5 @@ nbproject build/macosx/esptool-*-osx.zip build/macosx/dist/osx-xtensa-lx106-elf.tgz +/docs/lib_dump/full +/docs/lib_dump diff --git a/.travis.yml b/.travis.yml index 01f1e10ea6..e16a1898e3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,35 +1,38 @@ -sudo: true +sudo: false + language: java os: - linux - - osx + +addons: + apt: + packages: + - ant jdk: - oraclejdk8 script: - - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo apt-get update -qq; fi - - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo apt-get install -qq ant; fi - pushd build - - echo "" | ant dist + - echo "" | ant build - popd -#- bash -x ./generate-appimage - -deploy: - provider: releases - api_key: - secure: eKHcAMuC58JZKRsn1QwbiYE4aL/9dZsybDqqHTo1dUo8x9+3fGed/Dci76ItFFS7SmFfIdl6ej8/Uj0nPK/sIE21blKBe3+L0KAJm0TTq3m0ig1suCmMipCsSW+srWYM0hl58+OKagM4FoHKDjsEnzRDv9Z4xtxyvG+7/XLD1dE= - skip_cleanup: true - file_glob: true - file: - - '$TRAVIS_BUILD_DIR/build/linux/arduino-*.tar.xz' -# - '$TRAVIS_BUILD_DIR/Arduino.AppImage' - on: - tags: true - all_branches: true + - /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16 + - sleep 3 + - export DISPLAY=:1.0 + - export PATH="$PWD/build/linux/work:$PATH" + - which arduino + - source hardware/esp8266com/esp8266/tests/common.sh + - arduino --board esp8266com:esp8266:generic --save-prefs + - build_sketches arduino $PWD/hardware/esp8266com/esp8266 notifications: email: on_success: change on_failure: change + webhooks: + urls: + - secure: "dnSY+KA7NK+KD+Z71copmANDUsyVePrZ0iXvXxmqMEQv+lp3j2Z87G5pHn7j0WNcNZrejJqOdbElJ9Q4QESRaAYxTR7cA6ameJeEKHiFJrQtN/4abvoXb9E1CxpL8aNON/xgnqCk+fycOK3nbWWXlJBodzBm7KN64vrcHO7et+M=" + on_success: change # options: [always|never|change] default: always + on_failure: always # options: [always|never|change] default: always + on_start: false # default: false diff --git a/README.md b/README.md index db43813bb3..c73cd8917c 100644 --- a/README.md +++ b/README.md @@ -1,325 +1,73 @@ -Arduino-compatible IDE with ESP8266 support +Arduino core for ESP8266 WiFi chip =========================================== -[![Linux build status](http://img.shields.io/travis/igrr/Arduino.svg)](https://travis-ci.org/igrr/Arduino) -[![Donate](http://img.shields.io/paypal/donate.png?color=yellow)](https://www.paypal.com/webscr?cmd=_s-xclick&hosted_button_id=4M56YCWV6PX66) +This project brings support for ESP8266 chip to the Arduino environment. It lets you write sketches using familiar Arduino functions and libraries, and run them directly on ESP8266, no external microcontroller required. -This project brings support for ESP8266 chip to the Arduino environment. ESP8266WiFi library bundled with this project has the same interface as the WiFi Shield library, making it easy to re-use existing code and libraries. +ESP8266 Arduino core comes with libraries to communicate over WiFi using TCP and UDP, set up HTTP, mDNS, SSDP, and DNS servers, do OTA updates, use a file system in flash memory, work with SD cards, servos, SPI and I2C peripherals. ### Installing with Boards Manager ### Starting with 1.6.4, Arduino allows installation of third-party platform packages using Boards Manager. We have packages available for Windows, Mac OS, and Linux (32 and 64 bit). -- Install Arduino 1.6.4 from the [Arduino website](http://www.arduino.cc/en/main/software). -- Start Arduino and open Perferences window. -- Enter ```http://arduino.esp8266.com/package_esp8266com_index.json``` into *Additional Board Manager URLs* field. You can add multiple URLs, separating them with commas. +- Install Arduino 1.6.5 from the [Arduino website](http://www.arduino.cc/en/main/software). +- Start Arduino and open Preferences window. +- Enter ```http://arduino.esp8266.com/stable/package_esp8266com_index.json``` into *Additional Board Manager URLs* field. You can add multiple URLs, separating them with commas. - Open Boards Manager from Tools > Board menu and install *esp8266* platform (and don't forget to select your ESP8266 board from Tools > Board menu after installation). -### [Change log](hardware/esp8266com/esp8266/changes.md) +#### Available versions -### Building latest version from source ### -``` -$ git clone https://github.com/esp8266/Arduino.git -$ cd Arduino/build -$ ant dist -``` - -### Supported boards ### -- Generic esp8266 modules (without auto-reset support) -- NodeMCU -- Olimex MOD-WIFI-ESP8266 - -### Things that work ### - -#### Basic Wiring functions #### - -```pinMode```, ```digitalRead```, ```digitalWrite```, ```analogWrite``` work as usual. - -Pin numbers correspond directly to the esp8266 GPIO pin numbers. To read GPIO2, -call ```digitalRead(2);``` - -GPIO0-GPIO15 can be ```INPUT```, ```OUTPUT```, ```INPUT_PULLUP```, and ```INPUT_PULLDOWN```. -GPIO16 can be ```INPUT```, ```OUTPUT``` or ```INPUT_PULLDOWN```. - -```analogRead(A0)``` reads the value of the ADC channel connected to the TOUT pin. - -```analogWrite(pin, value)``` enables software PWM on the given pin. PWM may be used on pins 0 to 15. -Call ```analogWrite(pin, 0)``` to disable PWM on the pin. ```value``` may be in range from 0 to ```PWMRANGE```, which is currently equal to 1023. - -Pin interrupts are supported through ```attachInterrupt```, ```detachInterrupt``` functions. -Interrupts may be attached to any GPIO pin, except GPIO16. Standard Arduino interrupt -types are supported: ```CHANGE```, ```RISING```, ```FALLING```. - -#### Pin Functions #### - -![Pin Functions](https://raw.githubusercontent.com/Links2004/Arduino/esp8266/docs/pin_functions.png) -The most usable pin functions are mapped to the macro ```SPECIAL```, so calling ```pinMode(pin, SPECIAL)``` -will switch that pin in the most usable FUNCTION_X. Those are UART RX/TX on pins 1 - 3, HSPI for pins 12-15 and CLK functions for pins 0, 4 and 5. - -#### Timing and delays #### -```millis``` and ```micros``` return the number of milliseconds and microseconds elapsed after reset, respectively. - -```delay``` pauses the sketch for a given number of milliseconds and allows WiFi and TCP/IP tasks to run. -```delayMicroseconds``` pauses for a given number of microseconds. - -Remember that there is a lot of code that needs to run on the chip besides the sketch -when WiFi is connected. WiFi and TCP/IP libraries get a chance to handle any pending -events each time the ```loop()``` function completes, OR when ```delay(...)``` is called. -If you have a loop somewhere in your sketch that takes a lot of time (>50ms) without -calling ```delay()```, you might consider adding a call to delay function to keep the WiFi -stack running smoothly. - -There is also a ```yield()``` function which is equivalent to ```delay(0)```. The delayMicroseconds -function, on the other hand, does not yield to other tasks, so using it for delays -more than 20 milliseconds is not recommended. - -#### Serial #### - -```Serial``` object works much the same way as on a regular Arduino. Apart from hardware FIFO (128 bytes for TX and RX) HardwareSerial has additional 256-byte TX and RX buffers. Both transmit and receive is interrupt-driven. Write and read functions only block the sketch execution when the respective FIFO/buffers are full/empty. - -```Serial``` uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15 (TX) and GPIO13 (RX) by calling ```Serial.swap();``` after ```Serial.begin();```. Calling ```swap``` again maps UART0 back to GPIO1 and GPIO3. - -```Serial1``` uses UART1 which is a transmit-only UART. UART1 TX pin is GPIO2. To use ```Serial1```, call ```Serial1.begin```. - -By default the diagnostic output from WiFi libraries is disabled when you call ```Serial.begin```. To enable debug output again, call ```Serial.setDebugOutput(true);```. To redirect debug output to ```Serial1``` instead, call ```Serial1.setDebugOutput(true);```. - -You also need to use ```Serial.setDebugOutput(true)``` to enable output from the Arduino ```printf()``` function. - -Both ```Serial``` and ```Serial1``` objects support 5, 6, 7, 8 data bits, odd (O), even (E), and no (N) parity, and 1 or 2 stop bits. To set the desired mode, call ```Serial.begin(baudrate, SERIAL_8N1);```, ```Serial.begin(baudrate, SERIAL_6E2);```, etc. - -#### Progmem #### - -The Program memory features work much the same way as on a regular Arduino; placing read only data and strings in read only memory and freeing heap for your application. -The important difference is that on the esp8266 the literal strings are not pooled. This means that the same literal string defined inside a ```F("")``` and/or ```PSTR("")``` will take up space for each instance in the code. So you will need to manage the duplicate strings yourself. - -#### WiFi(ESP8266WiFi library) #### - -This is mostly similar to WiFi shield library. Differences include: - -- ```WiFi.mode(m)```: set mode to ```WIFI_AP```, ```WIFI_STA```, or ```WIFI_AP_STA```. -- call ```WiFi.softAP(ssid)``` to set up an open network -- call ```WiFi.softAP(ssid, password)``` to set up a WPA2-PSK network (password should be at least 8 characters) -- ```WiFi.macAddress(mac)``` is for STA, ```WiFi.softAPmacAddress(mac)``` is for AP. -- ```WiFi.localIP()``` is for STA, ```WiFi.softAPIP()``` is for AP. -- ```WiFi.RSSI()``` doesn't work -- ```WiFi.printDiag(Serial);``` will print out some diagnostic info -- ```WiFiUDP``` class supports sending and receiving multicast packets on STA interface. -When sending a multicast packet, replace ```udp.beginPacket(addr, port)``` with -```udp.beginPacketMulticast(addr, port, WiFi.localIP())```. -When listening to multicast packets, replace ```udp.begin(port)``` with -```udp.beginMulticast(WiFi.localIP(), multicast_ip_addr, port)```. -You can use ```udp.destinationIP()``` to tell whether the packet received was -sent to the multicast or unicast address. -Also note that multicast doesn't work on softAP interface. - -WiFiServer, WiFiClient, and WiFiUDP behave mostly the same way as with WiFi shield library. -Four samples are provided for this library. -You can see more commands here: [http://www.arduino.cc/en/Reference/WiFi](http://www.arduino.cc/en/Reference/WiFi) - -#### Ticker #### - -Library for calling functions repeatedly with a certain period. Two examples included. - -It is currently not recommended to do blocking IO operations (network, serial, file) from Ticker -callback functions. Instead, set a flag inside the ticker callback and check for that flag inside the loop function. - -#### EEPROM #### - -This is a bit different from standard EEPROM class. You need to call ```EEPROM.begin(size)``` -before you start reading or writing, size being the number of bytes you want to use. -Size can be anywhere between 4 and 4096 bytes. - -```EEPROM.write``` does not write to flash immediately, instead you must call ```EEPROM.commit()``` -whenever you wish to save changes to flash. ```EEPROM.end()``` will also commit, and will -release the RAM copy of EEPROM contents. - -EEPROM library uses one sector of flash located at 0x7b000 for storage. - -Three examples included. - -#### I2C (Wire library) #### - -Wire library currently supports master mode up to approximately 450KHz. -Before using I2C, pins for SDA and SCL need to be set by calling -```Wire.begin(int sda, int scl)```, i.e. ```Wire.begin(0, 2);``` on ESP-01, -else they default to pins 4(SDA) and 5(SCL). +##### Stable version ![](http://arduino.esp8266.com/stable/badge.svg) +Boards manager link: `http://arduino.esp8266.com/stable/package_esp8266com_index.json` -#### SPI #### +Documentation: [Reference](http://arduino.esp8266.com/stable/doc/reference.html) -SPI library supports the entire Arduino SPI API including transactions, including setting phase (CPHA). -Setting the Clock polarity (CPOL) is not supported, yet (SPI_MODE2 and SPI_MODE3 not working). +##### Staging version ![](http://arduino.esp8266.com/staging/badge.svg) +Boards manager link: `http://arduino.esp8266.com/staging/package_esp8266com_index.json` -#### ESP-specific APIs #### +Documentation: [Reference](http://arduino.esp8266.com/staging/doc/reference.html) -APIs related to deep sleep and watchdog timer are available in the ```ESP``` object, only available in Alpha version. -```ESP.deepSleep(microseconds, mode)``` will put the chip into deep sleep. ```mode``` is one of ```WAKE_RF_DEFAULT```, ```WAKE_RFCAL```, ```WAKE_NO_RFCAL```, ```WAKE_RF_DISABLED```. (GPIO16 needs to be tied to RST to wake from deepSleep.) +### Building latest version from source [![Linux build status](https://travis-ci.org/esp8266/Arduino.svg)](https://travis-ci.org/esp8266/Arduino) -```ESP.restart()``` restarts the CPU. - -```ESP.getFreeHeap()``` returns the free heap size. - -```ESP.getChipId()``` returns the ESP8266 chip ID as a 32-bit integer. - -Several APIs may be used to get flash chip info: - -```ESP.getFlashChipId()``` returns the flash chip ID as a 32-bit integer. - -```ESP.getFlashChipSize()``` returns the flash chip size, in bytes, as seen by the SDK (may be less than actual size). - -```ESP.getFlashChipSpeed(void)``` returns the flash chip frequency, in Hz. - -```ESP.getCycleCount()``` returns the cpu instruction cycle count since start as an unsigned 32-bit. This is useful for accurate timing of very short actions like bit banging. - -```ESP.getVcc()``` may be used to measure supply voltage. ESP needs to reconfigure the ADC -at startup in order for this feature to be available. Add the following line to the top -of your sketch to use ```getVcc```: ``` -ADC_MODE(ADC_VCC); +$ git clone https://github.com/esp8266/Arduino.git +$ cd Arduino/build +$ ant dist ``` -TOUT pin has to be disconnected in this mode. - -Note that by default ADC is configured to read from TOUT pin using ```analogRead(A0)```, and -```ESP.getVCC()``` is not available. - -#### OneWire (from https://www.pjrc.com/teensy/td_libs_OneWire.html) #### - -Library was adapted to work with ESP8266 by including register definitions into OneWire.h -Note that if you already have OneWire library in your Arduino/libraries folder, it will be used -instead of the one that comes with this package. - -#### mDNS responder (ESP8266mDNS library) #### - -Allows the sketch to respond to multicast DNS queries for domain names like "foo.local". -Currently the library only works on STA interface, AP interface is not supported. -See attached example and library README file for details. - -#### DNS server (DNSServer library) #### - -Implements a simple DNS server that can be used in both STA and AP modes. The DNS server currently supports only one domain (for all other domains it will reply with NXDOMAIN or custom status code). With it clients can open a web server running on ESP8266 using a domain name, not an IP address. -See attached example for details. - -#### Servo #### - -This library exposes the ability to control RC (hobby) servo motors. It will support upto 24 servos on any available output pin. By defualt the first 12 servos will use Timer0 and currently this will not interfere with any other support. Servo counts above 12 will use Timer1 and features that use it will be effected. -While many RC servo motors will accept the 3.3v IO data pin from a esp8266, most will not be able to run off 3.3v and will require another power source that matches their specifications. Make sure to connect the grounds between the esp8266 and the servo motor power supply. - -#### Other libraries (not included with the IDE) -Libraries that don't rely on low-level access to AVR registers should work well. Here are a few libraries that were verified to work: +Documentation for latest development version: -- [arduinoWebSockets](https://github.com/Links2004/arduinoWebSockets) - WebSocket Server and Client compatible with esp8266 (RFC6455) -- [aREST](https://github.com/marcoschwartz/aREST) REST API handler library. -- [Blynk](https://github.com/blynkkk/blynk-library) - easy IoT framework for Makers (check out the [Kickstarter page](http://tiny.cc/blynk-kick)). -- [DallasTemperature](https://github.com/milesburton/Arduino-Temperature-Control-Library.git) -- [DHT11](https://github.com/adafruit/DHT-sensor-library) - Download latest v1.1.0 library and no changes are necessary. Older versions should initialize DHT as follows: ```DHT dht(DHTPIN, DHTTYPE, 15);``` -- [NeoPixel](https://github.com/adafruit/Adafruit_NeoPixel) - Adafruit's NeoPixel library, now with support for the ESP8266 (use version 1.0.2 or higher from Arduino's library manager). -- [NeoPixelBus](https://github.com/Makuna/NeoPixelBus) - Arduino NeoPixel library compatible with esp8266. Use the "NeoPixelAnimator" branch for esp8266 to get HSL color support and more. -- [PubSubClient](https://github.com/Imroy/pubsubclient) MQTT library by @Imroy. -- [RTC](https://github.com/Makuna/Rtc) - Arduino Library for Ds1307 & Ds3231 compatible with esp8266. -- [Souliss, Smart Home](https://github.com/souliss/souliss) - Framework for Smart Home based on Arduino, Android and openHAB. -- [ST7735](https://github.com/nzmichaelh/Adafruit-ST7735-Library) - Adafruit's ST7735 library modified to be compatible with esp8266. Just make sure to modify the pins in the examples as they are still AVR specific. +- [Reference](hardware/esp8266com/esp8266/doc/reference.md) +- [Supported boards](hardware/esp8266com/esp8266/doc/boards.md) +- [Change log](hardware/esp8266com/esp8266/doc/changes.md) -#### Upload via serial port #### -Pick the correct serial port. -You need to put ESP8266 into bootloader mode before uploading code. - -#### Power Supply #### - -For stable use of the ESP8266 a power supply with 3V3 and >= 250mA is required. - -* Note - - using Power from USB to Serial is may unstable, they not deliver enough current. - -#### Serial Adapter #### - -There are many different USB to Serial adapters / boards. - -* Note - - for full upload management you need RTS and DTR - - the chip need to have 3V3 TTL (5V may damage the chip) - - not all board have all pins of the ICs as breakout (check before order) - - CTS and DSR are not useful for upload (they are Inputs) - -* Working ICs - - FT232RL - - CP2102 - - may others (drop a comment) - -#### Minimal hardware Setup for Bootloading and usage #### - -ESPxx Hardware - -| PIN | Resistor | Serial Adapter | -| ------------- | -------- | -------------- | -| VCC | | VCC (3.3V) | -| GND | | GND | -| TX or GPIO2* | | RX | -| RX | | TX | -| GPIO0 | PullUp | DTR | -| Reset* | | RTS | -| GPIO15* | PullDown | | -| CH_PD | PullUp | | - -* Note - - GPIO15 is also named MTDO - - Reset is also named RSBT or REST (adding PullUp improves the stability of the Module) - - GPIO2 is alternative TX for the boot loader mode - -###### esp to Serial -![ESP to Serial](https://raw.githubusercontent.com/Links2004/Arduino/esp8266/docs/ESP_to_serial.png) - -#### Minimal hardware Setup for Bootloading only #### -ESPxx Hardware - -| PIN | Resistor | Serial Adapter | -| ------------- | -------- | --------------- | -| VCC | | VCC (3.3V) | -| GND | | GND | -| TX or GPIO2 | | RX | -| RX | | TX | -| GPIO0 | | GND | -| Reset | | RTS* | -| GPIO15 | PullDown | | -| CH_PD | PullUp | | - -* Note - - if no RTS is used a manual power toggle is needed - -#### Minimal hardware Setup for running only #### - -ESPxx Hardware +### Issues and support ### -| PIN | Resistor | Power supply | -| ------------- | -------- | --------------- | -| VCC | | VCC (3.3V) | -| GND | | GND | -| GPIO0 | PullUp | | -| GPIO15 | PullDown | | -| CH_PD | PullUp | | +The best place to ask questions related to this core is ESP8266 community forum: http://www.esp8266.com/arduino. +If you find the forum useful, please consider supporting it with a donation. +[![Donate](https://img.shields.io/badge/paypal-donate-yellow.svg)](https://www.paypal.com/webscr?cmd=_s-xclick&hosted_button_id=4M56YCWV6PX66) -###### minimal -![ESP min](https://raw.githubusercontent.com/Links2004/Arduino/esp8266/docs/ESP_min.png) +If you encounter an issue, you are welcome to submit it here on Github: https://github.com/esp8266/Arduino/issues. +Please provide as much context as possible: version which you are using (you can check it in Boards Manager), your sketch code, serial output, board model, IDE settings (board selection, flash size, etc). -###### improved stability -![ESP improved stability](https://raw.githubusercontent.com/Links2004/Arduino/esp8266/docs/ESP_improved_stability.png) +### Contributing -### Issues and support ### +For minor fixes of code and documentation, go ahead and submit a pull request. -Forum: http://www.esp8266.com/arduino +Larger changes (rewriting parts of existing code from scratch, adding new functions to the core, adding new libraries) should generally be discussed [in the chat](https://gitter.im/esp8266/Arduino) first. -Submit issues on Github: https://github.com/esp8266/Arduino/issues +Feature branches with lots of small commits (especially titled "oops", "fix typo", "forgot to add file", etc.) should be squashed before opening a pull request. At the same time, please refrain from putting multiple unrelated changes into a single pull request. ### License and credits ### -Arduino IDE is based on Wiring and Processing. It is developed and maintained by the Arduino team. The IDE is licensed under GPL, and the core libraries are licensed under LGPL. +Arduino IDE is developed and maintained by the Arduino team. The IDE is licensed under GPL. -This build includes an xtensa gcc toolchain, which is also under GPL. - -Espressif SDK included in this build is under Espressif Public License. +ESP8266 core includes an xtensa gcc toolchain, which is also under GPL. Esptool written by Christian Klippel is licensed under GPLv2, currently maintained by Ivan Grokhotkov: https://github.com/igrr/esptool-ck. -ESP8266 core support, ESP8266WiFi, Ticker, ESP8266WebServer libraries were written by Ivan Grokhotkov, ivan@esp8266.com. +Espressif SDK included in this build is under Espressif MIT License. + +ESP8266 core files are licensed under LGPL. [SPI Flash File System (SPIFFS)](https://github.com/pellepl/spiffs) written by Peter Andersson is used in this project. It is distributed under MIT license. diff --git a/build/build_board_manager_package.sh b/build/build_board_manager_package.sh index 64834f7001..ef88d35adb 100755 --- a/build/build_board_manager_package.sh +++ b/build/build_board_manager_package.sh @@ -27,17 +27,29 @@ size=`/bin/ls -l $outdir.zip | awk '{print $5}'` echo Size: $size echo SHA-256: $sha -if [ "$upload" == "prod" ]; then - remote="http://arduino.esp8266.com" +if [ "$upload" == "stable" ]; then + badge_title="stable" + badge_color="blue" path="" -elif [ "$upload" == "stag" ]; then - remote="http://arduino.esp8266.com" +elif [ "$upload" == "staging" ]; then + badge_title="staging" + badge_color="yellow" path="staging/" +elif [ "$upload" == "test" ]; then + badge_title="test" + badge_color="red" + path="test/" else upload="" remote="http://localhost:8000" fi +if [ ! -z "$upload" ]; then + remote="http://arduino.esp8266.com" + release_date=$(date "+%b_%d,_%Y") + wget -O badge.svg https://img.shields.io/badge/$badge_title-$release_date-$badge_color.svg +fi + cat << EOF > package_esp8266com_index.json { "packages": [ { @@ -76,6 +88,9 @@ cat << EOF > package_esp8266com_index.json }, { "name":"Adafruit HUZZAH ESP8266 (ESP-12)" + }, + { + "name":"SweetPea ESP-210" } ], "toolsDependencies":[ { @@ -120,7 +135,7 @@ cat << EOF > package_esp8266com_index.json "url":"https://github.com/igrr/esptool-ck/releases/download/0.4.5/esptool-0.4.5-linux32.tar.gz", "archiveFileName":"esptool-0.4.5-linux32.tar.gz", "checksum":"SHA-256:4aa81b97a470641771cf371e5d470ac92d3b177adbe8263c4aae66e607b67755", - "size":"12044" + "size":"12044" } ] }, @@ -168,9 +183,7 @@ if [ ! -z "$upload" ]; then scp $outdir.zip $remote_path scp package_esp8266com_index.json $remote_path scp -r $srcdir/doc $remote_path + scp badge.svg $remote_path else - python -m SimpleHTTPServer + python -m SimpleHTTPServer fi - - - diff --git a/hardware/esp8266com/esp8266/boards.txt b/hardware/esp8266com/esp8266/boards.txt index f92c773b48..58eb78edb5 100644 --- a/hardware/esp8266com/esp8266/boards.txt +++ b/hardware/esp8266com/esp8266/boards.txt @@ -135,56 +135,46 @@ generic.menu.FlashSize.4M.upload.maximum_size=1044464 # generic.menu.FlashSize.16M.build.spiffs_blocksize=8192 ############################################################## -modwifi.name=Olimex MOD-WIFI-ESP8266(-DEV) +huzzah.name=Adafruit HUZZAH ESP8266 -modwifi.upload.tool=esptool -modwifi.upload.speed=115200 -modwifi.upload.resetmethod=ck -modwifi.upload.maximum_size=1044464 -modwifi.upload.maximum_data_size=81920 -modwifi.upload.wait_for_upload_port=true -modwifi.serial.disableDTR=true -modwifi.serial.disableRTS=true +huzzah.upload.tool=esptool +huzzah.upload.speed=115200 +huzzah.upload.resetmethod=ck +huzzah.upload.maximum_size=1044464 +huzzah.upload.maximum_data_size=81920 +huzzah.upload.wait_for_upload_port=true +huzzah.serial.disableDTR=true +huzzah.serial.disableRTS=true -modwifi.build.mcu=esp8266 -modwifi.build.f_cpu=80000000L -modwifi.build.board=MOD_WIFI_ESP8266 -modwifi.build.core=esp8266 -modwifi.build.variant=generic -# Winbond W25Q16 flash -modwifi.build.flash_mode=qio -modwifi.build.flash_size=2M -modwifi.build.flash_freq=40 -modwifi.build.flash_ld=eagle.flash.2m.ld -modwifi.build.spiffs_start=0x100000 -modwifi.build.spiffs_end=0x1FB000 -modwifi.build.spiffs_pagesize=256 -modwifi.build.spiffs_blocksize=8192 +huzzah.build.mcu=esp8266 +huzzah.build.f_cpu=80000000L +huzzah.build.board=ESP8266_ESP12 +huzzah.build.core=esp8266 +huzzah.build.variant=adafruit +huzzah.build.flash_mode=qio +huzzah.build.flash_size=4M +huzzah.build.flash_freq=40 +huzzah.build.flash_ld=eagle.flash.4m.ld +huzzah.build.spiffs_start=0x100000 +huzzah.build.spiffs_end=0x3FB000 +huzzah.build.spiffs_pagesize=256 +huzzah.build.spiffs_blocksize=8192 -modwifi.menu.CpuFrequency.80=80 MHz -modwifi.menu.CpuFrequency.80.build.f_cpu=80000000L -modwifi.menu.CpuFrequency.160=160 MHz -modwifi.menu.CpuFrequency.160.build.f_cpu=160000000L +huzzah.menu.CpuFrequency.80=80 MHz +huzzah.menu.CpuFrequency.80.build.f_cpu=80000000L +huzzah.menu.CpuFrequency.160=160 MHz +huzzah.menu.CpuFrequency.160.build.f_cpu=160000000L -modwifi.menu.UploadSpeed.115200=115200 -modwifi.menu.UploadSpeed.115200.upload.speed=115200 -modwifi.menu.UploadSpeed.9600=9600 -modwifi.menu.UploadSpeed.9600.upload.speed=9600 -modwifi.menu.UploadSpeed.57600=57600 -modwifi.menu.UploadSpeed.57600.upload.speed=57600 -modwifi.menu.UploadSpeed.256000.windows=256000 -modwifi.menu.UploadSpeed.256000.upload.speed=256000 -modwifi.menu.UploadSpeed.230400.linux=230400 -modwifi.menu.UploadSpeed.230400.macosx=230400 -modwifi.menu.UploadSpeed.230400.macosx=230400 -modwifi.menu.UploadSpeed.230400.upload.speed=230400 -modwifi.menu.UploadSpeed.460800.linux=460800 -modwifi.menu.UploadSpeed.460800.macosx=460800 -modwifi.menu.UploadSpeed.460800.upload.speed=460800 -modwifi.menu.UploadSpeed.512000.windows=512000 -modwifi.menu.UploadSpeed.512000.upload.speed=512000 -modwifi.menu.UploadSpeed.921600=921600 -modwifi.menu.UploadSpeed.921600.upload.speed=921600 +huzzah.menu.UploadSpeed.115200=115200 +huzzah.menu.UploadSpeed.115200.upload.speed=115200 +huzzah.menu.UploadSpeed.9600=9600 +huzzah.menu.UploadSpeed.9600.upload.speed=9600 +huzzah.menu.UploadSpeed.57600=57600 +huzzah.menu.UploadSpeed.57600.upload.speed=57600 +huzzah.menu.UploadSpeed.256000=256000 +huzzah.menu.UploadSpeed.256000.upload.speed=256000 +huzzah.menu.UploadSpeed.921600=921600 +huzzah.menu.UploadSpeed.921600.upload.speed=921600 ############################################################## nodemcu.name=NodeMCU 0.9 (ESP-12 Module) @@ -239,7 +229,7 @@ nodemcu.menu.UploadSpeed.921600.upload.speed=921600 ############################################################## nodemcuv2.name=NodeMCU 1.0 (ESP-12E Module) - + nodemcuv2.upload.tool=esptool nodemcuv2.upload.speed=115200 nodemcuv2.upload.resetmethod=ck @@ -248,7 +238,7 @@ nodemcuv2.upload.maximum_data_size=81920 nodemcuv2.upload.wait_for_upload_port=true nodemcuv2.serial.disableDTR=true nodemcuv2.serial.disableRTS=true - + nodemcuv2.build.mcu=esp8266 nodemcuv2.build.f_cpu=80000000L nodemcuv2.build.board=ESP8266_ESP12 @@ -262,12 +252,12 @@ nodemcuv2.build.spiffs_start=0x100000 nodemcuv2.build.spiffs_end=0x3FB000 nodemcuv2.build.spiffs_pagesize=256 nodemcuv2.build.spiffs_blocksize=8192 - + nodemcuv2.menu.CpuFrequency.80=80 MHz nodemcuv2.menu.CpuFrequency.80.build.f_cpu=80000000L nodemcuv2.menu.CpuFrequency.160=160 MHz nodemcuv2.menu.CpuFrequency.160.build.f_cpu=160000000L - + nodemcuv2.menu.UploadSpeed.115200=115200 nodemcuv2.menu.UploadSpeed.115200.upload.speed=115200 nodemcuv2.menu.UploadSpeed.9600=9600 @@ -289,46 +279,106 @@ nodemcuv2.menu.UploadSpeed.921600=921600 nodemcuv2.menu.UploadSpeed.921600.upload.speed=921600 ############################################################## -huzzah.name=Adafruit HUZZAH ESP8266 +modwifi.name=Olimex MOD-WIFI-ESP8266(-DEV) -huzzah.upload.tool=esptool -huzzah.upload.speed=115200 -huzzah.upload.resetmethod=ck -huzzah.upload.maximum_size=1044464 -huzzah.upload.maximum_data_size=81920 -huzzah.upload.wait_for_upload_port=true -huzzah.serial.disableDTR=true -huzzah.serial.disableRTS=true +modwifi.upload.tool=esptool +modwifi.upload.speed=115200 +modwifi.upload.resetmethod=ck +modwifi.upload.maximum_size=1044464 +modwifi.upload.maximum_data_size=81920 +modwifi.upload.wait_for_upload_port=true +modwifi.serial.disableDTR=true +modwifi.serial.disableRTS=true -huzzah.build.mcu=esp8266 -huzzah.build.f_cpu=80000000L -huzzah.build.board=ESP8266_ESP12 -huzzah.build.core=esp8266 -huzzah.build.variant=adafruit -huzzah.build.flash_mode=qio -huzzah.build.flash_size=4M -huzzah.build.flash_freq=40 -huzzah.build.flash_ld=eagle.flash.4m.ld -huzzah.build.spiffs_start=0x100000 -huzzah.build.spiffs_end=0x3FB000 -huzzah.build.spiffs_pagesize=256 -huzzah.build.spiffs_blocksize=8192 +modwifi.build.mcu=esp8266 +modwifi.build.f_cpu=80000000L +modwifi.build.board=MOD_WIFI_ESP8266 +modwifi.build.core=esp8266 +modwifi.build.variant=generic +# Winbond W25Q16 flash +modwifi.build.flash_mode=qio +modwifi.build.flash_size=2M +modwifi.build.flash_freq=40 +modwifi.build.flash_ld=eagle.flash.2m.ld +modwifi.build.spiffs_start=0x100000 +modwifi.build.spiffs_end=0x1FB000 +modwifi.build.spiffs_pagesize=256 +modwifi.build.spiffs_blocksize=8192 -huzzah.menu.CpuFrequency.80=80 MHz -huzzah.menu.CpuFrequency.80.build.f_cpu=80000000L -huzzah.menu.CpuFrequency.160=160 MHz -huzzah.menu.CpuFrequency.160.build.f_cpu=160000000L +modwifi.menu.CpuFrequency.80=80 MHz +modwifi.menu.CpuFrequency.80.build.f_cpu=80000000L +modwifi.menu.CpuFrequency.160=160 MHz +modwifi.menu.CpuFrequency.160.build.f_cpu=160000000L -huzzah.menu.UploadSpeed.115200=115200 -huzzah.menu.UploadSpeed.115200.upload.speed=115200 -huzzah.menu.UploadSpeed.9600=9600 -huzzah.menu.UploadSpeed.9600.upload.speed=9600 -huzzah.menu.UploadSpeed.57600=57600 -huzzah.menu.UploadSpeed.57600.upload.speed=57600 -huzzah.menu.UploadSpeed.256000=256000 -huzzah.menu.UploadSpeed.256000.upload.speed=256000 -huzzah.menu.UploadSpeed.921600=921600 -huzzah.menu.UploadSpeed.921600.upload.speed=921600 +modwifi.menu.UploadSpeed.115200=115200 +modwifi.menu.UploadSpeed.115200.upload.speed=115200 +modwifi.menu.UploadSpeed.9600=9600 +modwifi.menu.UploadSpeed.9600.upload.speed=9600 +modwifi.menu.UploadSpeed.57600=57600 +modwifi.menu.UploadSpeed.57600.upload.speed=57600 +modwifi.menu.UploadSpeed.256000.windows=256000 +modwifi.menu.UploadSpeed.256000.upload.speed=256000 +modwifi.menu.UploadSpeed.230400.linux=230400 +modwifi.menu.UploadSpeed.230400.macosx=230400 +modwifi.menu.UploadSpeed.230400.macosx=230400 +modwifi.menu.UploadSpeed.230400.upload.speed=230400 +modwifi.menu.UploadSpeed.460800.linux=460800 +modwifi.menu.UploadSpeed.460800.macosx=460800 +modwifi.menu.UploadSpeed.460800.upload.speed=460800 +modwifi.menu.UploadSpeed.512000.windows=512000 +modwifi.menu.UploadSpeed.512000.upload.speed=512000 +modwifi.menu.UploadSpeed.921600=921600 +modwifi.menu.UploadSpeed.921600.upload.speed=921600 + +############################################################## +thing.name=SparkFun ESP8266 Thing + +thing.upload.tool=esptool +thing.upload.speed=921600 +thing.upload.resetmethod=ck +thing.upload.maximum_size=434160 +thing.upload.maximum_data_size=81920 +thing.upload.wait_for_upload_port=true +thing.serial.disableDTR=true +thing.serial.disableRTS=true + +thing.build.mcu=esp8266 +thing.build.f_cpu=80000000L +thing.build.board=ESP8266_THING +thing.build.core=esp8266 +thing.build.variant=thing +thing.build.flash_mode=qio +# flash chip: AT25SF041 (512 kbyte, 4Mbit) +thing.build.flash_size=512K +thing.build.flash_ld=eagle.flash.512k.ld +thing.build.flash_freq=40 +thing.build.spiffs_start=0x6B000 +thing.build.spiffs_end=0x7B000 +thing.build.spiffs_blocksize=4096 + +thing.menu.CpuFrequency.80=80 MHz +thing.menu.CpuFrequency.80.build.f_cpu=80000000L +thing.menu.CpuFrequency.160=160 MHz +thing.menu.CpuFrequency.160.build.f_cpu=160000000L + +thing.menu.UploadSpeed.115200=115200 +thing.menu.UploadSpeed.115200.upload.speed=115200 +thing.menu.UploadSpeed.9600=9600 +thing.menu.UploadSpeed.9600.upload.speed=9600 +thing.menu.UploadSpeed.57600=57600 +thing.menu.UploadSpeed.57600.upload.speed=57600 +thing.menu.UploadSpeed.256000.windows=256000 +thing.menu.UploadSpeed.256000.upload.speed=256000 +thing.menu.UploadSpeed.230400.linux=230400 +thing.menu.UploadSpeed.230400.macosx=230400 +thing.menu.UploadSpeed.230400.upload.speed=230400 +thing.menu.UploadSpeed.460800.linux=460800 +thing.menu.UploadSpeed.460800.macosx=460800 +thing.menu.UploadSpeed.460800.upload.speed=460800 +thing.menu.UploadSpeed.512000.windows=512000 +thing.menu.UploadSpeed.512000.upload.speed=512000 +thing.menu.UploadSpeed.921600=921600 +thing.menu.UploadSpeed.921600.upload.speed=921600 ############################################################## esp210.name=SweetPea ESP-210 @@ -337,6 +387,7 @@ esp210.upload.tool=esptool esp210.upload.speed=115200 esp210.upload.resetmethod=ck esp210.upload.maximum_size=1044464 +esp210.upload.maximum_data_size=81920 esp210.upload.wait_for_upload_port=true esp210.serial.disableDTR=true esp210.serial.disableRTS=true diff --git a/hardware/esp8266com/esp8266/bootloaders/eboot/eboot.c b/hardware/esp8266com/esp8266/bootloaders/eboot/eboot.c index cbc87044b6..3c0bc1cce5 100644 --- a/hardware/esp8266com/esp8266/bootloaders/eboot/eboot.c +++ b/hardware/esp8266com/esp8266/bootloaders/eboot/eboot.c @@ -1,4 +1,4 @@ -/* Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. +/* Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. * This file is part of eboot bootloader. * * Redistribution and use is permitted according to the conditions of the @@ -14,6 +14,8 @@ #define SWRST do { (*((volatile uint32_t*) 0x60000700)) |= 0x80000000; } while(0); +extern void ets_wdt_enable(void); +extern void ets_wdt_disable(void); int load_app_from_flash_raw(const uint32_t flash_addr) { @@ -24,10 +26,10 @@ int load_app_from_flash_raw(const uint32_t flash_addr) return 1; } pos += sizeof(image_header); - + for (uint32_t section_index = 0; - section_index < image_header.num_segments; + section_index < image_header.num_segments; ++section_index) { section_header_t section_header = {0}; @@ -72,8 +74,8 @@ int load_app_from_flash_raw(const uint32_t flash_addr) -int copy_raw(const uint32_t src_addr, - const uint32_t dst_addr, +int copy_raw(const uint32_t src_addr, + const uint32_t dst_addr, const uint32_t size) { // require regions to be aligned @@ -87,20 +89,20 @@ int copy_raw(const uint32_t src_addr, uint32_t left = ((size+buffer_size-1) & ~(buffer_size-1)); uint32_t saddr = src_addr; uint32_t daddr = dst_addr; - + while (left) { - if (SPIEraseSector(daddr/buffer_size)) { - return 2; - } - if (SPIRead(saddr, buffer, buffer_size)) { - return 3; - } - if (SPIWrite(daddr, buffer, buffer_size)) { - return 4; - } - saddr += buffer_size; - daddr += buffer_size; - left -= buffer_size; + if (SPIEraseSector(daddr/buffer_size)) { + return 2; + } + if (SPIRead(saddr, buffer, buffer_size)) { + return 3; + } + if (SPIWrite(daddr, buffer, buffer_size)) { + return 4; + } + saddr += buffer_size; + daddr += buffer_size; + left -= buffer_size; } return 0; @@ -121,10 +123,12 @@ void main() ets_putc('@'); } eboot_command_clear(); - + if (cmd.action == ACTION_COPY_RAW) { ets_putc('c'); ets_putc('p'); ets_putc(':'); + ets_wdt_disable(); res = copy_raw(cmd.args[0], cmd.args[1], cmd.args[2]); + ets_wdt_enable(); ets_putc('0'+res); ets_putc('\n'); if (res == 0) { cmd.action = ACTION_LOAD_APP; @@ -133,14 +137,14 @@ void main() } if (cmd.action == ACTION_LOAD_APP) { - ets_putc('l'); ets_putc('d'); ets_putc('\n'); - res = load_app_from_flash_raw(cmd.args[0]); - //we will get to this only on load fail - ets_putc('e'); ets_putc(':'); ets_putc('0'+res); ets_putc('\n'); + ets_putc('l'); ets_putc('d'); ets_putc('\n'); + res = load_app_from_flash_raw(cmd.args[0]); + //we will get to this only on load fail + ets_putc('e'); ets_putc(':'); ets_putc('0'+res); ets_putc('\n'); } if (res) { - SWRST; + SWRST; } while(true){} diff --git a/hardware/esp8266com/esp8266/bootloaders/eboot/eboot.elf b/hardware/esp8266com/esp8266/bootloaders/eboot/eboot.elf index 36c480fe0c..7fb4f5f93a 100755 Binary files a/hardware/esp8266com/esp8266/bootloaders/eboot/eboot.elf and b/hardware/esp8266com/esp8266/bootloaders/eboot/eboot.elf differ diff --git a/hardware/esp8266com/esp8266/cores/esp8266/Arduino.h b/hardware/esp8266com/esp8266/cores/esp8266/Arduino.h index ad0e7cb36d..6b379d5b1e 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/Arduino.h +++ b/hardware/esp8266com/esp8266/cores/esp8266/Arduino.h @@ -38,9 +38,6 @@ extern "C" { #include "esp8266_peri.h" #include "twi.h" -void yield(void); -void optimistic_yield(void); - #define HIGH 0x1 #define LOW 0x0 @@ -140,8 +137,8 @@ void timer0_detachInterrupt(void); void ets_intr_lock(); void ets_intr_unlock(); -// level (0-15), -// level 15 will disable ALL interrupts, +// level (0-15), +// level 15 will disable ALL interrupts, // level 0 will disable most software interrupts // #define xt_disable_interrupts(state, level) __asm__ __volatile__("rsil %0," __STRINGIFY(level) : "=a" (state)) @@ -207,6 +204,9 @@ void detachInterrupt(uint8_t); void setup(void); void loop(void); +void yield(void); +void optimistic_yield(uint32_t interval_us); + // Get the bit location within the hardware port of the given virtual pin. // This comes from the pins_*.c file for the active board configuration. #define digitalPinToPort(pin) (0) diff --git a/hardware/esp8266com/esp8266/cores/esp8266/Esp.h b/hardware/esp8266com/esp8266/cores/esp8266/Esp.h index 8e66f8f88d..17349f6882 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/Esp.h +++ b/hardware/esp8266com/esp8266/cores/esp8266/Esp.h @@ -68,7 +68,7 @@ enum ADCMode { ADC_VDD = 255 }; -#define ADC_MODE(mode) extern "C" int __get_adc_mode() { return (int) (mode); } +#define ADC_MODE(mode) extern "C" int __get_adc_mode(void) { return (int) (mode); } typedef enum { FM_QIO = 0x00, diff --git a/hardware/esp8266com/esp8266/cores/esp8266/FS.cpp b/hardware/esp8266com/esp8266/cores/esp8266/FS.cpp new file mode 100644 index 0000000000..18eda0c86f --- /dev/null +++ b/hardware/esp8266com/esp8266/cores/esp8266/FS.cpp @@ -0,0 +1,310 @@ +/* + FS.cpp - file system wrapper + Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "FS.h" +#include "FSImpl.h" + +static bool sflags(const char* mode, OpenMode& om, AccessMode& am); + +size_t File::write(uint8_t c) { + if (!_p) + return 0; + + _p->write(&c, 1); +} + +size_t File::write(const uint8_t *buf, size_t size) { + if (!_p) + return 0; + + _p->write(buf, size); +} + +int File::available() { + if (!_p) + return false; + + return _p->position() < _p->size(); +} + +int File::read() { + if (!_p) + return -1; + + uint8_t result; + if (_p->read(&result, 1) != 1) { + return -1; + } + + return result; +} + +size_t File::read(uint8_t* buf, size_t size) { + if (!_p) + return -1; + + return _p->read(buf, size); +} + +int File::peek() { + if (!_p) + return -1; + + size_t curPos = _p->position(); + int result = read(); + seek(curPos, SeekSet); + return result; +} + +void File::flush() { + if (!_p) + return; + + _p->flush(); +} + +bool File::seek(uint32_t pos, SeekMode mode) { + if (!_p) + return false; + + return _p->seek(pos, mode); +} + +size_t File::position() const { + if (!_p) + return 0; + + return _p->position(); +} + +size_t File::size() const { + if (!_p) + return 0; + + return _p->size(); +} + +void File::close() { + if (_p) { + _p->close(); + _p = nullptr; + } +} + +File::operator bool() const { + return !!_p; +} + +File Dir::openFile(const char* mode) { + if (!_impl) { + return File(); + } + + OpenMode om; + AccessMode am; + if (!sflags(mode, om, am)) { + DEBUGV("Dir::openFile: invalid mode `%s`\r\n", mode); + return File(); + } + + return File(_impl->openFile(om, am)); +} + +String Dir::fileName() { + if (!_impl) { + return String(); + } + + return _impl->fileName(); +} + +bool Dir::next() { + if (!_impl) { + return false; + } + + return _impl->next(); +} + +bool FS::begin() { + if (!_impl) { + return false; + } + return _impl->begin(); +} + +File FS::open(const String& path, const char* mode) { + return open(path.c_str(), mode); +} + +File FS::open(const char* path, const char* mode) { + if (!_impl) { + return File(); + } + + OpenMode om; + AccessMode am; + if (!sflags(mode, om, am)) { + DEBUGV("FS::open: invalid mode `%s`\r\n", mode); + return File(); + } + + return File(_impl->open(path, om, am)); +} + +Dir FS::openDir(const char* path) { + if (!_impl) { + return Dir(); + } + return Dir(_impl->openDir(path)); +} + +Dir FS::openDir(const String& path) { + return openDir(path.c_str()); +} + +bool FS::remove(const char* path) { + if (!_impl) { + return false; + } + return _impl->remove(path); +} + +bool FS::remove(const String& path) { + return remove(path.c_str()); +} + +bool FS::rename(const char* pathFrom, const char* pathTo) { + if (!_impl) { + return false; + } + return _impl->rename(pathFrom, pathTo); +} + +bool FS::rename(const String& pathFrom, const String& pathTo) { + return rename(pathFrom.c_str(), pathTo.c_str()); +} + + +static bool sflags(const char* mode, OpenMode& om, AccessMode& am) { + switch (mode[0]) { + case 'r': + am = AM_READ; + om = OM_DEFAULT; + break; + case 'w': + am = AM_WRITE; + om = (OpenMode) (OM_CREATE | OM_TRUNCATE); + break; + case 'a': + am = AM_WRITE; + om = (OpenMode) (OM_CREATE | OM_APPEND); + break; + default: + return false; + } + switch(mode[1]) { + case '+': + am = (AccessMode) (AM_WRITE | AM_READ); + break; + case 0: + break; + default: + return false; + } + return true; +} + + +#if defined(FS_FREESTANDING_FUNCTIONS) + +/* +TODO: move these functions to public API: +*/ +File open(const char* path, const char* mode); +File open(String& path, const char* mode); + +Dir openDir(const char* path); +Dir openDir(String& path); + +template<> +bool mount(FS& fs, const char* mountPoint); +/* +*/ + + +struct MountEntry { + FSImplPtr fs; + String path; + MountEntry* next; +}; + +static MountEntry* s_mounted = nullptr; + +template<> +bool mount(FS& fs, const char* mountPoint) { + FSImplPtr p = fs._impl; + if (!p || !p->mount()) { + DEBUGV("FSImpl mount failed\r\n"); + return false; + } + + !make sure mountPoint has trailing '/' here + + MountEntry* entry = new MountEntry; + entry->fs = p; + entry->path = mountPoint; + entry->next = s_mounted; + s_mounted = entry; + return true; +} + + +/* + iterate over MountEntries and look for the ones which match the path +*/ +File open(const char* path, const char* mode) { + OpenMode om; + AccessMode am; + if (!sflags(mode, om, am)) { + DEBUGV("open: invalid mode `%s`\r\n", mode); + return File(); + } + + for (MountEntry* entry = s_mounted; entry; entry = entry->next) { + size_t offset = entry->path.length(); + if (strstr(path, entry->path.c_str())) { + File result = entry->fs->open(path + offset); + if (result) + return result; + } + } + + return File(); +} + +File open(const String& path, const char* mode) { + return FS::open(path.c_str(), mode); +} + +Dir openDir(const String& path) { + return openDir(path.c_str()); +} +#endif diff --git a/hardware/esp8266com/esp8266/cores/esp8266/FS.h b/hardware/esp8266com/esp8266/cores/esp8266/FS.h new file mode 100644 index 0000000000..ce6d220baf --- /dev/null +++ b/hardware/esp8266com/esp8266/cores/esp8266/FS.h @@ -0,0 +1,110 @@ +/* + FS.h - file system wrapper + Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef FS_H +#define FS_H + +#include +#include + +class File; +class Dir; + +class FileImpl; +typedef std::shared_ptr FileImplPtr; +class FSImpl; +typedef std::shared_ptr FSImplPtr; +class DirImpl; +typedef std::shared_ptr DirImplPtr; + +template +bool mount(Tfs& fs, const char* mountPoint); + +enum SeekMode { + SeekSet = 0, + SeekCur = 1, + SeekEnd = 2 +}; + +class File : public Stream +{ +public: + File(FileImplPtr p = FileImplPtr()) : _p(p) {} + + // Print methods: + size_t write(uint8_t) override; + size_t write(const uint8_t *buf, size_t size) override; + + // Stream methods: + int available() override; + int read() override; + int peek() override; + void flush() override; + + size_t read(uint8_t* buf, size_t size); + bool seek(uint32_t pos, SeekMode mode); + size_t position() const; + size_t size() const; + void close(); + operator bool() const; + +protected: + FileImplPtr _p; +}; + +class Dir { +public: + Dir(DirImplPtr impl = DirImplPtr()): _impl(impl) { } + + File openFile(const char* mode); + String fileName(); + bool next(); + +protected: + DirImplPtr _impl; +}; + +class FS +{ +public: + FS(FSImplPtr impl) : _impl(impl) { } + + bool begin(); + + File open(const char* path, const char* mode); + File open(const String& path, const char* mode); + + Dir openDir(const char* path); + Dir openDir(const String& path); + + bool remove(const char* path); + bool remove(const String& path); + + bool rename(const char* pathFrom, const char* pathTo); + bool rename(const String& pathFrom, const String& pathTo); + +protected: + FSImplPtr _impl; + +}; + +extern FS SPIFFS; + +#endif //FS_H diff --git a/hardware/esp8266com/esp8266/cores/esp8266/FSImpl.h b/hardware/esp8266com/esp8266/cores/esp8266/FSImpl.h new file mode 100644 index 0000000000..8977e64c0a --- /dev/null +++ b/hardware/esp8266com/esp8266/cores/esp8266/FSImpl.h @@ -0,0 +1,70 @@ +/* + FSImpl.h - base file system interface + Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef FSIMPL_H +#define FSIMPL_H + +#include +#include + +class FileImpl { +public: + virtual ~FileImpl() { } + virtual size_t write(const uint8_t *buf, size_t size) = 0; + virtual size_t read(uint8_t* buf, size_t size) = 0; + virtual void flush() = 0; + virtual bool seek(uint32_t pos, SeekMode mode) = 0; + virtual size_t position() const = 0; + virtual size_t size() const = 0; + virtual void close() = 0; +}; + +enum OpenMode { + OM_DEFAULT = 0, + OM_CREATE = 1, + OM_APPEND = 2, + OM_TRUNCATE = 4 +}; + +enum AccessMode { + AM_READ = 1, + AM_WRITE = 2, + AM_RW = AM_READ | AM_WRITE +}; + +class DirImpl { +public: + virtual ~DirImpl() { } + virtual FileImplPtr openFile(OpenMode openMode, AccessMode accessMode) = 0; + virtual const char* fileName() = 0; + virtual bool next() = 0; +}; + +class FSImpl { +public: + virtual bool begin() = 0; + virtual FileImplPtr open(const char* path, OpenMode openMode, AccessMode accessMode) = 0; + virtual DirImplPtr openDir(const char* path) = 0; + virtual bool rename(const char* pathFrom, const char* pathTo) = 0; + virtual bool remove(const char* path) = 0; + +}; + + +#endif //FSIMPL_H diff --git a/hardware/esp8266com/esp8266/cores/esp8266/HardwareSerial.cpp b/hardware/esp8266com/esp8266/cores/esp8266/HardwareSerial.cpp index 493561a24e..2489503976 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/HardwareSerial.cpp +++ b/hardware/esp8266com/esp8266/cores/esp8266/HardwareSerial.cpp @@ -1,9 +1,9 @@ -/* +/* HardwareSerial.cpp - esp8266 UART support Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -559,7 +559,7 @@ int HardwareSerial::available(void) { } if (!result) { - optimistic_yield(); + optimistic_yield(USD(_uart->uart_nr) / 128); } return result; diff --git a/hardware/esp8266com/esp8266/cores/esp8266/WString.h b/hardware/esp8266com/esp8266/cores/esp8266/WString.h index 531fc88c8f..4c502bfe54 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/WString.h +++ b/hardware/esp8266com/esp8266/cores/esp8266/WString.h @@ -35,8 +35,8 @@ class StringSumHelper; // an abstract class used as a means to proide a unique pointer type // but really has no body class __FlashStringHelper; -#define F(string_literal) (reinterpret_cast(PSTR(string_literal))) - +#define FPSTR(pstr_pointer) (reinterpret_cast(pstr_pointer)) +#define F(string_literal) (FPSTR(PSTR(string_literal))) // The string class class String { diff --git a/hardware/esp8266com/esp8266/cores/esp8266/cont.S b/hardware/esp8266com/esp8266/cores/esp8266/cont.S index 4c85142468..06ad2a74cc 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/cont.S +++ b/hardware/esp8266com/esp8266/cores/esp8266/cont.S @@ -1,8 +1,8 @@ -/* +/* cont.S - continuations support for Xtensa call0 ABI Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -18,106 +18,109 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - .text - .align 4 - .literal_position - .global cont_yield - .type cont_yield, @function + .text + .align 4 + .literal_position + .global cont_yield + .type cont_yield, @function cont_yield: - /* a1: sp */ - /* a2: void* cont_ctx */ - /* adjust stack and save registers */ - addi a1, a1, -24 - s32i a12, a1, 0 - s32i a13, a1, 4 - s32i a14, a1, 8 - s32i a15, a1, 12 - s32i a0, a1, 16 - s32i a2, a1, 20 + /* a1: sp */ + /* a2: void* cont_ctx */ + /* adjust stack and save registers */ + addi a1, a1, -24 + s32i a12, a1, 0 + s32i a13, a1, 4 + s32i a14, a1, 8 + s32i a15, a1, 12 + s32i a0, a1, 16 + s32i a2, a1, 20 - /* &cont_continue -> cont_ctx.pc_yield */ - movi a3, cont_continue - s32i a3, a2, 8 - /* sp -> cont_ctx.sp_yield */ - s32i a1, a2, 12 + /* &cont_continue -> cont_ctx.pc_yield */ + movi a3, cont_continue + s32i a3, a2, 8 + /* sp -> cont_ctx.sp_yield */ + s32i a1, a2, 12 - /* a0 <- cont_ctx.pc_ret */ - l32i a0, a2, 0 - /* sp <- cont_ctx.sp_ret */ - l32i a1, a2, 4 - jx a0 + /* a0 <- cont_ctx.pc_ret */ + l32i a0, a2, 0 + /* sp <- cont_ctx.sp_ret */ + l32i a1, a2, 4 + jx a0 cont_continue: - l32i a12, a1, 0 - l32i a13, a1, 4 - l32i a14, a1, 8 - l32i a15, a1, 12 - l32i a0, a1, 16 - l32i a2, a1, 20 - addi a1, a1, 24 - ret - .size cont_yield, . - cont_yield + l32i a12, a1, 0 + l32i a13, a1, 4 + l32i a14, a1, 8 + l32i a15, a1, 12 + l32i a0, a1, 16 + l32i a2, a1, 20 + addi a1, a1, 24 + ret + .size cont_yield, . - cont_yield //////////////////////////////////////////////////// - .text - .align 4 - .literal_position - .global cont_run - .type cont_run, @function + .text + .align 4 + .literal_position + .global cont_run + .type cont_run, @function cont_run: - /* a1: sp */ - /* a2: void* cont_ctx */ - /* a3: void (*pfn) */ + /* a1: sp */ + /* a2: void* cont_ctx */ + /* a3: void (*pfn) */ - /* adjust stack and save registers */ - addi a1, a1, -20 - s32i a12, a1, 0 - s32i a13, a1, 4 - s32i a14, a1, 8 - s32i a15, a1, 12 - s32i a0, a1, 16 + /* adjust stack and save registers */ + addi a1, a1, -20 + s32i a12, a1, 0 + s32i a13, a1, 4 + s32i a14, a1, 8 + s32i a15, a1, 12 + s32i a0, a1, 16 - /* cont_ret -> a4 -> cont_ctx.pc_ret*/ - movi a4, cont_ret - s32i a4, a2, 0 - /* sp -> cont_ctx.sp_ret */ - s32i a1, a2, 4 + /* cont_ret -> a4 -> cont_ctx.pc_ret*/ + movi a4, cont_ret + s32i a4, a2, 0 + /* sp -> cont_ctx.sp_ret */ + s32i a1, a2, 4 - /* if cont_ctx.pc_yield != 0, goto cont_resume */ - l32i a4, a2, 8 - bnez a4, cont_resume - /* else */ - /* set new stack*/ - l32i a1, a2, 16; - /* goto pfn */ - movi a0, cont_norm - jx a3 + /* if cont_ctx.pc_yield != 0, goto cont_resume */ + l32i a4, a2, 8 + bnez a4, cont_resume + /* else */ + /* set new stack*/ + l32i a1, a2, 16; + /* goto pfn */ + movi a0, cont_norm + jx a3 cont_resume: - /* a1 <- cont_ctx.sp_yield */ - l32i a1, a2, 12 - /* reset yield flag, 0 -> cont_ctx.pc_yield */ - movi a3, 0 - s32i a3, a2, 8 - /* jump to saved cont_ctx.pc_yield */ - movi a0, cont_ret - jx a4 + /* a1 <- cont_ctx.sp_yield */ + l32i a1, a2, 12 + /* reset yield flag, 0 -> cont_ctx.pc_yield */ + movi a3, 0 + s32i a3, a2, 8 + /* jump to saved cont_ctx.pc_yield */ + movi a0, cont_ret + jx a4 cont_norm: - /* calculate pointer to cont_ctx.struct_start from sp */ - l32i a2, a1, 4 - /* sp <- cont_ctx.sp_ret */ - l32i a1, a2, 4 + /* calculate pointer to cont_ctx.struct_start from sp */ + l32i a2, a1, 4 + /* sp <- cont_ctx.sp_ret */ + l32i a1, a2, 4 + /* 0 -> cont_ctx.pc_ret */ + movi a4, 0 + s32i a4, a2, 0 cont_ret: - /* restore registers */ - l32i a12, a1, 0 - l32i a13, a1, 4 - l32i a14, a1, 8 - l32i a15, a1, 12 - l32i a0, a1, 16 - /* adjust stack and return */ - addi a1, a1, 20 - ret - .size cont_run, . - cont_run + /* restore registers */ + l32i a12, a1, 0 + l32i a13, a1, 4 + l32i a14, a1, 8 + l32i a15, a1, 12 + l32i a0, a1, 16 + /* adjust stack and return */ + addi a1, a1, 20 + ret + .size cont_run, . - cont_run diff --git a/hardware/esp8266com/esp8266/cores/esp8266/cont.h b/hardware/esp8266com/esp8266/cores/esp8266/cont.h index 5da60f4978..4fe742f44a 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/cont.h +++ b/hardware/esp8266com/esp8266/cores/esp8266/cont.h @@ -1,8 +1,8 @@ -/* +/* cont.h - continuations support for Xtensa call0 ABI Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -21,6 +21,8 @@ #ifndef CONT_H_ #define CONT_H_ +#include + #ifndef CONT_STACKSIZE #define CONT_STACKSIZE 4096 #endif @@ -58,4 +60,8 @@ void cont_yield(cont_t*); // return 1 if guard bytes were overwritten. int cont_check(cont_t* cont); +// Check if yield() may be called. Returns true if we are running inside +// continuation stack +bool cont_can_yield(cont_t* cont); + #endif /* CONT_H_ */ diff --git a/hardware/esp8266com/esp8266/cores/esp8266/cont_util.c b/hardware/esp8266com/esp8266/cores/esp8266/cont_util.c index 590cd36ad1..9af49edcb3 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/cont_util.c +++ b/hardware/esp8266com/esp8266/cores/esp8266/cont_util.c @@ -1,8 +1,8 @@ -/* +/* cont_util.s - continuations support for Xtensa call0 ABI Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -19,6 +19,9 @@ */ #include "cont.h" +#include +#include "ets_sys.h" + #define CONT_STACKGUARD 0xfeefeffe @@ -34,3 +37,8 @@ int cont_check(cont_t* cont) { return 0; } + +bool cont_can_yield(cont_t* cont) { + return !ETS_INTR_WITHINISR() && + cont->pc_ret != 0 && cont->pc_yield == 0; +} diff --git a/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_main.cpp b/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_main.cpp index ca78055696..67c3f38024 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_main.cpp +++ b/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_main.cpp @@ -1,10 +1,10 @@ -/* +/* main.cpp - platform initialization and context switching emulation Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -64,16 +64,16 @@ extern void (*__init_array_end)(void); cont_t g_cont __attribute__ ((aligned (16))); static os_event_t g_loop_queue[LOOP_QUEUE_SIZE]; -static uint32_t g_micros_at_last_task_yield; +static uint32_t g_micros_at_task_start; extern "C" void abort() { - while(1) { - } + do { + *((int*)0) = 0; + } while(true); } extern "C" void esp_yield() { - g_micros_at_last_task_yield = system_get_time(); cont_yield(&g_cont); } @@ -82,16 +82,22 @@ extern "C" void esp_schedule() { } extern "C" void __yield() { - esp_schedule(); - esp_yield(); + if (cont_can_yield(&g_cont)) { + esp_schedule(); + esp_yield(); + } + else { + abort(); + } } + extern "C" void yield(void) __attribute__ ((weak, alias("__yield"))); -extern "C" void optimistic_yield(void) { - if (!ETS_INTR_WITHINISR() && - (system_get_time() - g_micros_at_last_task_yield) > OPTIMISTIC_YIELD_TIME_US) +extern "C" void optimistic_yield(uint32_t interval_us) { + if (cont_can_yield(&g_cont) && + (system_get_time() - g_micros_at_task_start) > interval_us) { - __yield(); + yield(); } } @@ -107,10 +113,10 @@ static void loop_wrapper() { } static void loop_task(os_event_t *events) { - g_micros_at_last_task_yield = system_get_time(); + g_micros_at_task_start = system_get_time(); cont_run(&g_cont, &loop_wrapper); if(cont_check(&g_cont) != 0) { - ets_printf("\r\nheap collided with sketch stack\r\n"); + ets_printf("\r\nsketch stack overflow detected\r\n"); abort(); } } @@ -127,13 +133,11 @@ void init_done() { esp_schedule(); } -extern "C" { -void user_init(void) { - struct rst_info *rtc_info_ptr = system_get_rst_info(); +extern "C" void user_init(void) { + struct rst_info *rtc_info_ptr = system_get_rst_info(); memcpy((void *) &resetInfo, (void *) rtc_info_ptr, sizeof(resetInfo)); - uart_div_modify(0, UART_CLK_FREQ / (115200)); init(); @@ -143,10 +147,8 @@ void user_init(void) { cont_init(&g_cont); system_os_task(loop_task, - LOOP_TASK_PRIORITY, g_loop_queue, - LOOP_QUEUE_SIZE); + LOOP_TASK_PRIORITY, g_loop_queue, + LOOP_QUEUE_SIZE); system_init_done_cb(&init_done); } -} - diff --git a/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_phy.c b/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_phy.c index cc624ade08..a4a189384c 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_phy.c +++ b/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_phy.c @@ -1,9 +1,9 @@ -/* +/* phy.c - ESP8266 PHY initialization data Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -24,7 +24,7 @@ #include #include -static uint8_t phy_init_data[128] = +static uint8_t phy_init_data[128] = { [0] = 5, // Reserved, do not change [1] = 0, // Reserved, do not change @@ -157,28 +157,28 @@ static uint8_t phy_init_data[128] = // lp_rf_stg10 // the attenuation of RF gain stage 0 and 1, - // 0xf: 0db, - // 0xe: -2.5db, - // 0xd: -6db, - // 0x9: -8.5db, - // 0xc: -11.5db, - // 0x8: -14db, - // 0x4: -17.5, + // 0xf: 0db, + // 0xe: -2.5db, + // 0xd: -6db, + // 0x9: -8.5db, + // 0xc: -11.5db, + // 0x8: -14db, + // 0x4: -17.5, // 0x0: -23 [94] = 0x00, // lp_bb_att_ext // the attenuation of BB gain, - // 0: 0db, - // 1: -0.25db, - // 2: -0.5db, - // 3: -0.75db, - // 4: -1db, - // 5: -1.25db, - // 6: -1.5db, - // 7: -1.75db, - // 8: -2db + // 0: 0db, + // 1: -0.25db, + // 2: -0.5db, + // 3: -0.75db, + // 4: -1db, + // 5: -1.25db, + // 6: -1.5db, + // 7: -1.75db, + // 8: -2db // max valve is 24(-6db) [95] = 0, @@ -198,17 +198,17 @@ static uint8_t phy_init_data[128] = // vdd33_const // the voltage of PA_VDD // x=0xff: it can measure VDD33, - // 18<=x<=36: use input voltage, + // 18<=x<=36: use input voltage, // the value is voltage*10, 33 is 3.3V, 30 is 3.0V, // x<18 or x>36: default voltage is 3.3V // // the value of this byte depend from the TOUT pin usage (1 or 2): - // 1) + // 1) // analogRead function (system_adc_read()): // is only available when wire TOUT pin17 to external circuitry, Input Voltage Range restricted to 0 ~ 1.0V. // For this function the vdd33_const must be set as real power voltage of VDD3P3 pin 3 and 4 // The range of operating voltage of ESP8266 is 1.8V~3.6V,the unit of vdd33_const is 0.1V,so effective value range of vdd33_const is [18,36] - // 2) + // 2) // getVcc function (system_get_vdd33): // is only available when TOUT pin17 is suspended (floating), this function measure the power voltage of VDD3P3 pin 3 and 4 // For this function the vdd33_const must be set to 255 (0xFF). @@ -220,7 +220,7 @@ static uint8_t phy_init_data[128] = // freq_correct_en // bit[0]:0->do not correct frequency offset, 1->correct frequency offset. // bit[1]:0->bbpll is 168M, it can correct + and - frequency offset, 1->bbpll is 160M, it only can correct + frequency offset - // bit[2]:0->auto measure frequency offset and correct it, 1->use 113 byte force_freq_offset to correct frequency offset. + // bit[2]:0->auto measure frequency offset and correct it, 1->use 113 byte force_freq_offset to correct frequency offset. // 0: do not correct frequency offset. // 1: auto measure frequency offset and correct it, bbpll is 168M, it can correct + and - frequency offset. // 3: auto measure frequency offset and correct it, bbpll is 160M, it only can correct + frequency offset. @@ -239,26 +239,30 @@ extern int __wrap_register_chipv6_phy(uint8_t* unused) { return __real_register_chipv6_phy(phy_init_data); } - -void user_rf_pre_init() { - // *((volatile uint32_t*) 0x60000710) = 0; - - volatile uint32_t* rtc_reg = (volatile uint32_t*) 0x60001000; - rtc_reg[30] = 0; - - system_set_os_print(0); -} - -extern int __get_rf_mode() __attribute__((weak)); -extern int __get_rf_mode() +extern int __get_rf_mode(void) __attribute__((weak)); +extern int __get_rf_mode(void) { return 0; // default mode } -extern int __get_adc_mode() __attribute__((weak)); -extern int __get_adc_mode() +extern int __get_adc_mode(void) __attribute__((weak)); +extern int __get_adc_mode(void) { return 33; // default ADC mode } +extern void __run_user_rf_pre_init(void) __attribute__((weak)); +extern void __run_user_rf_pre_init(void) +{ + return; // default do noting +} + +void user_rf_pre_init() { + // *((volatile uint32_t*) 0x60000710) = 0; + volatile uint32_t* rtc_reg = (volatile uint32_t*) 0x60001000; + rtc_reg[30] = 0; + + system_set_os_print(0); + __run_user_rf_pre_init(); +} diff --git a/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_postmortem.c b/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_postmortem.c index 2d749108a4..f5ede6c764 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_postmortem.c +++ b/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_postmortem.c @@ -30,7 +30,10 @@ extern void __real_system_restart_local(); extern cont_t g_cont; + +static void uart_write_char_d(char c); static void uart0_write_char_d(char c); +static void uart1_write_char_d(char c); static void print_stack(uint32_t start, uint32_t end); static void print_pcs(uint32_t start, uint32_t end); @@ -46,7 +49,7 @@ void __wrap_system_restart_local() { return; } - ets_install_putc1(&uart0_write_char_d); + ets_install_putc1(&uart_write_char_d); if (rst_info.reason == REASON_EXCEPTION_RST) { ets_printf("\nException (%d):\nepc1=0x%08x epc2=0x%08x epc3=0x%08x excvaddr=0x%08x depc=0x%08x\n", @@ -120,6 +123,11 @@ static void print_pcs(uint32_t start, uint32_t end) { ets_printf("<<> USTXC) & 0xff) >= 0x7e) { } @@ -128,3 +136,12 @@ void uart0_write_char_d(char c) { } USF(0) = c; } + +void uart1_write_char_d(char c) { + while (((USS(1) >> USTXC) & 0xff) >= 0x7e) { } + + if (c == '\n') { + USF(1) = '\r'; + } + USF(1) = c; +} diff --git a/hardware/esp8266com/esp8266/cores/esp8266/interrupts.h b/hardware/esp8266com/esp8266/cores/esp8266/interrupts.h new file mode 100644 index 0000000000..d86f89b1f1 --- /dev/null +++ b/hardware/esp8266com/esp8266/cores/esp8266/interrupts.h @@ -0,0 +1,30 @@ +#ifndef INTERRUPTS_H +#define INTERRUPTS_H + +#include +#include +extern "C" { +#include "c_types.h" +#include "ets_sys.h" +} + + +#define xt_disable_interrupts(state, level) __asm__ __volatile__("rsil %0," __STRINGIFY(level) : "=a" (state)) +#define xt_enable_interrupts(state) __asm__ __volatile__("wsr %0,ps; isync" :: "a" (state) : "memory") + +class InterruptLock { +public: + InterruptLock() { + xt_disable_interrupts(_state, 15); + } + + ~InterruptLock() { + xt_enable_interrupts(_state); + } + +protected: + uint32_t _state; +}; + + +#endif //INTERRUPTS_H diff --git a/hardware/esp8266com/esp8266/cores/esp8266/pgmspace.cpp b/hardware/esp8266com/esp8266/cores/esp8266/pgmspace.cpp index b91dd59128..7f03de4022 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/pgmspace.cpp +++ b/hardware/esp8266com/esp8266/cores/esp8266/pgmspace.cpp @@ -20,13 +20,13 @@ #include #include "pgmspace.h" -size_t strnlen_P(const char* s, size_t size) { +size_t strnlen_P(PGM_P s, size_t size) { const char* cp; for (cp = s; size != 0 && pgm_read_byte(cp) != '\0'; cp++, size--); return (size_t) (cp - s); } -void* memcpy_P(void* dest, const void* src, size_t count) { +void* memcpy_P(void* dest, PGM_VOID_P src, size_t count) { const uint8_t* read = reinterpret_cast(src); uint8_t* write = reinterpret_cast(dest); @@ -39,7 +39,83 @@ void* memcpy_P(void* dest, const void* src, size_t count) { return dest; } -char* strncpy_P(char* dest, const char* src, size_t size) { +int memcmp_P(const void* buf1, PGM_VOID_P buf2P, size_t size) { + int result = 0; + const uint8_t* read1 = (const uint8_t*)buf1; + const uint8_t* read2 = (const uint8_t*)buf2P; + + while (size > 0) { + uint8_t ch2 = pgm_read_byte(read2); + uint8_t ch1 = *read1; + if (ch1 != ch2) { + result = (int)(ch1)-(int)(ch2); + break; + } + + read1++; + read2++; + size--; + } + + return result; +} + +void* memccpy_P(void* dest, PGM_VOID_P src, int c, size_t count) { + uint8_t* read = (uint8_t*)src; + uint8_t* write = (uint8_t*)dest; + void* result = NULL; + + while (count > 0) { + uint8_t ch = pgm_read_byte(read++); + *write++ = ch; + count--; + if (c == ch) { + return write; // the value after the found c + } + } + + return result; +} + +void* memmem_P(const void* buf, size_t bufSize, PGM_VOID_P findP, size_t findPSize) { + const uint8_t* read = (const uint8_t*)buf; + const uint8_t* find = (uint8_t*)findP; + uint8_t first = pgm_read_byte(find++); + + findPSize--; + + while (bufSize > 0) { + if (*read == first) { + size_t findSize = findPSize; + const uint8_t* tag = read + 1; + size_t tagBufSize = bufSize - 1; + const uint8_t* findTag = find; + + while (tagBufSize > 0 && findSize > 0) { + uint8_t ch = pgm_read_byte(findTag++); + if (ch != *tag) { + bufSize--; + read++; + break; + } + findSize--; + tagBufSize--; + tag++; + } + if (findSize == 0) { + return (void*)read; + } + } + else { + bufSize--; + read++; + } + } + return NULL; +} + + +char* strncpy_P(char* dest, PGM_P src, size_t size) { const char* read = src; char* write = dest; char ch = '.'; @@ -53,7 +129,7 @@ char* strncpy_P(char* dest, const char* src, size_t size) { return dest; } -char* strncat_P(char* dest, const char* src, size_t size) { +char* strncat_P(char* dest, PGM_P src, size_t size) { char* write = dest; while (*write != '\0') @@ -80,7 +156,7 @@ char* strncat_P(char* dest, const char* src, size_t size) { return dest; } -int strncmp_P(const char* str1, const char* str2P, size_t size) { +int strncmp_P(const char* str1, PGM_P str2P, size_t size) { int result = 0; while (size > 0) @@ -99,7 +175,7 @@ int strncmp_P(const char* str1, const char* str2P, size_t size) { return result; } -int strncasecmp_P(const char* str1, const char* str2P, size_t size) { +int strncasecmp_P(const char* str1, PGM_P str2P, size_t size) { int result = 0; while (size > 0) @@ -118,7 +194,7 @@ int strncasecmp_P(const char* str1, const char* str2P, size_t size) { return result; } -int printf_P(const char* formatP, ...) { +int printf_P(PGM_P formatP, ...) { int ret; va_list arglist; va_start(arglist, formatP); @@ -135,7 +211,7 @@ int printf_P(const char* formatP, ...) { return ret; } -int sprintf_P(char* str, const char* formatP, ...) { +int sprintf_P(char* str, PGM_P formatP, ...) { int ret; va_list arglist; va_start(arglist, formatP); @@ -146,7 +222,7 @@ int sprintf_P(char* str, const char* formatP, ...) { return ret; } -int snprintf_P(char* str, size_t strSize, const char* formatP, ...) { +int snprintf_P(char* str, size_t strSize, PGM_P formatP, ...) { int ret; va_list arglist; va_start(arglist, formatP); @@ -157,7 +233,7 @@ int snprintf_P(char* str, size_t strSize, const char* formatP, ...) { return ret; } -int vsnprintf_P(char* str, size_t strSize, const char* formatP, va_list ap) { +int vsnprintf_P(char* str, size_t strSize, PGM_P formatP, va_list ap) { int ret; size_t fmtLen = strlen_P(formatP); diff --git a/hardware/esp8266com/esp8266/cores/esp8266/pgmspace.h b/hardware/esp8266com/esp8266/cores/esp8266/pgmspace.h index 7669058be3..4ee5995573 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/pgmspace.h +++ b/hardware/esp8266com/esp8266/cores/esp8266/pgmspace.h @@ -32,27 +32,40 @@ typedef uint32_t prog_uint32_t; #define SIZE_IRRELEVANT 0x7fffffff -void* memcpy_P(void* dest, const void* src, size_t count); - -char* strncpy_P(char* dest, const char* src, size_t size); +// memchr_P and memrchr_P are not implemented due to danger in its use, and +// how uninteresting their use is +// since its a flash string, you should already know where the char is within it, +// further, it could return a pointer into the flash memory that is not 32bit aligned +// which could cause an exception if read +// PGM_VOID_P memchr_P(PGM_VOID_P bufP, int c, size_t count); +// PGM_VOID_P memrchr_P(PGM_VOID_P bufP, int c, size_t count); + +int memcmp_P(const void* buf1, PGM_VOID_P buf2P, size_t size); +// memccpy_P is only valid when used with pointers to 8bit data, due to size aligned pointers +// and endianess of the values greater than 8bit, matching c may return invalid aligned pointers +void* memccpy_P(void* dest, PGM_VOID_P src, int c, size_t count); +void* memmem_P(const void* buf, size_t bufSize, PGM_VOID_P findP, size_t findPSize); +void* memcpy_P(void* dest, PGM_VOID_P src, size_t count); + +char* strncpy_P(char* dest, PGM_P src, size_t size); #define strcpy_P(dest, src) strncpy_P((dest), (src), SIZE_IRRELEVANT) -char* strncat_P(char* dest, const char* src, size_t size); +char* strncat_P(char* dest, PGM_P src, size_t size); #define strcat_P(dest, src) strncat_P((dest), (src), SIZE_IRRELEVANT) -int strncmp_P(const char* str1, const char* str2P, size_t size); +int strncmp_P(const char* str1, PGM_P str2P, size_t size); #define strcmp_P(str1, str2P) strncmp_P((str1), (str2P), SIZE_IRRELEVANT) -int strncasecmp_P(const char* str1, const char* str2P, size_t size); +int strncasecmp_P(const char* str1, PGM_P str2P, size_t size); #define strcasecmp_P(str1, str2P) strncasecmp_P((str1), (str2P), SIZE_IRRELEVANT) -size_t strnlen_P(const char *s, size_t size); +size_t strnlen_P(PGM_P s, size_t size); #define strlen_P(strP) strnlen_P((strP), SIZE_IRRELEVANT) -int printf_P(const char *formatP, ...) __attribute__ ((format (printf, 1, 2))); -int sprintf_P(char *str, const char *formatP, ...) __attribute__((format(printf, 2, 3))); -int snprintf_P(char *str, size_t strSize, const char *formatP, ...) __attribute__((format(printf, 3, 4))); -int vsnprintf_P(char *str, size_t strSize, const char *formatP, va_list ap) __attribute__ ((format (printf, 3, 0))); +int printf_P(PGM_P formatP, ...) __attribute__((format(printf, 1, 2))); +int sprintf_P(char *str, PGM_P formatP, ...) __attribute__((format(printf, 2, 3))); +int snprintf_P(char *str, size_t strSize, PGM_P formatP, ...) __attribute__((format(printf, 3, 4))); +int vsnprintf_P(char *str, size_t strSize, PGM_P formatP, va_list ap) __attribute__((format(printf, 3, 0))); // flash memory must be read using 32 bit aligned addresses else a processor // exception will be triggered diff --git a/hardware/esp8266com/esp8266/cores/esp8266/spiffs/spiffs_config.h b/hardware/esp8266com/esp8266/cores/esp8266/spiffs/spiffs_config.h index fa4bbd7b1b..10497c819d 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/spiffs/spiffs_config.h +++ b/hardware/esp8266com/esp8266/cores/esp8266/spiffs/spiffs_config.h @@ -8,15 +8,16 @@ #ifndef SPIFFS_CONFIG_H_ #define SPIFFS_CONFIG_H_ -#include "mem.h" +#include +#include +#include #include "c_types.h" -#include "stddef.h" -#include "osapi.h" #include "ets_sys.h" -#define c_memcpy os_memcpy -#define c_printf os_printf -#define c_memset os_memset + +#define c_memcpy memcpy +#define c_printf ets_printf +#define c_memset memset typedef signed short file_t; typedef int32_t s32_t; @@ -65,7 +66,7 @@ typedef uint8_t u8_t; // for filedescriptor and cache buffers. Once decided for a configuration, // this can be disabled to reduce flash. #ifndef SPIFFS_BUFFER_HELP -#define SPIFFS_BUFFER_HELP 0 +#define SPIFFS_BUFFER_HELP 1 #endif // Enables/disable memory read caching of nucleus file system operations. @@ -140,7 +141,7 @@ typedef uint8_t u8_t; // not on mount point. If not, SPIFFS_format must be called prior to mounting // again. #ifndef SPIFFS_USE_MAGIC -#define SPIFFS_USE_MAGIC (0) +#define SPIFFS_USE_MAGIC (1) #endif // SPIFFS_LOCK and SPIFFS_UNLOCK protects spiffs from reentrancy on api level diff --git a/hardware/esp8266com/esp8266/cores/esp8266/spiffs/spiffs_gc.c b/hardware/esp8266com/esp8266/cores/esp8266/spiffs/spiffs_gc.c index 87e4faf90a..fff659e3a7 100644 --- a/hardware/esp8266com/esp8266/cores/esp8266/spiffs/spiffs_gc.c +++ b/hardware/esp8266com/esp8266/cores/esp8266/spiffs/spiffs_gc.c @@ -556,4 +556,3 @@ s32_t spiffs_gc_clean(spiffs *fs, spiffs_block_ix bix) { return res; } - diff --git a/hardware/esp8266com/esp8266/cores/esp8266/spiffs_api.cpp b/hardware/esp8266com/esp8266/cores/esp8266/spiffs_api.cpp new file mode 100644 index 0000000000..d63a1bcd40 --- /dev/null +++ b/hardware/esp8266com/esp8266/cores/esp8266/spiffs_api.cpp @@ -0,0 +1,374 @@ +/* + spiffs_api.cpp - file system wrapper for SPIFFS + Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. + + This code was influenced by NodeMCU and Sming libraries, and first version of + Arduino wrapper written by Hristo Gochkov. + + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "FS.h" +#include "FSImpl.h" +#include "spiffs/spiffs.h" +#include "debug.h" + +extern "C" { +#include "c_types.h" +#include "spi_flash.h" +} + +extern int32_t spiffs_hal_write(uint32_t addr, uint32_t size, uint8_t *src); +extern int32_t spiffs_hal_erase(uint32_t addr, uint32_t size); +extern int32_t spiffs_hal_read(uint32_t addr, uint32_t size, uint8_t *dst); + +int getSpiffsMode(OpenMode openMode, AccessMode accessMode); + +class SPIFFSFileImpl; +class SPIFFSDirImpl; + +class SPIFFSImpl : public FSImpl { +public: + SPIFFSImpl(uint32_t start, uint32_t size, uint32_t pageSize, uint32_t blockSize, uint32_t maxOpenFds) + : _fs({0}) + , _start(start) + , _size(size) + , _pageSize(pageSize) + , _blockSize(blockSize) + , _maxOpenFds(maxOpenFds) + { + } + + FileImplPtr open(const char* path, OpenMode openMode, AccessMode accessMode) override; + + DirImplPtr openDir(const char* path) override; + + bool rename(const char* pathFrom, const char* pathTo) override { + char tmpNameFrom[SPIFFS_OBJ_NAME_LEN]; + strlcpy(tmpNameFrom, pathFrom, sizeof(tmpNameFrom)); + char tmpNameTo[SPIFFS_OBJ_NAME_LEN]; + strlcpy(tmpNameTo, pathTo, sizeof(tmpNameTo)); + auto rc = SPIFFS_rename(&_fs, tmpNameFrom, tmpNameTo); + if (rc != SPIFFS_OK) { + DEBUGV("SPIFFS_rename: rc=%d, from=`%s`, to=`%s`\r\n", rc, + pathFrom, pathTo); + return false; + } + return true; + } + + bool remove(const char* path) override { + char tmpName[SPIFFS_OBJ_NAME_LEN]; + strlcpy(tmpName, path, sizeof(tmpName)); + auto rc = SPIFFS_remove(&_fs, tmpName); + if (rc != SPIFFS_OK) { + DEBUGV("SPIFFS_remove: rc=%d path=`%s`\r\n", rc, path); + return false; + } + return true; + } + + bool begin() override { + if (SPIFFS_mounted(&_fs) != 0) { + return true; + } + if (_tryMount()) { + return true; + } + auto rc = SPIFFS_format(&_fs); + if (rc != SPIFFS_OK) { + DEBUGV("SPIFFS_format: rc=%d, err=%d\r\n", rc, _fs.err_code); + return false; + } + return _tryMount(); + } + +protected: + friend class SPIFFSFileImpl; + friend class SPIFFSDirImpl; + + spiffs* getFs() { + return &_fs; + } + + bool _tryMount() { + spiffs_config config = {0}; + + config.hal_read_f = &spiffs_hal_read; + config.hal_write_f = &spiffs_hal_write; + config.hal_erase_f = &spiffs_hal_erase; + config.phys_size = _size; + config.phys_addr = _start; + config.phys_erase_block = SPI_FLASH_SEC_SIZE; + config.log_block_size = _blockSize; + config.log_page_size = _pageSize; + + // hack: even though fs is not initialized at this point, + // SPIFFS_buffer_bytes_for_cache uses only fs->config.log_page_size + // suggestion: change SPIFFS_buffer_bytes_for_cache to take + // spiffs_config* instead of spiffs* as an argument + _fs.cfg.log_page_size = config.log_page_size; + + size_t workBufSize = 2 * _pageSize; + size_t fdsBufSize = SPIFFS_buffer_bytes_for_filedescs(&_fs, _maxOpenFds); + size_t cacheBufSize = SPIFFS_buffer_bytes_for_cache(&_fs, _maxOpenFds); + + if (!_workBuf) { + DEBUGV("SPIFFSImpl: allocating %d+%d+%d=%d bytes\r\n", + workBufSize, fdsBufSize, cacheBufSize, + workBufSize + fdsBufSize + cacheBufSize); + _workBuf.reset(new uint8_t[workBufSize]); + _fdsBuf.reset(new uint8_t[fdsBufSize]); + _cacheBuf.reset(new uint8_t[cacheBufSize]); + } + + DEBUGV("SPIFFSImpl: mounting fs @%x, size=%x, block=%x, page=%x\r\n", + _start, _size, _blockSize, _pageSize); + + auto err = SPIFFS_mount(&_fs, &config, _workBuf.get(), + _fdsBuf.get(), fdsBufSize, _cacheBuf.get(), cacheBufSize, + &SPIFFSImpl::_check_cb); + + DEBUGV("SPIFFSImpl: mount rc=%d\r\n", err); + + return err == SPIFFS_OK; + } + + static void _check_cb(spiffs_check_type type, spiffs_check_report report, + uint32_t arg1, uint32_t arg2) { + // TODO: spiffs doesn't pass any context pointer along with _check_cb, + // so we can't do anything useful here other than perhaps + // feeding the watchdog + } + + spiffs _fs; + + uint32_t _start; + uint32_t _size; + uint32_t _pageSize; + uint32_t _blockSize; + uint32_t _maxOpenFds; + + std::unique_ptr _workBuf; + std::unique_ptr _fdsBuf; + std::unique_ptr _cacheBuf; +}; + +#define CHECKFD() while (_fd == 0) { DEBUGV("SPIFFSFileImpl(%d) _fd == 0\r\n", __LINE__); abort(); } + +class SPIFFSFileImpl : public FileImpl { +public: + SPIFFSFileImpl(SPIFFSImpl* fs, spiffs_file fd) + : _fs(fs) + , _fd(fd) + , _stat({0}) + { + CHECKFD(); + auto rc = SPIFFS_fstat(_fs->getFs(), _fd, &_stat); + if (rc != SPIFFS_OK) { + DEBUGV("SPIFFS_fstat rc=%d\r\n", rc); + _stat = {0}; + } + } + + ~SPIFFSFileImpl() override { + close(); + } + + size_t write(const uint8_t *buf, size_t size) override { + CHECKFD(); + + auto result = SPIFFS_write(_fs->getFs(), _fd, (void*) buf, size); + if (result < 0) { + DEBUGV("SPIFFS_write rc=%d\r\n", result); + return 0; + } + + return result; + } + + size_t read(uint8_t* buf, size_t size) override { + CHECKFD(); + + auto result = SPIFFS_read(_fs->getFs(), _fd, (void*) buf, size); + if (result < 0) { + DEBUGV("SPIFFS_read rc=%d\r\n", result); + return 0; + } + + return result; + } + + void flush() override { + CHECKFD(); + + auto rc = SPIFFS_fflush(_fs->getFs(), _fd); + if (rc < 0) { + DEBUGV("SPIFFS_fflush rc=%d\r\n", rc); + } + } + + bool seek(uint32_t pos, SeekMode mode) override { + CHECKFD(); + + auto rc = SPIFFS_lseek(_fs->getFs(), _fd, pos, (int) mode); + if (rc < 0) { + DEBUGV("SPIFFS_lseek rc=%d\r\n", rc); + return false; + } + + return true; + } + + size_t position() const override { + CHECKFD(); + + auto result = SPIFFS_tell(_fs->getFs(), _fd); + if (result < 0) { + DEBUGV("SPIFFS_tell rc=%d\r\n", result); + return 0; + } + + return result; + } + + size_t size() const override { + CHECKFD(); + + return _stat.size; + } + + void close() override { + CHECKFD(); + + SPIFFS_close(_fs->getFs(), _fd); + DEBUGV("SPIFFS_close: fd=%d\r\n", _fd); + } + +protected: + SPIFFSImpl* _fs; + spiffs_file _fd; + spiffs_stat _stat; +}; + +class SPIFFSDirImpl : public DirImpl { +public: + SPIFFSDirImpl(SPIFFSImpl* fs, spiffs_DIR& dir) + : _fs(fs) + , _dir(dir) + , _valid(false) + { + } + + ~SPIFFSDirImpl() override { + SPIFFS_closedir(&_dir); + } + + FileImplPtr openFile(OpenMode openMode, AccessMode accessMode) override { + if (!_valid) { + return FileImplPtr(); + } + int mode = getSpiffsMode(openMode, accessMode); + spiffs_file fd = SPIFFS_open_by_dirent(_fs->getFs(), &_dirent, mode, 0); + if (fd < 0) { + DEBUGV("SPIFFSDirImpl::openFile: fd=%d path=`%s` openMode=%d accessMode=%d err=%d\r\n", + fd, _dirent.name, openMode, accessMode, _fs.err_code); + return FileImplPtr(); + } + return std::make_shared(_fs, fd); + } + + const char* fileName() override { + if (!_valid) + return nullptr; + + return (const char*) _dirent.name; + } + + bool next() override { + spiffs_dirent* result = SPIFFS_readdir(&_dir, &_dirent); + _valid = (result != nullptr); + return _valid; + } + +protected: + SPIFFSImpl* _fs; + spiffs_DIR _dir; + spiffs_dirent _dirent; + bool _valid; +}; + + +FileImplPtr SPIFFSImpl::open(const char* path, OpenMode openMode, AccessMode accessMode) { + int mode = getSpiffsMode(openMode, accessMode); + char tmpName[SPIFFS_OBJ_NAME_LEN]; + strlcpy(tmpName, path, sizeof(tmpName)); + int fd = SPIFFS_open(&_fs, tmpName, mode, 0); + if (fd < 0) { + DEBUGV("SPIFFSImpl::open: fd=%d path=`%s` openMode=%d accessMode=%d err=%d\r\n", + fd, path, openMode, accessMode, _fs.err_code); + return FileImplPtr(); + } + return std::make_shared(this, fd); +} + +DirImplPtr SPIFFSImpl::openDir(const char* path) { + spiffs_DIR dir; + char tmpName[SPIFFS_OBJ_NAME_LEN]; + strlcpy(tmpName, path, sizeof(tmpName)); + spiffs_DIR* result = SPIFFS_opendir(&_fs, tmpName, &dir); + if (!result) { + DEBUGV("SPIFFSImpl::openDir: path=`%s` err=%d\r\n", path, _fs.err_code); + return DirImplPtr(); + } + return std::make_shared(this, dir); +} + +int getSpiffsMode(OpenMode openMode, AccessMode accessMode) { + int mode = 0; + if (openMode & OM_CREATE) { + mode |= SPIFFS_CREAT; + } + if (openMode & OM_APPEND) { + mode |= SPIFFS_APPEND; + } + if (openMode & OM_TRUNCATE) { + mode |= SPIFFS_TRUNC; + } + if (accessMode & AM_READ) { + mode |= SPIFFS_RDONLY; + } + if (accessMode & AM_WRITE) { + mode |= SPIFFS_WRONLY; + } + return mode; +} + +// these symbols should be defined in the linker script for each flash layout +extern "C" uint32_t _SPIFFS_start; +extern "C" uint32_t _SPIFFS_end; +extern "C" uint32_t _SPIFFS_page; +extern "C" uint32_t _SPIFFS_block; + +static SPIFFSImpl s_defaultFs( + (uint32_t) &_SPIFFS_start - 0x40200000, + (uint32_t) (&_SPIFFS_end - &_SPIFFS_start), + (uint32_t) &_SPIFFS_page, + (uint32_t) &_SPIFFS_block, + 5); + +FS SPIFFS = FS(FSImplPtr(&s_defaultFs)); diff --git a/hardware/esp8266com/esp8266/cores/esp8266/spiffs_hal.cpp b/hardware/esp8266com/esp8266/cores/esp8266/spiffs_hal.cpp new file mode 100644 index 0000000000..2719eb6e00 --- /dev/null +++ b/hardware/esp8266com/esp8266/cores/esp8266/spiffs_hal.cpp @@ -0,0 +1,192 @@ +/* + spiffs_hal.cpp - SPI read/write/erase functions for SPIFFS. + Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include "spiffs/spiffs.h" +#include "debug.h" +#include "interrupts.h" + +extern "C" { +#include "c_types.h" +#include "spi_flash.h" +} + +static int spi_flash_read_locked(uint32_t addr, uint32_t* dst, uint32_t size) { + InterruptLock lock; + return spi_flash_read(addr, dst, size); +} + +static int spi_flash_write_locked(uint32_t addr, const uint32_t* src, uint32_t size) { + InterruptLock lock; + return spi_flash_write(addr, (uint32_t*) src, size); +} + +static int spi_flash_erase_sector_locked(uint32_t sector) { + optimistic_yield(10000); + InterruptLock lock; + return spi_flash_erase_sector(sector); +} + + +/* + spi_flash_read function requires flash address to be aligned on word boundary. + We take care of this by reading first and last words separately and memcpy + relevant bytes into result buffer. + +alignment: 012301230123012301230123 +bytes requested: -------***********------ +read directly: --------xxxxxxxx-------- +read pre: ----aaaa---------------- +read post: ----------------bbbb---- +alignedBegin: ^ +alignedEnd: ^ +*/ + +int32_t spiffs_hal_read(uint32_t addr, uint32_t size, uint8_t *dst) { + uint32_t result = SPIFFS_OK; + uint32_t alignedBegin = (addr + 3) & (~3); + uint32_t alignedEnd = (addr + size) & (~3); + + if (addr < alignedBegin) { + uint32_t nb = alignedBegin - addr; + uint32_t tmp; + if (spi_flash_read_locked(alignedBegin - 4, &tmp, 4) != SPI_FLASH_RESULT_OK) { + DEBUGV("_spif_read(%d) addr=%x size=%x ab=%x ae=%x\r\n", + __LINE__, addr, size, alignedBegin, alignedEnd); + return SPIFFS_ERR_INTERNAL; + } + memcpy(dst, &tmp + 4 - nb, nb); + } + + if (alignedEnd != alignedBegin) { + if (spi_flash_read_locked(alignedBegin, (uint32_t*) (dst + alignedBegin - addr), + alignedEnd - alignedBegin) != SPI_FLASH_RESULT_OK) { + DEBUGV("_spif_read(%d) addr=%x size=%x ab=%x ae=%x\r\n", + __LINE__, addr, size, alignedBegin, alignedEnd); + return SPIFFS_ERR_INTERNAL; + } + } + + if (addr + size > alignedEnd) { + uint32_t nb = addr + size - alignedEnd; + uint32_t tmp; + if (spi_flash_read_locked(alignedEnd, &tmp, 4) != SPI_FLASH_RESULT_OK) { + DEBUGV("_spif_read(%d) addr=%x size=%x ab=%x ae=%x\r\n", + __LINE__, addr, size, alignedBegin, alignedEnd); + return SPIFFS_ERR_INTERNAL; + } + + memcpy(dst + size - nb, &tmp, nb); + } + + return result; +} + +/* + Like spi_flash_read, spi_flash_write has a requirement for flash address to be + aligned. However it also requires RAM address to be aligned as it reads data + in 32-bit words. Flash address (mis-)alignment is handled much the same way + as for reads, but for RAM alignment we have to copy data into a temporary + buffer. The size of this buffer is a tradeoff between number of writes required + and amount of stack required. This is chosen to be 512 bytes here, but might + be adjusted in the future if there are good reasons to do so. +*/ + +static const int UNALIGNED_WRITE_BUFFER_SIZE = 512; + +int32_t spiffs_hal_write(uint32_t addr, uint32_t size, uint8_t *src) { + uint32_t alignedBegin = (addr + 3) & (~3); + uint32_t alignedEnd = (addr + size) & (~3); + + if (addr < alignedBegin) { + uint32_t nb = alignedBegin - addr; + uint32_t tmp = 0xffffffff; + memcpy(((uint8_t* )&tmp) + 4 - nb, src, nb); + if (spi_flash_write_locked(alignedBegin - 4, &tmp, 4) != SPI_FLASH_RESULT_OK) { + DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n", + __LINE__, addr, size, alignedBegin, alignedEnd); + return SPIFFS_ERR_INTERNAL; + } + } + + if (alignedEnd != alignedBegin) { + uint32_t* srcLeftover = (uint32_t*) (src + alignedBegin - addr); + uint32_t srcAlign = ((uint32_t) srcLeftover) & 3; + if (!srcAlign) { + if (spi_flash_write_locked(alignedBegin, (uint32_t*) srcLeftover, + alignedEnd - alignedBegin) != SPI_FLASH_RESULT_OK) { + DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n", + __LINE__, addr, size, alignedBegin, alignedEnd); + return SPIFFS_ERR_INTERNAL; + } + } + else { + uint8_t buf[UNALIGNED_WRITE_BUFFER_SIZE]; + for (uint32_t sizeLeft = alignedEnd - alignedBegin; sizeLeft; ) { + size_t willCopy = std::min(sizeLeft, sizeof(buf)); + memcpy(buf, srcLeftover, willCopy); + + if (spi_flash_write_locked(alignedBegin, (uint32_t*) buf, + willCopy) != SPI_FLASH_RESULT_OK) { + DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n", + __LINE__, addr, size, alignedBegin, alignedEnd); + return SPIFFS_ERR_INTERNAL; + } + + sizeLeft -= willCopy; + srcLeftover += willCopy; + alignedBegin += willCopy; + } + } + } + + if (addr + size > alignedEnd) { + uint32_t nb = addr + size - alignedEnd; + uint32_t tmp = 0xffffffff; + memcpy(&tmp, src + size - nb, nb); + + if (spi_flash_write_locked(alignedEnd, &tmp, 4) != SPI_FLASH_RESULT_OK) { + DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n", + __LINE__, addr, size, alignedBegin, alignedEnd); + return SPIFFS_ERR_INTERNAL; + } + } + + return SPIFFS_OK; +} + +int32_t spiffs_hal_erase(uint32_t addr, uint32_t size) { + if ((size & (SPI_FLASH_SEC_SIZE - 1)) != 0 || + (addr & (SPI_FLASH_SEC_SIZE - 1)) != 0) { + DEBUGV("_spif_erase called with addr=%x, size=%d\r\n", addr, size); + abort(); + } + const uint32_t sector = addr / SPI_FLASH_SEC_SIZE; + const uint32_t sectorCount = size / SPI_FLASH_SEC_SIZE; + for (uint32_t i = 0; i < sectorCount; ++i) { + if (spi_flash_erase_sector_locked(sector + i) != 0) { + DEBUGV("_spif_erase addr=%x size=%d i=%d\r\n", addr, size, i); + return SPIFFS_ERR_INTERNAL; + } + } + return SPIFFS_OK; +} diff --git a/hardware/esp8266com/esp8266/doc/boards.md b/hardware/esp8266com/esp8266/doc/boards.md new file mode 100644 index 0000000000..99bb7cb8cb --- /dev/null +++ b/hardware/esp8266com/esp8266/doc/boards.md @@ -0,0 +1,145 @@ +--- +title: Supported Hardware +--- + +- [Adafruit HUZZAH ESP8266 (ESP-12)](#adafruit-huzzah-esp8266-esp-12) +- [NodeMCU 0.9](#nodemcu-0-9) +- [NodeMCU 1.0](#nodemcu-1-0) +- [Olimex MOD-WIFI-ESP8266](#olimex-mod-wifi-esp8266) +- [SparkFun ESP8266 Thing](#sparkfun-esp8266-thing) +- [SweetPea ESP-210](#sweetpea-esp-210) +- [Generic ESP8266 modules](#generic-esp8266-modules) + +### Adafruit HUZZAH ESP8266 (ESP-12) + +*TODO: add notes* + +### NodeMCU 0.9 + +#### Pin mapping + +Pin numbers written on the board itself do not correspond to ESP8266 GPIO pin numbers. Constants are defined to make using this board easier: + +```C++ +static const uint8_t D0 = 16; +static const uint8_t D1 = 5; +static const uint8_t D2 = 4; +static const uint8_t D3 = 0; +static const uint8_t D4 = 2; +static const uint8_t D5 = 14; +static const uint8_t D6 = 12; +static const uint8_t D7 = 13; +static const uint8_t D8 = 15; +static const uint8_t D9 = 3; +static const uint8_t D10 = 1; +``` + +If you want to use NodeMCU pin 5, use D5 for pin number, and it will be translated to 'real' GPIO pin 14. + +### NodeMCU 1.0 + +*TODO: add notes* + +### Olimex MOD-WIFI-ESP8266 + +*TODO: add notes* + +### SparkFun ESP8266 Thing ### + +Product page: https://www.sparkfun.com/products/13231 + +*TODO: add notes* + +### SweetPea ESP-210 + +*TODO: add notes* + +### Generic ESP8266 modules + +These modules come in different form factors and pinouts. See the page at ESP8266 community wiki for more info: +[ESP8266 Module Family](http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family). + +Usually these modules have no bootstapping resistors on board, insufficient decoupling capacitors, no voltage regulator, no reset circuit, and no USB-serial adapter. This makes using them somewhat tricky, compared to development boards which add these features. + +In order to use these modules, make sure to observe the following: + +- **Provide sufficient power to the module.** For stable use of the ESP8266 a power supply with 3.3V and >= 250mA is required. Using the power available from USB to Serial adapter is not recommended, these adapters typically do not supply enough current to run ESP8266 reliably in every situation. An external supply or regulator along with filtering capacitors is preferred. + +- **Connect bootstapping resistors** to GPIO0, GPIO2, GPIO15 according to the schematics below. + +- **Put ESP8266 into bootloader mode** before uploading code. + +### Serial Adapter + +There are many different USB to Serial adapters / boards. + +* Note + - for full upload management you need RTS and DTR + - the chip need to have 3.3V TTL (5V may damage the chip) + - not all board have all pins of the ICs as breakout (check before order) + - CTS and DSR are not useful for upload (they are Inputs) + +* Working ICs + - FT232RL + - CP2102 + - CH340G + - maybe others (drop a comment) + +### Minimal Hardware Setup for Bootloading and Usage + +ESPxx Hardware + +| PIN | Resistor | Serial Adapter | +| ------------- | -------- | -------------- | +| VCC | | VCC (3.3V) | +| GND | | GND | +| TX or GPIO2* | | RX | +| RX | | TX | +| GPIO0 | PullUp | DTR | +| Reset* | PullUp | RTS | +| GPIO15* | PullDown | | +| CH_PD | PullUp | | + +* Note + - GPIO15 is also named MTDO + - Reset is also named RSBT or REST (adding PullUp improves the stability of the Module) + - GPIO2 is alternative TX for the boot loader mode + - **Directly connecting a pin to VCC or GND is not a substitute for a PullUp or PullDown resistor, doing this can break upload management and the serial console, instability has also been noted in some cases.** + +### ESP to Serial +![ESP to Serial](https://raw.githubusercontent.com/Links2004/Arduino/esp8266/docs/ESP_to_serial.png) + +#### Minimal Hardware Setup for Bootloading only ## +ESPxx Hardware + +| PIN | Resistor | Serial Adapter | +| ------------- | -------- | --------------- | +| VCC | | VCC (3.3V) | +| GND | | GND | +| TX or GPIO2 | | RX | +| RX | | TX | +| GPIO0 | | GND | +| Reset | | RTS* | +| GPIO15 | PullDown | | +| CH_PD | PullUp | | + +* Note + - if no RTS is used a manual power toggle is needed + +#### Minimal Hardware Setup for Running only ## + +ESPxx Hardware + +| PIN | Resistor | Power supply | +| ------------- | -------- | --------------- | +| VCC | | VCC (3.3V) | +| GND | | GND | +| GPIO0 | PullUp | | +| GPIO15 | PullDown | | +| CH_PD | PullUp | | + +### Minimal +![ESP min](https://raw.githubusercontent.com/Links2004/Arduino/esp8266/docs/ESP_min.png) + +### Improved Stability +![ESP improved stability](https://raw.githubusercontent.com/Links2004/Arduino/esp8266/docs/ESP_improved_stability.png) diff --git a/hardware/esp8266com/esp8266/doc/changes.md b/hardware/esp8266com/esp8266/doc/changes.md index 22da473e83..f9731095e0 100644 --- a/hardware/esp8266com/esp8266/doc/changes.md +++ b/hardware/esp8266com/esp8266/doc/changes.md @@ -1,26 +1,78 @@ -# Change log +--- +title: Change log +--- + +*Current release* + +### Core + +- Add first batch of file system APIs +- Allow user to run code in user_rf_pre_init + + +### Libraries -## Current version +- ESP8266WebServer: support for sending of PROGMEM strings +- ESP8266WiFi: fix mode selection (#529) + +### Tools + +- Update SDK to 1.2.0_15_07_13_p4 + +--- +## 1.6.5-947-g39819f0 +July 23, 2015 + +Package link: `http://arduino.esp8266.com/versions/1.6.5-947-g39819f0/package_esp8266com_index.json`. ### Core -- Updated I2C library to better handle repeated start for certain devices. +- I2C library updated to better handle repeated start for certain devices, + improved waveforms, higher frequencies for 160MHz core clock, fix case where + using different pins would not work with libs calling begin internally. +- Add Adafruit HUZZAH board +- Add SparkFun Thing board +- Add SweetPea ESP-210 board +- Add eboot bootloader +- Timer0 support +- Add PWM range and frequency control +- Add ESP.eraseConfig method +- Fix pin change interrupt handling (#322) +- Add SLC and I2S register definitions +- Fix math functions calling themselves recursively (#233, #354) +- Print stack on exception and soft WDT reset +- Add Updater class +- Remove implementations of WDT-related functions +- Provide selection between A0 and VCC (#443, #338) ### Libraries -- ESP8266WebServer: add gzip streaming, fix sendContent behaviour, +- ESP8266WebServer: add gzip streaming, fix sendContent behaviour, add setContentSize method. - ESP8266WiFi: add BSSID, channel, isHidden methods, fix AP/STA mode selection (#28). +- Better handling of WiFi disconnect (#231) +- Add API to set the beginning of local ports range for WiFiClient. +- Add RSSI function +- Add function to get the MAC / BSSID as String +- Servo library support +- Add ESP8266WiFiMesh library +- Add ESP8266SSDP library +- Add DNS-SD support to ESP8266mDNS library ### Tools -- SDK updated to 1.1.0 (#306) +- Update SDK to v1.2.0_15_07_03 +- Better sketch size reporting (#314) +- Update esptool to 0.4.5 +--- ## 1.6.4-673-g8cd3697 May 22, 2015 +Package link: `http://arduino.esp8266.com/versions/1.6.4-673-g8cd3697/package_esp8266com_index.json`. + ### Tools - Add 32-bit Linux toolchain. @@ -31,8 +83,8 @@ May 22, 2015 - Better connection handling in ESP8266WebServer. The server now sends Content-Length and Connection: close headers, then waits for the client to disconnect. By not closing the connection - actively, server avoids TIME_WAIT TCP state, and TCP stack is able to - release the memory immediately, without waiting for 2xMSL period. + actively, server avoids TIME_WAIT TCP state, and TCP stack is able to + release the memory immediately, without waiting for 2xMSL period. If the client doesn't disconnect in 2000ms, the server closes the connection actively. - Add Hash library, which has a function to calculate SHA1 hash. @@ -45,4 +97,3 @@ May 22, 2015 May 19, 2015 - Initial release of Boards Manager package for ESP8266 platform. - diff --git a/hardware/esp8266com/esp8266/doc/esp12.svg b/hardware/esp8266com/esp8266/doc/esp12.svg new file mode 100644 index 0000000000..107073dfae --- /dev/null +++ b/hardware/esp8266com/esp8266/doc/esp12.svg @@ -0,0 +1,1187 @@ + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + RESET + + + + RESET + + + + + ADC + + + + GPIO16 + + + + + D16~ + + + + CHPD + + + + D14~ + + + + D12~ + + + + D13~ + + + + D15~ + + + + RESET + + + + VCC + + + + GND + + + + D2~ + + + + D0~ + + + + D4~ + + + + D5~ + + + + D3~ + + + + D1~ + + + + TX0 + + + + RX0 + + + + RX0* + + + + TX0* + + + + TX1 + + + + SDA + + + + SCL + + + + SS + + + + MISO + + + + MOSI + + + + SCK + + ESP-12 + + diff --git a/hardware/esp8266com/esp8266/doc/reference.md b/hardware/esp8266com/esp8266/doc/reference.md new file mode 100644 index 0000000000..fd556756a6 --- /dev/null +++ b/hardware/esp8266com/esp8266/doc/reference.md @@ -0,0 +1,239 @@ +--- +title: Reference +--- + +## Digital IO + +Pin numbers in Arduino correspond directly to the ESP8266 GPIO pin numbers. `pinMode`, `digitalRead`, and `digitalWrite` functions work as usual, so to read GPIO2, call `digitalRead(2)`. + +Digital pins 0—15 can be `INPUT`, `OUTPUT`, or `INPUT_PULLUP`. +Pin 16 can be `INPUT`, `OUTPUT` or `INPUT_PULLDOWN_16`. At startup, pins are configured as `INPUT`. + +Pins may also serve other functions, like Serial, I2C, SPI. These functions are normally activated by the corresponding library. The diagram below shows pin mapping for the popular ESP-12 module. + +![Pin Functions](https://cdn.rawgit.com/esp8266/Arduino/doc-update/hardware/esp8266com/esp8266/doc/esp12.svg) + +Digital pins 6—11 are not shown on this diagram because they are used to connect flash memory chip on most modules. Trying to use these pins as IOs will likely cause the program to crash. + +Note that some boards and modules (ESP-12ED, NodeMCU 1.0) also break out pins 9 and 11. These may be used as IO if flash chip works in DIO mode (as opposed to QIO, which is the default one). + +Pin interrupts are supported through `attachInterrupt`, `detachInterrupt` functions. +Interrupts may be attached to any GPIO pin, except GPIO16. Standard Arduino interrupt +types are supported: `CHANGE`, `RISING`, `FALLING`. + +## Analog input + +ESP8266 has a single ADC channel available to users. It may be used either to read voltage at ADC pin, or to read module supply voltage (VCC). + +To read external voltage applied to ADC pin, use `analogRead(A0)`. Input voltage range is 0 — 1.0V. + +To read VCC voltage, ADC pin must be kept unconnected. Additionally, the following line has to be added to the sketch: + +```c++ +ADC_MODE(ADC_VCC); +``` + +This line has to appear outside of any functions, for instance right after the `#include ` lines of your sketch. + +## Analog output + +`analogWrite(pin, value)` enables software PWM on the given pin. PWM may be used on pins 0 to 16. +Call `analogWrite(pin, 0)` to disable PWM on the pin. `value` may be in range from 0 to `PWMRANGE`, which is equal to 1023 by default. PWM range may be changed by calling `analogWriteRange(new_range)`. + +PWM frequency is 1kHz by default. Call `analogWriteFreq(new_frequency)` to change the frequency. + +## Timing and delays +`millis()` and `micros()` return the number of milliseconds and microseconds elapsed after reset, respectively. + +`delay(ms)` pauses the sketch for a given number of milliseconds and allows WiFi and TCP/IP tasks to run. +`delayMicroseconds(us)` pauses for a given number of microseconds. + +Remember that there is a lot of code that needs to run on the chip besides the sketch +when WiFi is connected. WiFi and TCP/IP libraries get a chance to handle any pending +events each time the `loop()` function completes, OR when `delay` is called. +If you have a loop somewhere in your sketch that takes a lot of time (>50ms) without +calling `delay`, you might consider adding a call to `delay` function to keep the WiFi +stack running smoothly. + +There is also a `yield()` function which is equivalent to `delay(0)`. The `delayMicroseconds` +function, on the other hand, does not yield to other tasks, so using it for delays +more than 20 milliseconds is not recommended. + +## Serial + +`Serial` object works much the same way as on a regular Arduino. Apart from hardware FIFO (128 bytes for TX and RX) HardwareSerial has additional 256-byte TX and RX buffers. Both transmit and receive is interrupt-driven. Write and read functions only block the sketch execution when the respective FIFO/buffers are full/empty. + +`Serial` uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15 (TX) and GPIO13 (RX) by calling `Serial.swap()` after `Serial.begin`. Calling `swap` again maps UART0 back to GPIO1 and GPIO3. + +`Serial1` uses UART1, TX pin is GPIO2. UART1 can not be used to receive data because normally it's RX pin is occupied for flash chip connection. To use `Serial1`, call `Serial1.begin(baudrate)`. + +By default the diagnostic output from WiFi libraries is disabled when you call `Serial.begin`. To enable debug output again, call `Serial.setDebugOutput(true)`. To redirect debug output to `Serial1` instead, call `Serial1.setDebugOutput(true)`. + +You also need to use `Serial.setDebugOutput(true)` to enable output from `printf()` function. + +Both `Serial` and `Serial1` objects support 5, 6, 7, 8 data bits, odd (O), even (E), and no (N) parity, and 1 or 2 stop bits. To set the desired mode, call `Serial.begin(baudrate, SERIAL_8N1)`, `Serial.begin(baudrate, SERIAL_6E2)`, etc. + +## Progmem + +The Program memory features work much the same way as on a regular Arduino; placing read only data and strings in read only memory and freeing heap for your application. +The important difference is that on the ESP8266 the literal strings are not pooled. This means that the same literal string defined inside a `F("")` and/or `PSTR("")` will take up space for each instance in the code. So you will need to manage the duplicate strings yourself. + +There is one additional helper macro to make it easier to pass ```const PROGMEM``` strings to methods that take a ```__FlashStringHelper``` called ```FPSTR()```. The use of this will help make it easier to pool strings. +Not pooling strings... + +```c++ +String response1; +response1 += F("http:"); +... +String response2; +response2 += F("http:"); +``` + +using FPSTR would become... + +```c++ +const char HTTP[] PROGMEM = "http:"; +... +{ + String response1; + response1 += FPSTR(HTTP); + ... + String response2; + response2 += FPSTR(HTTP); +} +``` + + +## WiFi(ESP8266WiFi library) + +This is mostly similar to WiFi shield library. Differences include: + +- `WiFi.mode(m)`: set mode to `WIFI_AP`, `WIFI_STA`, or `WIFI_AP_STA`. +- call `WiFi.softAP(ssid)` to set up an open network +- call `WiFi.softAP(ssid, password)` to set up a WPA2-PSK network (password should be at least 8 characters) +- `WiFi.macAddress(mac)` is for STA, `WiFi.softAPmacAddress(mac)` is for AP. +- `WiFi.localIP()` is for STA, `WiFi.softAPIP()` is for AP. +- `WiFi.RSSI()` doesn't work +- `WiFi.printDiag(Serial)` will print out some diagnostic info +- `WiFiUDP` class supports sending and receiving multicast packets on STA interface. +When sending a multicast packet, replace `udp.beginPacket(addr, port)` with +`udp.beginPacketMulticast(addr, port, WiFi.localIP())`. +When listening to multicast packets, replace `udp.begin(port)` with +`udp.beginMulticast(WiFi.localIP(), multicast_ip_addr, port)`. +You can use `udp.destinationIP()` to tell whether the packet received was +sent to the multicast or unicast address. +Also note that multicast doesn't work on softAP interface. + +`WiFiServer`, `WiFiClient`, and `WiFiUDP` behave mostly the same way as with WiFi shield library. +Four samples are provided for this library. +You can see more commands here: [http://www.arduino.cc/en/Reference/WiFi](http://www.arduino.cc/en/Reference/WiFi) + +## Ticker + +Library for calling functions repeatedly with a certain period. Two examples included. + +It is currently not recommended to do blocking IO operations (network, serial, file) from Ticker +callback functions. Instead, set a flag inside the ticker callback and check for that flag inside the loop function. + +## EEPROM + +This is a bit different from standard EEPROM class. You need to call `EEPROM.begin(size)` +before you start reading or writing, size being the number of bytes you want to use. +Size can be anywhere between 4 and 4096 bytes. + +`EEPROM.write` does not write to flash immediately, instead you must call `EEPROM.commit()` +whenever you wish to save changes to flash. `EEPROM.end()` will also commit, and will +release the RAM copy of EEPROM contents. + +EEPROM library uses one sector of flash located at 0x7b000 for storage. + +Three examples included. + +## I2C (Wire library) + +Wire library currently supports master mode up to approximately 450KHz. +Before using I2C, pins for SDA and SCL need to be set by calling +`Wire.begin(int sda, int scl)`, i.e. `Wire.begin(0, 2)` on ESP-01, +else they default to pins 4(SDA) and 5(SCL). + +## SPI + +SPI library supports the entire Arduino SPI API including transactions, including setting phase (CPHA). +Setting the Clock polarity (CPOL) is not supported, yet (SPI_MODE2 and SPI_MODE3 not working). + +## ESP-specific APIs + +APIs related to deep sleep and watchdog timer are available in the `ESP` object, only available in Alpha version. + +`ESP.deepSleep(microseconds, mode)` will put the chip into deep sleep. `mode` is one of `WAKE_RF_DEFAULT`, `WAKE_RFCAL`, `WAKE_NO_RFCAL`, `WAKE_RF_DISABLED`. (GPIO16 needs to be tied to RST to wake from deepSleep.) + +`ESP.restart()` restarts the CPU. + +`ESP.getFreeHeap()` returns the free heap size. + +`ESP.getChipId()` returns the ESP8266 chip ID as a 32-bit integer. + +Several APIs may be used to get flash chip info: + +`ESP.getFlashChipId()` returns the flash chip ID as a 32-bit integer. + +`ESP.getFlashChipSize()` returns the flash chip size, in bytes, as seen by the SDK (may be less than actual size). + +`ESP.getFlashChipSpeed(void)` returns the flash chip frequency, in Hz. + +`ESP.getCycleCount()` returns the cpu instruction cycle count since start as an unsigned 32-bit. This is useful for accurate timing of very short actions like bit banging. + +`ESP.getVcc()` may be used to measure supply voltage. ESP needs to reconfigure the ADC +at startup in order for this feature to be available. Add the following line to the top +of your sketch to use `getVcc`: + +```c++ +ADC_MODE(ADC_VCC); +``` + +TOUT pin has to be disconnected in this mode. + +Note that by default ADC is configured to read from TOUT pin using `analogRead(A0)`, and +`ESP.getVCC()` is not available. + +## OneWire (from https://www.pjrc.com/teensy/td_libs_OneWire.html) + +Library was adapted to work with ESP8266 by including register definitions into OneWire.h +Note that if you already have OneWire library in your Arduino/libraries folder, it will be used +instead of the one that comes with this package. + +## mDNS and DNS-SD responder (ESP8266mDNS library) + +Allows the sketch to respond to multicast DNS queries for domain names like "foo.local", and DNS-SD (service dicovery) queries. +Currently the library only works on STA interface, AP interface is not supported. +See attached example for details. + +## SSDP responder (ESP8266SSDP) + +SSDP is another service discovery protocol, supported on Windows out of the box. See attached example for reference. + +## DNS server (DNSServer library) + +Implements a simple DNS server that can be used in both STA and AP modes. The DNS server currently supports only one domain (for all other domains it will reply with NXDOMAIN or custom status code). With it clients can open a web server running on ESP8266 using a domain name, not an IP address. +See attached example for details. + +## Servo + +This library exposes the ability to control RC (hobby) servo motors. It will support upto 24 servos on any available output pin. By defualt the first 12 servos will use Timer0 and currently this will not interfere with any other support. Servo counts above 12 will use Timer1 and features that use it will be effected. +While many RC servo motors will accept the 3.3V IO data pin from a ESP8266, most will not be able to run off 3.3v and will require another power source that matches their specifications. Make sure to connect the grounds between the ESP8266 and the servo motor power supply. + +## Other libraries (not included with the IDE) + +Libraries that don't rely on low-level access to AVR registers should work well. Here are a few libraries that were verified to work: + +- [arduinoWebSockets](https://github.com/Links2004/arduinoWebSockets) - WebSocket Server and Client compatible with ESP8266 (RFC6455) +- [aREST](https://github.com/marcoschwartz/aREST) REST API handler library. +- [Blynk](https://github.com/blynkkk/blynk-library) - easy IoT framework for Makers (check out the [Kickstarter page](http://tiny.cc/blynk-kick)). +- [DallasTemperature](https://github.com/milesburton/Arduino-Temperature-Control-Library.git) +- [DHT-sensor-library](https://github.com/adafruit/DHT-sensor-library) - Arduino library for the DHT11/DHT22 temperature and humidity sensors. Download latest v1.1.1 library and no changes are necessary. Older versions should initialize DHT as follows: `DHT dht(DHTPIN, DHTTYPE, 15)` +- [NeoPixel](https://github.com/adafruit/Adafruit_NeoPixel) - Adafruit's NeoPixel library, now with support for the ESP8266 (use version 1.0.2 or higher from Arduino's library manager). +- [NeoPixelBus](https://github.com/Makuna/NeoPixelBus) - Arduino NeoPixel library compatible with ESP8266. Use the "NeoPixelAnimator" branch for ESP8266 to get HSL color support and more. +- [PubSubClient](https://github.com/Imroy/pubsubclient) MQTT library by @Imroy. +- [RTC](https://github.com/Makuna/Rtc) - Arduino Library for Ds1307 & Ds3231 compatible with ESP8266. +- [Souliss, Smart Home](https://github.com/souliss/souliss) - Framework for Smart Home based on Arduino, Android and openHAB. +- [ST7735](https://github.com/nzmichaelh/Adafruit-ST7735-Library) - Adafruit's ST7735 library modified to be compatible with ESP8266. Just make sure to modify the pins in the examples as they are still AVR specific. diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino b/hardware/esp8266com/esp8266/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino index a1f55a8480..6b34e6cfe0 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino +++ b/hardware/esp8266com/esp8266/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino @@ -1,5 +1,4 @@ #include -#include #include #include @@ -12,11 +11,11 @@ void setup() { Serial.begin(115200); Serial.println(); Serial.println("Starting WiFi..."); - + WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if(WiFi.waitForConnectResult() == WL_CONNECTED){ - + Serial.printf("Starting HTTP...\n"); HTTP.on("/index.html", HTTP_GET, [](){ HTTP.send(200, "text/plain", "Hello World!"); @@ -25,7 +24,7 @@ void setup() { SSDP.schema(HTTP.client()); }); HTTP.begin(); - + Serial.printf("Starting SSDP...\n"); SSDP.setSchemaURL("description.xml"); SSDP.setHTTPPort(80); @@ -38,7 +37,7 @@ void setup() { SSDP.setManufacturer("Royal Philips Electronics"); SSDP.setManufacturerURL("http://www.philips.com"); SSDP.begin(); - + Serial.printf("Ready!\n"); } else { Serial.printf("WiFi Failed\n"); diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino b/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino index 88a2093a58..c62cadfd60 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino +++ b/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino @@ -1,9 +1,9 @@ -/* +/* SDWebServer - Example WebServer with SD Card backend for esp8266 Copyright (c) 2015 Hristo Gochkov. All rights reserved. This file is part of the ESP8266WebServer library for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -23,7 +23,7 @@ File extensions with more than 3 charecters are not supported by the SD Library File Names longer than 8 charecters will be truncated by the SD library, so keep filenames shorter index.htm is the default index (works on subfolders as well) - + upload the contents of SdRoot to the root of the SDcard and access the editor by going to http://esp8266sd.local/edit */ @@ -38,9 +38,8 @@ const char* ssid = "**********"; const char* password = "**********"; -const char* hostname = "esp8266sd"; +const char* host = "esp8266sd"; -MDNSResponder mdns; ESP8266WebServer server(80); static bool hasSD = false; @@ -62,7 +61,7 @@ void returnFail(String msg) { bool loadFromSdCard(String path){ String dataType = "text/plain"; if(path.endsWith("/")) path += "index.htm"; - + if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf(".")); else if(path.endsWith(".htm")) dataType = "text/html"; else if(path.endsWith(".css")) dataType = "text/css"; @@ -74,7 +73,7 @@ bool loadFromSdCard(String path){ else if(path.endsWith(".xml")) dataType = "text/xml"; else if(path.endsWith(".pdf")) dataType = "application/pdf"; else if(path.endsWith(".zip")) dataType = "application/zip"; - + File dataFile = SD.open(path.c_str()); if(dataFile.isDirectory()){ path += "/index.htm"; @@ -84,9 +83,9 @@ bool loadFromSdCard(String path){ if (!dataFile) return false; - + if (server.hasArg("download")) dataType = "application/octet-stream"; - + if (server.streamFile(dataFile, dataType) != dataFile.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); } @@ -152,7 +151,7 @@ void handleDelete(){ void handleCreate(){ if(server.args() == 0) return returnFail("BAD ARGS"); String path = server.arg(0); - if(path == "/" || SD.exists((char *)path.c_str())) { + if(path == "/" || SD.exists((char *)path.c_str())) { returnFail("BAD PATH"); return; } @@ -183,7 +182,7 @@ void printDirectory() { server.setContentLength(CONTENT_LENGTH_UNKNOWN); server.send(200, "text/json", ""); WiFiClient client = server.client(); - + server.sendContent("["); for (int cnt = 0; true; ++cnt) { File entry = dir.openNextFile(); @@ -244,25 +243,26 @@ void setup(void){ } DBG_OUTPUT_PORT.print("Connected! IP address: "); DBG_OUTPUT_PORT.println(WiFi.localIP()); - - if (mdns.begin(hostname, WiFi.localIP())) { + + if (MDNS.begin(host)) { + MDNS.addService("http", "tcp", 80); DBG_OUTPUT_PORT.println("MDNS responder started"); DBG_OUTPUT_PORT.print("You can now connect to http://"); - DBG_OUTPUT_PORT.print(hostname); + DBG_OUTPUT_PORT.print(host); DBG_OUTPUT_PORT.println(".local"); } - - + + server.on("/list", HTTP_GET, printDirectory); server.on("/edit", HTTP_DELETE, handleDelete); server.on("/edit", HTTP_PUT, handleCreate); server.on("/edit", HTTP_POST, [](){ returnOK(); }); server.onNotFound(handleNotFound); server.onFileUpload(handleFileUpload); - + server.begin(); DBG_OUTPUT_PORT.println("HTTP server started"); - + if (SD.begin(SS)){ DBG_OUTPUT_PORT.println("SD Card initialized."); hasSD = true; diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/src/ESP8266WebServer.cpp b/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/src/ESP8266WebServer.cpp index 4a0fbd3f51..cf0121388a 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/src/ESP8266WebServer.cpp +++ b/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/src/ESP8266WebServer.cpp @@ -129,30 +129,51 @@ void ESP8266WebServer::sendHeader(const String& name, const String& value, bool } } + +void ESP8266WebServer::_prepareHeader(String& response, int code, const char* content_type, size_t contentLength) { + response = "HTTP/1.1 "; + response += String(code); + response += " "; + response += _responseCodeToString(code); + response += "\r\n"; + + if (!content_type) + content_type = "text/html"; + + sendHeader("Content-Type", content_type, true); + if (_contentLength != CONTENT_LENGTH_UNKNOWN && _contentLength != CONTENT_LENGTH_NOT_SET) { + sendHeader("Content-Length", String(_contentLength).c_str()); + } + else if (contentLength > 0){ + sendHeader("Content-Length", String(contentLength).c_str()); + } + sendHeader("Connection", "close"); + sendHeader("Access-Control-Allow-Origin", "*"); + + response += _responseHeaders; + response += "\r\n"; + _responseHeaders = String(); +} + void ESP8266WebServer::send(int code, const char* content_type, const String& content) { - String response = "HTTP/1.1 "; - response += String(code); - response += " "; - response += _responseCodeToString(code); - response += "\r\n"; - - if (!content_type) - content_type = "text/html"; - - sendHeader("Content-Type", content_type, true); - if (_contentLength != CONTENT_LENGTH_UNKNOWN && _contentLength != CONTENT_LENGTH_NOT_SET) { - sendHeader("Content-Length", String(_contentLength).c_str()); - } else if(content.length() > 0){ - sendHeader("Content-Length", String(content.length()).c_str()); - } - sendHeader("Connection", "close"); - sendHeader("Access-Control-Allow-Origin", "*"); - - response += _responseHeaders; - response += "\r\n"; - response += content; - _responseHeaders = String(); - sendContent(response); + String header; + _prepareHeader(header, code, content_type, content.length()); + sendContent(header); + + sendContent(content); +} + +void ESP8266WebServer::send_P(int code, PGM_P content_type, PGM_P content) { + size_t contentLength = 0; + + if (content != NULL) { + contentLength = strlen_P(content); + } + + String header; + _prepareHeader(header, code, String(FPSTR(content_type)).c_str(), contentLength); + sendContent(header); + sendContent_P(content); } void ESP8266WebServer::send(int code, char* content_type, const String& content) { @@ -178,6 +199,34 @@ void ESP8266WebServer::sendContent(const String& content) { } } +void ESP8266WebServer::sendContent_P(PGM_P content) { + char contentUnit[HTTP_DOWNLOAD_UNIT_SIZE + 1]; + + contentUnit[HTTP_DOWNLOAD_UNIT_SIZE] = '\0'; + + while (content != NULL) { + size_t contentUnitLen; + PGM_P contentNext; + + // due to the memccpy signature, lots of casts are needed + contentNext = (PGM_P)memccpy_P((void*)contentUnit, (PGM_VOID_P)content, 0, HTTP_DOWNLOAD_UNIT_SIZE); + + if (contentNext == NULL) { + // no terminator, more data available + content += HTTP_DOWNLOAD_UNIT_SIZE; + contentUnitLen = HTTP_DOWNLOAD_UNIT_SIZE; + } + else { + // reached terminator + contentUnitLen = contentNext - content; + content = NULL; + } + + // write is so overloaded, had to use the cast to get it pick the right one + _currentClient.write((const char*)contentUnit, contentUnitLen); + } +} + String ESP8266WebServer::arg(const char* name) { for (int i = 0; i < _currentArgCount; ++i) { if (_currentArgs[i].key == name) diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/src/ESP8266WebServer.h b/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/src/ESP8266WebServer.h index 888e36b4a9..bf538c3e0d 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/src/ESP8266WebServer.h +++ b/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/src/ESP8266WebServer.h @@ -80,10 +80,12 @@ class ESP8266WebServer void send(int code, const char* content_type = NULL, const String& content = String("")); void send(int code, char* content_type, const String& content); void send(int code, const String& content_type, const String& content); + void send_P(int code, PGM_P content_type, PGM_P content); void setContentLength(size_t contentLength) { _contentLength = contentLength; } void sendHeader(const String& name, const String& value, bool first = false); void sendContent(const String& content); + void sendContent_P(PGM_P content); template size_t streamFile(T &file, const String& contentType){ setContentLength(file.size()); @@ -104,7 +106,8 @@ template size_t streamFile(T &file, const String& contentType){ void _parseForm(WiFiClient& client, String boundary, uint32_t len); void _uploadWriteByte(uint8_t b); uint8_t _uploadReadByte(WiFiClient& client); - + void _prepareHeader(String& response, int code, const char* content_type, size_t contentLength); + struct RequestHandler; struct RequestArgument { String key; diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFi.cpp b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFi.cpp index 57af3f0faa..5400f02d9c 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFi.cpp +++ b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFi.cpp @@ -1,9 +1,9 @@ -/* +/* ESP8266WiFi.cpp - WiFi library for esp8266 Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -55,6 +55,30 @@ void ESP8266WiFiClass::mode(WiFiMode m) if(wifi_get_opmode() == (uint8)m) { return; } + + if((m & WIFI_AP)) { + _useApMode = true; + } else { + _useApMode = false; + } + + if((m & WIFI_STA)) { + _useClientMode = true; + } else { + _useClientMode = false; + } + + ETS_UART_INTR_DISABLE(); + wifi_set_opmode(m); + ETS_UART_INTR_ENABLE(); +} + +void ESP8266WiFiClass::_mode(WiFiMode m) +{ + if(wifi_get_opmode() == (uint8)m) { + return; + } + ETS_UART_INTR_DISABLE(); wifi_set_opmode(m); ETS_UART_INTR_ENABLE(); @@ -69,10 +93,10 @@ int ESP8266WiFiClass::begin(const char* ssid, const char *passphrase, int32_t ch if(_useApMode) { // turn on AP+STA mode - mode(WIFI_AP_STA); + _mode(WIFI_AP_STA); } else { // turn on STA mode - mode(WIFI_STA); + _mode(WIFI_STA); } if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) { @@ -134,7 +158,7 @@ void ESP8266WiFiClass::config(IPAddress local_ip, IPAddress gateway, IPAddress s wifi_station_dhcpc_stop(); wifi_set_ip_info(STATION_IF, &info); - + _useStaticIp = true; } @@ -152,10 +176,35 @@ void ESP8266WiFiClass::config(IPAddress local_ip, IPAddress gateway, IPAddress s ip_addr_t d; d.addr = static_cast(dns); dns_setserver(0,&d); - + _useStaticIp = true; } +int ESP8266WiFiClass::softAPdisconnect(bool wifioff) +{ + struct softap_config conf; + *conf.ssid = 0; + *conf.password = 0; + ETS_UART_INTR_DISABLE(); + wifi_softap_set_config(&conf); + wifi_station_disconnect(); + ETS_UART_INTR_ENABLE(); + + if(wifioff) { + _useApMode = false; + + if( _useClientMode) { + // turn on STA + _mode(WIFI_STA); + } else { + // turn wifi off + _mode(WIFI_OFF); + } + } + + return 0; +} + int ESP8266WiFiClass::disconnect(bool wifioff) { struct station_config conf; @@ -171,10 +220,10 @@ int ESP8266WiFiClass::disconnect(bool wifioff) if(_useApMode) { // turn on AP - mode(WIFI_AP); + _mode(WIFI_AP); } else { // turn wifi off - mode(WIFI_OFF); + _mode(WIFI_OFF); } } @@ -185,17 +234,17 @@ void ESP8266WiFiClass::softAP(const char* ssid) { softAP(ssid, 0); } - + void ESP8266WiFiClass::softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden) { _useApMode = true; if(_useClientMode) { // turn on AP+STA mode - mode(WIFI_AP_STA); + _mode(WIFI_AP_STA); } else { // turn on STA mode - mode(WIFI_AP); + _mode(WIFI_AP); } if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) { @@ -265,7 +314,7 @@ uint8_t* ESP8266WiFiClass::softAPmacAddress(uint8_t* mac) wifi_get_macaddr(SOFTAP_IF, mac); return mac; } - + String ESP8266WiFiClass::softAPmacAddress(void) { uint8_t mac[6]; @@ -287,7 +336,7 @@ IPAddress ESP8266WiFiClass::softAPIP() { struct ip_info ip; wifi_get_ip_info(SOFTAP_IF, &ip); - return IPAddress(ip.ip.addr); + return IPAddress(ip.ip.addr); } IPAddress ESP8266WiFiClass::subnetMask() @@ -351,7 +400,7 @@ void ESP8266WiFiClass::_scanDone(void* result, int status) } else { - + int i = 0; bss_info_head_t* head = reinterpret_cast(result); @@ -417,10 +466,10 @@ int8_t ESP8266WiFiClass::scanNetworks(bool async) if(_useApMode) { // turn on AP+STA mode - mode(WIFI_AP_STA); + _mode(WIFI_AP_STA); } else { // turn on STA mode - mode(WIFI_STA); + _mode(WIFI_STA); } int status = wifi_station_get_connect_status(); @@ -428,7 +477,7 @@ int8_t ESP8266WiFiClass::scanNetworks(bool async) { disconnect(); } - + scanDelete(); struct scan_config config; @@ -592,7 +641,7 @@ int ESP8266WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) esp_yield(); // will return here when dns_found_callback fires } - + return (aResult != 0) ? 1 : 0; } @@ -645,15 +694,15 @@ bool ESP8266WiFiClass::beginWPSConfig(void) { if(_useApMode) { // turn on AP+STA mode - mode(WIFI_AP_STA); + _mode(WIFI_AP_STA); } else { // turn on STA mode - mode(WIFI_STA); + _mode(WIFI_STA); } disconnect(); - DEBUGV("wps begin: %d\n", wps_type); + DEBUGV("wps begin\n"); if(!wifi_wps_disable()) { DEBUGV("wps disable faild\n"); @@ -693,16 +742,16 @@ void ESP8266WiFiClass::beginSmartConfig() if(_useApMode) { // turn on AP+STA mode - mode(WIFI_AP_STA); + _mode(WIFI_AP_STA); } else { // turn on STA mode - mode(WIFI_STA); + _mode(WIFI_STA); } _smartConfigStarted = true; _smartConfigDone = false; - //SC_TYPE_ESPTOUCH use ESPTOUCH for smartconfig, or use SC_TYPE_AIRKISS for AIRKISS + //SC_TYPE_ESPTOUCH use ESPTOUCH for smartconfig, or use SC_TYPE_AIRKISS for AIRKISS smartconfig_start(reinterpret_cast(&ESP8266WiFiClass::_smartConfigCallback), 1); } @@ -728,7 +777,7 @@ void ESP8266WiFiClass::_smartConfigCallback(uint32_t st, void* result) sc_status status = (sc_status) st; if (status == SC_STATUS_LINK) { station_config* sta_conf = reinterpret_cast(result); - + wifi_station_set_config(sta_conf); wifi_station_disconnect(); wifi_station_connect(); @@ -777,7 +826,7 @@ void ESP8266WiFiClass::printDiag(Print& p) static struct station_config conf; wifi_station_get_config(&conf); - + const char* ssid = reinterpret_cast(conf.ssid); p.print("SSID ("); p.print(strlen(ssid)); diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFi.h b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFi.h index a7201c56dc..369892ecf5 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFi.h +++ b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFi.h @@ -104,6 +104,13 @@ class ESP8266WiFiClass */ void softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet); + /* + * Disconnect from the network (close AP) + * + * return: one value of wl_status_t enum + */ + int softAPdisconnect(bool wifioff = false); + /* * Disconnect from the network * @@ -348,6 +355,7 @@ class ESP8266WiFiClass friend class WiFiServer; protected: + void _mode(WiFiMode); static void _scanDone(void* result, int status); void * _getScanInfoByIndex(int i); static void _smartConfigCallback(uint32_t status, void* result); diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFiMulti.cpp b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFiMulti.cpp index 789c1d77e6..f874441bdb 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFiMulti.cpp +++ b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/ESP8266WiFiMulti.cpp @@ -166,29 +166,34 @@ bool ESP8266WiFiMulti::APlistAdd(const char* ssid, const char *passphrase) { if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) { // fail SSID to long or missing! + DEBUG_WIFI_MULTI("[WIFI][APlistAdd] no ssid or ssid to long\n"); return false; } if(passphrase && strlen(passphrase) > 63) { // fail passphrase to long! + DEBUG_WIFI_MULTI("[WIFI][APlistAdd] passphrase to long\n"); return false; } newAP.ssid = strdup(ssid); if(!newAP.ssid) { + DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.ssid == 0\n"); return false; } if(passphrase && *passphrase != 0x00) { newAP.passphrase = strdup(passphrase); if(!newAP.passphrase) { + DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.passphrase == 0\n"); free(newAP.ssid); return false; } } APlist.push_back(newAP); + DEBUG_WIFI_MULTI("[WIFI][APlistAdd] add SSID: %s\n", newAP.ssid); return true; } diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiClient.cpp b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiClient.cpp index 083463444e..50e8d11234 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiClient.cpp +++ b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiClient.cpp @@ -1,10 +1,10 @@ -/* +/* WiFiClient.cpp - TCP/IP client for esp8266, mostly compatible with Arduino WiFi shield library Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -22,7 +22,7 @@ #define LWIP_INTERNAL -extern "C" +extern "C" { #include "include/wl_definitions.h" #include "osapi.h" @@ -48,7 +48,7 @@ template<> WiFiClient* SList::_s_first = 0; -WiFiClient::WiFiClient() +WiFiClient::WiFiClient() : _client(0) { WiFiClient::_add(this); @@ -78,7 +78,7 @@ WiFiClient::WiFiClient(const WiFiClient& other) WiFiClient& WiFiClient::operator=(const WiFiClient& other) { if (_client) - _client->unref(); + _client->unref(); _client = other._client; if (_client) _client->ref(); @@ -86,7 +86,7 @@ WiFiClient& WiFiClient::operator=(const WiFiClient& other) } -int WiFiClient::connect(const char* host, uint16_t port) +int WiFiClient::connect(const char* host, uint16_t port) { IPAddress remote_addr; if (WiFi.hostByName(host, remote_addr)) @@ -96,7 +96,7 @@ int WiFiClient::connect(const char* host, uint16_t port) return 0; } -int WiFiClient::connect(IPAddress ip, uint16_t port) +int WiFiClient::connect(IPAddress ip, uint16_t port) { ip_addr_t addr; addr.addr = ip; @@ -162,12 +162,12 @@ bool WiFiClient::getNoDelay() { return _client->getNoDelay(); } -size_t WiFiClient::write(uint8_t b) +size_t WiFiClient::write(uint8_t b) { return write(&b, 1); } -size_t WiFiClient::write(const uint8_t *buf, size_t size) +size_t WiFiClient::write(const uint8_t *buf, size_t size) { if (!_client || !size) { @@ -179,19 +179,18 @@ size_t WiFiClient::write(const uint8_t *buf, size_t size) int WiFiClient::available() { - int result = 0; + if (!_client) + return false; - if (_client) { - result = _client->getSize(); - } + int result = _client->getSize(); if (!result) { - optimistic_yield(); + optimistic_yield(100); } return result; } -int WiFiClient::read() +int WiFiClient::read() { if (!available()) return -1; @@ -200,12 +199,12 @@ int WiFiClient::read() } -int WiFiClient::read(uint8_t* buf, size_t size) +int WiFiClient::read(uint8_t* buf, size_t size) { return (int) _client->read(reinterpret_cast(buf), size); } -int WiFiClient::peek() +int WiFiClient::peek() { if (!available()) return -1; @@ -213,13 +212,13 @@ int WiFiClient::peek() return _client->peek(); } -void WiFiClient::flush() +void WiFiClient::flush() { if (_client) _client->flush(); } -void WiFiClient::stop() +void WiFiClient::stop() { if (!_client) return; @@ -228,7 +227,7 @@ void WiFiClient::stop() _client = 0; } -uint8_t WiFiClient::connected() +uint8_t WiFiClient::connected() { if (!_client) return 0; @@ -236,14 +235,14 @@ uint8_t WiFiClient::connected() return _client->state() == ESTABLISHED || available(); } -uint8_t WiFiClient::status() +uint8_t WiFiClient::status() { if (!_client) return CLOSED; return _client->state(); } - WiFiClient::operator bool() + WiFiClient::operator bool() { return _client != 0; } diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiServer.cpp b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiServer.cpp index cf975a330f..0e4af3f368 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiServer.cpp +++ b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiServer.cpp @@ -1,10 +1,10 @@ -/* +/* WiFiServer.cpp - TCP/IP server for esp8266, mostly compatible with Arduino WiFi shield library Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -99,7 +99,7 @@ WiFiClient WiFiServer::available(byte* status) return result; } - optimistic_yield(); + optimistic_yield(1000); return WiFiClient(); } @@ -161,4 +161,3 @@ void WiFiServer::_s_discard(void* server, ClientContext* ctx) { reinterpret_cast(server)->_discard(ctx); } - diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiUdp.cpp b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiUdp.cpp index 71f8ff41a5..733ba3ff83 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiUdp.cpp +++ b/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/src/WiFiUdp.cpp @@ -22,8 +22,8 @@ #define LWIP_INTERNAL #include - -extern "C" + +extern "C" { #include "include/wl_definitions.h" #include "osapi.h" @@ -45,7 +45,7 @@ template<> WiFiUDP* SList::_s_first = 0; /* Constructor */ -WiFiUDP::WiFiUDP() : _ctx(0) +WiFiUDP::WiFiUDP() : _ctx(0) { WiFiUDP::_add(this); } @@ -74,7 +74,7 @@ WiFiUDP::~WiFiUDP() } /* Start WiFiUDP socket, listening at local port */ -uint8_t WiFiUDP::begin(uint16_t port) +uint8_t WiFiUDP::begin(uint16_t port) { if (_ctx) { _ctx->unref(); @@ -94,7 +94,7 @@ uint8_t WiFiUDP::beginMulticast(IPAddress interfaceAddr, IPAddress multicast, ui _ctx->unref(); _ctx = 0; } - + ip_addr_t ifaddr; ifaddr.addr = (uint32_t) interfaceAddr; ip_addr_t multicast_addr; @@ -123,7 +123,9 @@ int WiFiUDP::available() { } if (!result) { - optimistic_yield(); + // yielding here will not make more data "available", + // but it will prevent the system from going into WDT reset + optimistic_yield(1000); } return result; @@ -161,7 +163,7 @@ int WiFiUDP::beginPacket(IPAddress ip, uint16_t port) return (_ctx->connect(addr, port)) ? 1 : 0; } -int WiFiUDP::beginPacketMulticast(IPAddress multicastAddress, uint16_t port, +int WiFiUDP::beginPacketMulticast(IPAddress multicastAddress, uint16_t port, IPAddress interfaceAddress, int ttl) { ip_addr_t mcastAddr; @@ -207,8 +209,12 @@ int WiFiUDP::parsePacket() { if (!_ctx) return 0; - if (!_ctx->next()) + + if (!_ctx->next()) { + optimistic_yield(100); return 0; + } + return _ctx->getSize(); } @@ -216,8 +222,8 @@ int WiFiUDP::read() { if (!_ctx) return -1; - - return _ctx->read(); + + return _ctx->read(); } int WiFiUDP::read(unsigned char* buffer, size_t len) @@ -284,4 +290,3 @@ void WiFiUDP::stopAll() it->stop(); } } - diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266mDNS/README.md b/hardware/esp8266com/esp8266/libraries/ESP8266mDNS/README.md index f438ae8d6c..728c5bc786 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266mDNS/README.md +++ b/hardware/esp8266com/esp8266/libraries/ESP8266mDNS/README.md @@ -19,12 +19,12 @@ Usage ----- 1. Download this repository as a zip (button on the right) and follow [these instructions to install into Arduino](http://arduino.cc/en/Guide/Libraries). 2. Include the ESP8266mDNS library in the sketch. -3. Create an instance of the MDNSResponder class. -4. Call the begin method in the sketch's setup and provide a domain name (without - the '.local' suffix, i.e. just provide 'foo' to resolve 'foo.local'), and the - IP address to advertise. Optionally provide a time to live (in seconds) - for the DNS record--the default is 1 hour. -5. Call the update method in each iteration of the sketch's loop function. +3. Call MDNS.begin method in the sketch's setup and provide a domain name (without + the '.local' suffix, i.e. just provide 'foo' to resolve 'foo.local'). Optionally provide + the IP address to advertise and time to live (in seconds) for the DNS record -- the default is 1 hour. +4. To advertise DNS-SD services, call MDNS.addService(service, proto, port), where service and proto + are strings with service and protocol name (e.g. "http", "tcp"), and port is an integer port number + for this service (e.g. 80). See the included MDNS + HTTP server sketch for a full example. @@ -49,4 +49,4 @@ 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. \ No newline at end of file +THE SOFTWARE. diff --git a/hardware/esp8266com/esp8266/libraries/ESP8266mDNS/examples/DNS_SD_Arduino_OTA/DNS_SD_Arduino_OTA.ino b/hardware/esp8266com/esp8266/libraries/ESP8266mDNS/examples/DNS_SD_Arduino_OTA/DNS_SD_Arduino_OTA.ino index 31c30f2ebd..0689a8531a 100644 --- a/hardware/esp8266com/esp8266/libraries/ESP8266mDNS/examples/DNS_SD_Arduino_OTA/DNS_SD_Arduino_OTA.ino +++ b/hardware/esp8266com/esp8266/libraries/ESP8266mDNS/examples/DNS_SD_Arduino_OTA/DNS_SD_Arduino_OTA.ino @@ -1,12 +1,12 @@ #include #include -#include - +#include + const char* host = "esp8266-ota"; const char* ssid = "**********"; const char* pass = "**********"; const uint16_t aport = 8266; - + WiFiServer TelnetServer(aport); WiFiClient Telnet; WiFiUDP OTA; @@ -15,10 +15,10 @@ void setup() { Serial.begin(115200); Serial.println(""); Serial.println("Arduino OTA Test"); - + Serial.printf("Sketch size: %u\n", ESP.getSketchSize()); Serial.printf("Free size: %u\n", ESP.getFreeSketchSpace()); - + WiFi.begin(ssid, pass); if(WiFi.waitForConnectResult() == WL_CONNECTED){ MDNS.begin(host); @@ -43,24 +43,24 @@ void loop() { Serial.print(remote); Serial.printf(", port:%d, size:%d\n", port, size); uint32_t startTime = millis(); - + WiFiUDP::stopAll(); - + if(!Update.begin(size)){ Serial.println("Update Begin Error"); return; } - + WiFiClient client; if (client.connect(remote, port)) { - + uint32_t written; while(!Update.isFinished()){ written = Update.write(client); if(written > 0) client.print(written, DEC); } Serial.setDebugOutput(false); - + if(Update.end()){ client.println("OK"); Serial.printf("Update Success: %u\nRebooting...\n", millis() - startTime); diff --git a/hardware/esp8266com/esp8266/libraries/Hash/examples/sha1.ino b/hardware/esp8266com/esp8266/libraries/Hash/examples/sha1/sha1.ino similarity index 94% rename from hardware/esp8266com/esp8266/libraries/Hash/examples/sha1.ino rename to hardware/esp8266com/esp8266/libraries/Hash/examples/sha1/sha1.ino index 75cb8443d1..6b4eb52a2f 100644 --- a/hardware/esp8266com/esp8266/libraries/Hash/examples/sha1.ino +++ b/hardware/esp8266com/esp8266/libraries/Hash/examples/sha1/sha1.ino @@ -1,32 +1,32 @@ -/** - * simple demo to show sha1 calculation - */ -#include -#include - -void setup() { - Serial.begin(921600); -} - -void loop() { - - // usage as String - // SHA1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 - - Serial.print("SHA1:"); - Serial.println(sha1("abc")); - - // usage as ptr - // SHA1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 - uint8_t hash[20]; - sha1("abc", &hash[0]); - - Serial.print("SHA1:"); - for(uint16_t i = 0; i < 20; i++) { - Serial.printf("%02x", hash[i]); - } - Serial.println(); - - delay(1000); -} - +/** + * simple demo to show sha1 calculation + */ +#include +#include + +void setup() { + Serial.begin(921600); +} + +void loop() { + + // usage as String + // SHA1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 + + Serial.print("SHA1:"); + Serial.println(sha1("abc")); + + // usage as ptr + // SHA1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 + uint8_t hash[20]; + sha1("abc", &hash[0]); + + Serial.print("SHA1:"); + for(uint16_t i = 0; i < 20; i++) { + Serial.printf("%02x", hash[i]); + } + Serial.println(); + + delay(1000); +} + diff --git a/hardware/esp8266com/esp8266/libraries/Servo/src/esp8266/Servo.cpp b/hardware/esp8266com/esp8266/libraries/Servo/src/esp8266/Servo.cpp index bbc7bb26ff..e9fce77f16 100644 --- a/hardware/esp8266com/esp8266/libraries/Servo/src/esp8266/Servo.cpp +++ b/hardware/esp8266com/esp8266/libraries/Servo/src/esp8266/Servo.cpp @@ -165,9 +165,6 @@ uint8_t Servo::attach(int pin, int minUs, int maxUs) { ServoTimerSequence timerId; - Serial.print("_servoIndex "); - Serial.println(_servoIndex); - if (_servoIndex < MAX_SERVOS) { pinMode(pin, OUTPUT); // set servo pin to output digitalWrite(pin, LOW); diff --git a/hardware/esp8266com/esp8266/libraries/TFT_Touch_Shield_V2/examples/paint/.test.skip b/hardware/esp8266com/esp8266/libraries/TFT_Touch_Shield_V2/examples/paint/.test.skip new file mode 100644 index 0000000000..e69de29bb2 diff --git a/hardware/esp8266com/esp8266/libraries/TFT_Touch_Shield_V2/examples/tftbmp/.test.skip b/hardware/esp8266com/esp8266/libraries/TFT_Touch_Shield_V2/examples/tftbmp/.test.skip new file mode 100644 index 0000000000..e69de29bb2 diff --git a/hardware/esp8266com/esp8266/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/.test.skip b/hardware/esp8266com/esp8266/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/.test.skip new file mode 100644 index 0000000000..e69de29bb2 diff --git a/hardware/esp8266com/esp8266/libraries/Wire/Wire.cpp b/hardware/esp8266com/esp8266/libraries/Wire/Wire.cpp index 84b4c8c224..c1f457aa47 100644 --- a/hardware/esp8266com/esp8266/libraries/Wire/Wire.cpp +++ b/hardware/esp8266com/esp8266/libraries/Wire/Wire.cpp @@ -161,13 +161,15 @@ size_t TwoWire::write(const uint8_t *data, size_t quantity){ } int TwoWire::available(void){ - int result = rxBufferLength - rxBufferIndex; + int result = rxBufferLength - rxBufferIndex; - if (!result) { - optimistic_yield(); - } + if (!result) { + // yielding here will not make more data "available", + // but it will prevent the system from going into WDT reset + optimistic_yield(1000); + } - return result; + return result; } int TwoWire::read(void){ @@ -209,7 +211,7 @@ void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes) // // copy twi rx buffer into local read buffer // // this enables new reads to happen in parallel // for(uint8_t i = 0; i < numBytes; ++i){ - // rxBuffer[i] = inBytes[i]; + // rxBuffer[i] = inBytes[i]; // } // // set rx iterator vars // rxBufferIndex = 0; @@ -242,4 +244,3 @@ void TwoWire::onRequest( void (*function)(void) ){ // Preinstantiate Objects ////////////////////////////////////////////////////// TwoWire Wire = TwoWire(); - diff --git a/hardware/esp8266com/esp8266/libraries/esp8266/examples/CallSDKFunctions/CallSDKFunctions.ino b/hardware/esp8266com/esp8266/libraries/esp8266/examples/CallSDKFunctions/CallSDKFunctions.ino new file mode 100644 index 0000000000..485531aa60 --- /dev/null +++ b/hardware/esp8266com/esp8266/libraries/esp8266/examples/CallSDKFunctions/CallSDKFunctions.ino @@ -0,0 +1,33 @@ + +/* + * NativeSdk by Simon Peter + * Access functionality from the Espressif ESP8266 SDK + * This example code is in the public domain + * + * This is for advanced users. + * Note that this makes your code dependent on the ESP8266, which is generally + * a bad idea. So you should try to use esp8266/Arduino functionality + * where possible instead, in order to abstract away the hardware dependency. + */ + +// Expose Espressif SDK functionality - wrapped in ifdef so that it still +// compiles on other platforms +#ifdef ESP8266 +extern "C" { +#include "user_interface.h" +} +#endif + +void setup() { + Serial.begin(115200); +} + +void loop() { + // Call Espressif SDK functionality - wrapped in ifdef so that it still + // compiles on other platforms +#ifdef ESP8266 + Serial.print("wifi_station_get_hostname: "); + Serial.println(wifi_station_get_hostname()); +#endif + delay(1000); +} diff --git a/hardware/esp8266com/esp8266/tests/FSWrapper/FSWrapper.ino b/hardware/esp8266com/esp8266/tests/FSWrapper/FSWrapper.ino new file mode 100644 index 0000000000..1da05a59a9 --- /dev/null +++ b/hardware/esp8266com/esp8266/tests/FSWrapper/FSWrapper.ino @@ -0,0 +1,103 @@ +#include +#include "FS.h" + + +void fail(const char* msg) { + Serial.println(msg); + while(true) { + yield(); + } +} + +void setup() { + Serial.begin(115200); + Serial.setDebugOutput(true); + WiFi.mode(WIFI_OFF); + Serial.println("\n\nFS test\n"); + + if (!SPIFFS.begin()) { + fail("SPIFFS init failed"); + } + + String text = "write test"; + { + File out = SPIFFS.open("/tmp.txt", "w"); + if (!out) { + fail("failed to open tmp.txt for writing"); + } + out.print(text); + } + + { + File in = SPIFFS.open("/tmp.txt", "r"); + if (!in) { + fail("failed to open tmp.txt for reading"); + } + Serial.printf("size=%d\r\n", in.size()); + if (in.size() != text.length()) { + fail("invalid size of tmp.txt"); + } + Serial.print("Reading data: "); + in.setTimeout(0); + String result = in.readString(); + Serial.println(result); + if (result != text) { + fail("invalid data in tmp.txt"); + } + } + + { + for (int i = 0; i < 10; ++i) { + String name = "seq_"; + name += i; + name += ".txt"; + + File out = SPIFFS.open(name, "w"); + if (!out) { + fail("can't open seq_ file"); + } + + out.println(i); + } + } + { + Dir root = SPIFFS.openDir("/"); + while (root.next()) { + String fileName = root.fileName(); + File f = root.openFile("r"); + Serial.printf("%s: %d\r\n", fileName.c_str(), f.size()); + } + } + + { + Dir root = SPIFFS.openDir("/"); + while(root.next()) { + String fileName = root.fileName(); + Serial.print("deleting "); + Serial.println(fileName); + if (!SPIFFS.remove(fileName)) { + fail("remove failed"); + } + } + } + + { + File tmp = SPIFFS.open("/tmp1.txt", "w"); + tmp.println("rename test"); + } + + { + if (!SPIFFS.rename("/tmp1.txt", "/tmp2.txt")) { + fail("rename failed"); + } + File tmp2 = SPIFFS.open("/tmp2.txt", "r"); + if (!tmp2) { + fail("open tmp2 failed"); + } + } + + Serial.println("success"); +} + +void loop() { +} diff --git a/hardware/esp8266com/esp8266/tests/common.sh b/hardware/esp8266com/esp8266/tests/common.sh new file mode 100755 index 0000000000..fab1a90f33 --- /dev/null +++ b/hardware/esp8266com/esp8266/tests/common.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +function build_sketches() +{ + local arduino=$1 + local srcpath=$2 + local sketches=$(find $srcpath -name *.ino) + for sketch in $sketches; do + local sketchdir=$(dirname $sketch) + if [[ -f "$sketchdir/.test.skip" ]]; then + echo -e "\n\n ------------ Skipping $sketch ------------ \n\n"; + continue + fi + echo -e "\n\n ------------ Building $sketch ------------ \n\n"; + $arduino --verify --verbose $sketch; + local result=$? + if [ $result -ne 0 ]; then + echo "Build failed ($1)" + return $result + fi + done +} diff --git a/hardware/esp8266com/esp8266/tools/sdk/changelog.txt b/hardware/esp8266com/esp8266/tools/sdk/changelog.txt index 5cd5b9cc27..05d32ebb5a 100644 --- a/hardware/esp8266com/esp8266/tools/sdk/changelog.txt +++ b/hardware/esp8266com/esp8266/tools/sdk/changelog.txt @@ -1,3 +1,50 @@ +esp_iot_sdk_v1.2.0_15_07_13_p4 Release Note +------------------------------------------- + +Here is a patch of memory optimization based on SDK_v1.2.0 +1. It saved about 8KBytes memory. +2. It revised problem that change mode may cause memory leak. +3. Update SmartConfig to version 2.4.3 + +Please replace the lib in \esp_iot_sdk_v1.2.0\lib + +Thanks for your interest in Espressif Systems and ESP8266 ! + + + + +esp_iot_sdk_v1.2.0_15_07_09_p3 Release Note +------------------------------------------- + +Here is a patch based on SDK_v1.2.0 solved problem that if AP’s SSID is hidden,ESPTOUCH may get wrong BSSID of AP and cause connection fail. +Please replace the lib in \esp_iot_sdk_v1.2.0\lib + +Sorry for the inconvenience. + + + + +esp_iot_sdk_v1.2.0_15_07_09_p2 Release Note +------------------------------------------- + +Updated libssl again. To support SHA-256 and SHA-512. + +Thanks for your interest in Espressif Systems and ESP8266 ! + + + + +esp_iot_sdk_v1.2.0_15_07_08_p1 Release Note +------------------------------------------- + +Here is a patch based on SDK_v1.2.0 solved problem that abnormal SSL disconnection may cause reset. +Please replace the lib in \esp_iot_sdk_v1.2.0\lib + +Sorry for the inconvenience. + + + + esp_iot_sdk_v1.2.0_15_07_03 Release Note ------------------------------------------- Resolved Issues(Bugs below are eligible for Bug Bounty Program): diff --git a/hardware/esp8266com/esp8266/tools/sdk/include/ets_sys.h b/hardware/esp8266com/esp8266/tools/sdk/include/ets_sys.h index 8d7adbde3f..607d601f18 100644 --- a/hardware/esp8266com/esp8266/tools/sdk/include/ets_sys.h +++ b/hardware/esp8266com/esp8266/tools/sdk/include/ets_sys.h @@ -65,8 +65,8 @@ inline bool ETS_INTR_WITHINISR() { uint32_t ps; __asm__ __volatile__("rsr %0,ps":"=a" (ps)); - // PS.EXCM and PS.UM bit checks - return ((ps & ((1 << 4) | (1 << 5))) > 0); + // PS.EXCM bit check + return ((ps & (1 << 4)) != 0); } inline uint32_t ETS_INTR_ENABLED(void) diff --git a/hardware/esp8266com/esp8266/tools/sdk/lib/libnet80211.a b/hardware/esp8266com/esp8266/tools/sdk/lib/libnet80211.a index 59fc632e41..d7af5f4659 100644 Binary files a/hardware/esp8266com/esp8266/tools/sdk/lib/libnet80211.a and b/hardware/esp8266com/esp8266/tools/sdk/lib/libnet80211.a differ diff --git a/hardware/esp8266com/esp8266/tools/sdk/lib/libpp.a b/hardware/esp8266com/esp8266/tools/sdk/lib/libpp.a index ae4b8b7033..d8b550c7fe 100644 Binary files a/hardware/esp8266com/esp8266/tools/sdk/lib/libpp.a and b/hardware/esp8266com/esp8266/tools/sdk/lib/libpp.a differ diff --git a/hardware/esp8266com/esp8266/tools/sdk/lib/libsmartconfig.a b/hardware/esp8266com/esp8266/tools/sdk/lib/libsmartconfig.a index 0f7fb9a372..f3b0d65547 100644 Binary files a/hardware/esp8266com/esp8266/tools/sdk/lib/libsmartconfig.a and b/hardware/esp8266com/esp8266/tools/sdk/lib/libsmartconfig.a differ diff --git a/hardware/esp8266com/esp8266/tools/sdk/lib/libssl.a b/hardware/esp8266com/esp8266/tools/sdk/lib/libssl.a index b49dd7bd1b..0634025f12 100644 Binary files a/hardware/esp8266com/esp8266/tools/sdk/lib/libssl.a and b/hardware/esp8266com/esp8266/tools/sdk/lib/libssl.a differ diff --git a/hardware/esp8266com/esp8266/tools/sdk/version b/hardware/esp8266com/esp8266/tools/sdk/version index e876391a54..4139f843a3 100644 --- a/hardware/esp8266com/esp8266/tools/sdk/version +++ b/hardware/esp8266com/esp8266/tools/sdk/version @@ -1 +1 @@ -1.2.0_15_07_03 \ No newline at end of file +1.2.0_15_07_13_p4 \ No newline at end of file diff --git a/hardware/esp8266com/esp8266/variants/thing/pins_arduino.h b/hardware/esp8266com/esp8266/variants/thing/pins_arduino.h new file mode 100644 index 0000000000..72d0aaea15 --- /dev/null +++ b/hardware/esp8266com/esp8266/variants/thing/pins_arduino.h @@ -0,0 +1,70 @@ +/* + pins_arduino.h - Pin definition functions for Arduino + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2007 David A. Mellis + Modified for ESP8266 platform by Ivan Grokhotkov, 2014-2015. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id: wiring.h 249 2007-02-03 16:52:51Z mellis $ +*/ + +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 17 +#define NUM_ANALOG_INPUTS 1 + +#define analogInputToDigitalPin(p) ((p > 0)?NOT_A_PIN:0) +#define digitalPinToInterrupt(p) (((p) < EXTERNAL_NUM_INTERRUPTS)?p:NOT_A_PIN) +#define digitalPinHasPWM(p) (((p) < NUM_DIGITAL_PINS)?p:NOT_A_PIN) + +static const uint8_t SDA = 2; +static const uint8_t SCL = 14; + +static const uint8_t SS = 15; +static const uint8_t MOSI = 13; +static const uint8_t MISO = 12; +static const uint8_t SCK = 14; + +static const uint8_t BUILTIN_LED = 5; + +static const uint8_t A0 = 17; + + +// These serial port names are intended to allow libraries and architecture-neutral +// sketches to automatically default to the correct port name for a particular type +// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN, +// the first hardware serial port whose RX/TX pins are not dedicated to another use. +// +// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor +// +// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial +// +// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library +// +// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins. +// +// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX +// pins are NOT connected to anything by default. +#define SERIAL_PORT_MONITOR Serial +#define SERIAL_PORT_USBVIRTUAL Serial +#define SERIAL_PORT_HARDWARE Serial +#define SERIAL_PORT_HARDWARE_OPEN Serial + +#endif /* Pins_Arduino_h */ diff --git a/libraries/Adafruit_ILI9341/examples/graphicstest_esp8266/graphicstest.ino b/libraries/Adafruit_ILI9341/examples/graphicstest_esp8266/graphicstest_esp8266.ino similarity index 100% rename from libraries/Adafruit_ILI9341/examples/graphicstest_esp8266/graphicstest.ino rename to libraries/Adafruit_ILI9341/examples/graphicstest_esp8266/graphicstest_esp8266.ino