Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Will this work on the Adafruit HUZZAH32 - ESP32 board? #34

Open
tpitman opened this issue Oct 22, 2018 · 4 comments
Open

Will this work on the Adafruit HUZZAH32 - ESP32 board? #34

tpitman opened this issue Oct 22, 2018 · 4 comments

Comments

@tpitman
Copy link

tpitman commented Oct 22, 2018

Will this work on the Adafruit HUZZAH32 - ESP32 board?

@ilioss
Copy link

ilioss commented Jun 16, 2020

Hello tpitman,

I alsop hat the question if this also worked on a ESP32.
Not out of the box. So I went puzzling to have finally a working script on the ESP32.
Note with the arduino ide it works on the PlatformIO it remains resetting the ESP32.
Hoppefully it is of help for you.
Regards,
ilioSS
`/* ESP32-Async
*

  • dd 10-05-2020 File: ESP32-Async_01
  •                     A-Temp. van tttapa van esp8266 naar esp32 proberen om te zetten?????
    
  • dd 15-06-2020 File: ESP32-tttapa-temp.logger_01
  •                     De esp8266 file omgebouwd naar de ESP32 lijkt te werken???????
    
  • dd 16-06-2020 File: ESP32-tttapa-temp-logger_04
  •                     Werkt en opgeschoond
    

*/
#include <Arduino.h>

//**************************** NETWORK ******************************************
#include <HTTP_Method.h>
#include <WebServer.h>
#include <WiFi.h>
#include <WiFiUdp.h>
#include <WiFiMulti.h>
#include <ESPAsyncWebServer.h>
#include <ESPmDNS.h>
#include <AsyncTCP.h>
#include <AsyncWebSocket.h>
#include <ArduinoOTA.h>

//************************* DS18B20 ********************************************
#include <OneWire.h>
#include <DallasTemperature.h>
#define TEMP_SENSOR_PIN 5 // PAS OP DIT IS OP PIN D2!!!!!!!!!!!!!!!!!!!!!!!!
OneWire oneWire(TEMP_SENSOR_PIN); // Set up a OneWire instance to communicate with OneWire devices
DallasTemperature tempSensors(&oneWire); // Create an instance of the temperature sensor class

//********************* SPIFFS ************************************************
#include <FS.h>
#include <SPIFFS.h>
#define FORMAT_SPIFFS_IF_FAILED true

#define ONE_HOUR 3600000UL // timer for request time

WebServer server(80);

File fsUploadFile;

WiFiMulti wifiMulti;

WiFiUDP UDP;

IPAddress timeServerIP; // The time.nist.gov NTP server's IP address
const char *ntpServerName = "time.nist.gov";
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[NTP_PACKET_SIZE]; // A buffer to hold incoming and outgoing packets

const char *OTAName = "ESP32"; // A name and a password for the OTA service
const char *OTAPassword = "esp32";
const char *mdnsName = "esp32"; // Domain name for the mDNS responder

const unsigned long intervalNTP = ONE_HOUR; // Update the time every hour
unsigned long prevNTP = 0;
unsigned long lastNTPResponse = millis();

const unsigned long intervalTemp = 60000; // Do a temperature measurement every minute
unsigned long prevTemp = 0;
bool tmpRequested = false;
const unsigned long DS_delay = 750; // Reading the temperature from the DS18x20 can take up to 750ms

uint32_t timeUNIX = 0;

String formatBytes(size_t bytes) { // convert sizes in bytes to KB and MB
if (bytes < 1024) return String(bytes) + "B";
else if (bytes < (1024 * 1024)) return String(bytes / 1024.0) + "KB";
else if (bytes < (1024 * 1024 * 1024)) return String(bytes / 1024.0 / 1024.0) + "MB";
return "text/plain";
}

String getContentType(String filename) { // determine the filetype of a given filename, based on the extension
if (filename.endsWith(".html")) return "text/html";
else if (filename.endsWith(".css")) return "text/css";
else if (filename.endsWith(".js")) return "application/javascript";
else if (filename.endsWith(".ico")) return "image/x-icon";
else if (filename.endsWith(".gz")) return "application/x-gzip";
return "text/plain";
}

bool handleFileRead(String path) { // send the right file to the client (if it exists)
Serial.println("handleFileRead: " + path);
if (path.endsWith("/")) path += "index.html"; // If a folder is requested, send the index file
String contentType = getContentType(path); // Get the MIME type
String pathWithGz = path + ".gz";
if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) { // If the file exists, either as a compressed archive, or normal
if (SPIFFS.exists(pathWithGz)) // If there's a compressed version available
path += ".gz"; // Use the compressed verion
File file = SPIFFS.open(path, "r"); // Open the file
size_t sent = server.streamFile(file, contentType); // Send it to the client
file.close(); // Close the file again
Serial.println(String("\tSent file: ") + path);
return true;
}
Serial.println(String("\tFile Not Found: ") + path); // If the file doesn't exist, return false
return false;
}

//***************** VOIDS **********************************************************************
void handleNotFound() { // if the requested file or page doesn't exist, return a 404 not found error
if (!handleFileRead(server.uri())) { // check if the file exists in the flash memory (SPIFFS), if so, send it
server.send(404, "text/plain", "404: File Not Found");
}
}

void startUDP() {
Serial.println("Starting UDP");
UDP.begin(123); // Start listening for UDP messages to port 123
Serial.print("Local port:\t");
// Serial.println(UDP.localPort());
}

void startOTA() { // Start the OTA service
ArduinoOTA.setHostname(OTAName);
ArduinoOTA.setPassword(OTAPassword);

ArduinoOTA.onStart( {
Serial.println("Start");
});
ArduinoOTA.onEnd( {
Serial.println("\r\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("OTA ready\r\n");
}

void startSPIFFS() { // Start the SPIFFS and list all contents
SPIFFS.begin(); // Start the SPI Flash File System (SPIFFS)
Serial.println("SPIFFS started. Contents:");
{
File file = SPIFFS.open("/");{
}
Serial.printf("\n");
}
}

void listDir(fs::FS &fs, const char * dirname, uint8_t levels){
Serial.printf("Listing directory: %s\r\n", dirname);

File root = fs.open(dirname);
if(!root){
    Serial.println("- failed to open directory");
    return;
}
if(!root.isDirectory()){
    Serial.println(" - not a directory");
    return;
}

File file = root.openNextFile();
while(file){
    if(file.isDirectory()){
        Serial.print("  DIR : ");
        Serial.println(file.name());
        if(levels){
            listDir(fs, file.name(), levels -1);
        }
    } else {
        Serial.print("  FILE: ");
        Serial.print(file.name());
        Serial.print("\tSIZE: ");
        Serial.println(file.size());
    }
    file = root.openNextFile();
}

}

void startMDNS() { // Start the mDNS responder
MDNS.begin(mdnsName); // start the multicast domain name server
Serial.print("mDNS responder started: http://");
Serial.print(mdnsName);
Serial.println(".local");
}

void handleFileUpload() { // upload a new file to the SPIFFS
HTTPUpload& upload = server.upload();
String path;
if (upload.status == UPLOAD_FILE_START) {
path = upload.filename;
if (!path.startsWith("/")) path = "/" + path;
if (!path.endsWith(".gz")) { // The file server always prefers a compressed version of a file
String pathWithGz = path + ".gz"; // So if an uploaded file is not compressed, the existing compressed
if (SPIFFS.exists(pathWithGz)) // version of that file must be deleted (if it exists)
SPIFFS.remove(pathWithGz);
}
Serial.print("handleFileUpload Name: "); Serial.println(path);
fsUploadFile = SPIFFS.open(path, "w"); // Open the file for writing in SPIFFS (create if it doesn't exist)
path = String();
} else if (upload.status == UPLOAD_FILE_WRITE) {
if (fsUploadFile)
fsUploadFile.write(upload.buf, upload.currentSize); // Write the received bytes to the file
} else if (upload.status == UPLOAD_FILE_END) {
if (fsUploadFile) { // If the file was successfully created
fsUploadFile.close(); // Close the file again
Serial.print("handleFileUpload Size: "); Serial.println(upload.totalSize);
server.sendHeader("Location", "/success.html"); // Redirect the client to the success page
server.send(303);
} else {
server.send(500, "text/plain", "500: couldn't create file");
}
}
}

/HELPER_FUNCTIONS/

unsigned long getTime() { // Check if the time server has responded, if so, get the UNIX time, otherwise, return 0
if (UDP.parsePacket() == 0) { // If there's no response (yet)
return 0;
}
UDP.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer // Combine the 4 timestamp bytes into one 32-bit number
uint32_t NTPTime = (packetBuffer[40] << 24) | (packetBuffer[41] << 16) | (packetBuffer[42] << 8) | packetBuffer[43];
const uint32_t seventyYears = 2208988800UL; // Unix time starts on Jan 1 1970. That's 2208988800 seconds in NTP time:
uint32_t UNIXTime = NTPTime - seventyYears; // subtract seventy years:
return UNIXTime;
}

void sendNTPpacket(IPAddress& address) {
Serial.println("Sending NTP request"); // send a packet requesting a timestamp:
memset(packetBuffer, 0, NTP_PACKET_SIZE); // set all bytes in the buffer to 0
// Initialize values needed to form NTP request
packetBuffer[0] = 0b11100011; // LI, Version, Mode

UDP.beginPacket(address, 123); // NTP requests are to port 123
UDP.write(packetBuffer, NTP_PACKET_SIZE);
UDP.endPacket();
}

void startWiFi() { // Try to connect to some given access points. Then wait for a connection
wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1"); // add Wi-Fi networks you want to connect to
wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

Serial.println("Connecting");
while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
delay(250);
Serial.print('.');
}
Serial.println("\r\n");
Serial.print("Connected to ");
Serial.println(WiFi.SSID()); // Tell us what network we're connected to
Serial.print("IP address:\t");
Serial.print(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
Serial.println("\r\n");
}

void startServer() { // Start a HTTP server with a file read handler and an upload handler
server.on("/edit.html", HTTP_POST, { // If a POST request is sent to the /edit.html address,
server.send(200, "text/plain", "");
}, handleFileUpload); // go to 'handleFileUpload'

server.onNotFound(handleNotFound); // if someone requests any other file or page, go to function 'handleNotFound'// and check if the file exists
server.begin(); // start the HTTP server
Serial.println("HTTP server started.");
}

//*************************************** SET-UP *******************************************
void setup() {
Serial.begin(115200); // Start the Serial communication to send messages to the computer
delay(10);
Serial.println("\r\n");

if(!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)){
Serial.println("SPIFFS Mount Failed");
return;
}

tempSensors.setWaitForConversion(false); // Don't block the program while the temperature sensor is reading
tempSensors.begin(); // Start the temperature sensor

if (tempSensors.getDeviceCount() == 0) {
Serial.printf("No DS18x20 temperature sensor found on pin %d. Rebooting.\r\n", TEMP_SENSOR_PIN);
Serial.flush();
ESP.restart();
}
startWiFi(); // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection

startOTA(); // Start the OTA service

listDir(SPIFFS, "/", 0); // Start the SPIFFS and list all contents

startMDNS(); // Start the mDNS responder

startServer(); // Start a HTTP server with a file read handler and an upload handler

startUDP(); // Start listening for UDP messages to port 123

WiFi.hostByName(ntpServerName, timeServerIP); // Get the IP address of the NTP server
Serial.print("Time server IP:\t");
Serial.println(timeServerIP);

sendNTPpacket(timeServerIP);
delay(500);
}

//************************************** LOOP *************************************************
void loop() {

unsigned long currentMillis = millis();

if (currentMillis - prevNTP > intervalNTP) { // Request the time from the time server every hour
prevNTP = currentMillis;
sendNTPpacket(timeServerIP);
}

uint32_t time = getTime(); // Check if the time server has responded, if so, get the UNIX time
if (time) {
timeUNIX = time;
Serial.print("NTP response:\t");
Serial.println(timeUNIX);
lastNTPResponse = millis();
} else if ((millis() - lastNTPResponse) > 24UL * ONE_HOUR) {
Serial.println("More than 24 hours since last NTP response. Rebooting.");
Serial.flush();
ESP.restart();
}

if (timeUNIX != 0) {
if (currentMillis - prevTemp > intervalTemp) { // Every minute, request the temperature
tempSensors.requestTemperatures(); // Request the temperature from the sensor (it takes some time to read it)
tmpRequested = true;
prevTemp = currentMillis;
Serial.println("Temperature requested");
}
if (currentMillis - prevTemp > DS_delay && tmpRequested) { // 750 ms after requesting the temperature
long unsigned int actualTime = timeUNIX + (currentMillis - lastNTPResponse) / 1000;
// The actual time is the last NTP time plus the time that has elapsed since the last NTP response
tmpRequested = false;
float temp = tempSensors.getTempCByIndex(0); // Get the temperature from the sensor
temp = round(temp * 100.0) / 100.0; // round temperature to 2 digits

  Serial.printf("Appending temperature to file: %lu,", actualTime);
  Serial.println(temp);
  File tempLog = SPIFFS.open("/temp.csv", "a");       // Write the time and the temperature to the csv file
  tempLog.print(actualTime);
  tempLog.print(',');
  tempLog.println(temp);
  tempLog.close();
}

} else { // If we didn't receive an NTP response yet, send another request
sendNTPpacket(timeServerIP);
delay(500);
}
server.handleClient(); // run the server
ArduinoOTA.handle(); // listen for OTA events
}
`

@tpitman
Copy link
Author

tpitman commented Jun 16, 2020 via email

@ilioss
Copy link

ilioss commented Jun 16, 2020 via email

@tpitman
Copy link
Author

tpitman commented Jun 16, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants