How to Install WiFi - esp32

This is about PlftformIO extension to VSCode.
Code:
/*********
Rui Santos
Complete project details at http://randomnerdtutorials.com
*********/
// Load Wi-Fi library
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "linksys";
const char* password = "goskomstat";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String output26State = "off";
String output5State = "off";
// Assign output variables to GPIO pins
const int output26 = 26;
const int output5 = 5;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(output26, OUTPUT);
pinMode(output5, OUTPUT);
// Set outputs to LOW
digitalWrite(output26, LOW);
digitalWrite(output5, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (header.indexOf("GET /26/on") >= 0) {
Serial.println("GPIO 26 on");
output26State = "on";
digitalWrite(output26, HIGH);
} else if (header.indexOf("GET /26/off") >= 0) {
Serial.println("GPIO 26 off");
output26State = "off";
digitalWrite(output26, LOW);
} else if (header.indexOf("GET /5/on") >= 0) {
Serial.println("GPIO 5 on");
output5State = "on";
digitalWrite(output5, HIGH);
} else if (header.indexOf("GET /5/off") >= 0) {
Serial.println("GPIO 5 off");
output5State = "off";
digitalWrite(output5, LOW);
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
// Display current state, and ON/OFF buttons for GPIO 26
client.println("<p>GPIO 26 - State " + output26State + "</p>");
// If the output26State is off, it displays the ON button
if (output26State=="off") {
client.println("<p><button class=\"button\">ON</button></p>");
} else {
client.println("<p><button class=\"button button2\">OFF</button></p>");
}
// Display current state, and ON/OFF buttons for GPIO 27
client.println("<p>GPIO 5 - State " + output5State + "</p>");
// If the output27State is off, it displays the ON button
if (output5State=="off") {
client.println("<p><button class=\"button\">ON</button></p>");
} else {
client.println("<p><button class=\"button button2\">OFF</button></p>");
}
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Error:
* Executing task: platformio run
Processing nodemcu-32s (platform: espressif32; board: nodemcu-32s; framework: espidf)
---------------------------------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/nodemcu-32s.html
PLATFORM: Espressif 32 (6.0.1) > NodeMCU-32S
HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
DEBUG: Current (cmsis-dap) External (cmsis-dap, esp-bridge, esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa)
PACKAGES:
- framework-espidf # 3.50000.0 (5.0.0)
- tool-cmake # 3.16.4
- tool-esptoolpy # 1.40400.0 (4.4.0)
- tool-ninja # 1.7.1
- toolchain-esp32ulp # 1.23500.220830 (2.35.0)
- toolchain-xtensa-esp32 # 11.2.0+2022r1
Reading CMake configuration...
LDF: Library Dependency Finder -> https://----.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 0 compatible libraries
Scanning dependencies...
No dependencies
Building in release mode
Compiling .pio/build/nodemcu-32s/src/main.o
src/main.c:7:10: fatal error: WiFi.h: No such file or directory
**************************************************************
* Looking for WiFi.h dependency? Check our library registry!
*
* CLI > platformio lib search "header:WiFi.h"
* Web > https://registry.platformio.org/search?q=header:WiFi.h
*
**************************************************************
7 | #include <WiFi.h>
| ^~~~~~~~
compilation terminated.
Archiving .pio/build/nodemcu-32s/esp-idf/app_trace/libapp_trace.a
Indexing .pio/build/nodemcu-32s/esp-idf/app_trace/libapp_trace.a
Archiving .pio/build/nodemcu-32s/esp-idf/app_update/libapp_update.a
Indexing .pio/build/nodemcu-32s/esp-idf/app_update/libapp_update.a
Compiling .pio/build/nodemcu-32s/bootloader_support/src/bootloader_clock_init.o
Compiling .pio/build/nodemcu-32s/bootloader_support/bootloader_flash/src/bootloader_flash.o
Compiling .pio/build/nodemcu-32s/bootloader_support/src/bootloader_mem.o
*** [.pio/build/nodemcu-32s/src/main.o] Error 1
====================================== [FAILED] Took 2.12 seconds ======================================
* The terminal process "platformio 'run'" terminated with exit code: 1.
* Terminal will be reused by tasks, press any key to close it.
ini:
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = espidf
lib_deps = arduino-libraries/WiFi#^1.2.7
Library has been installed:
michael#michael:~/Documents/PlatformIO/Projects/blink$ pio pkg install --library "arduino-libraries/WiFi#^1.2.7"
Resolving nodemcu-32s dependencies...
Library Manager: WiFi#1.2.7 is already installed
Could you help me?

You don't "install wifi" separately. It's part of the Arduino framework for the ESP32 and it depends on other parts of the Arduino framework. It's not meant to be used separately.
Your platformio.ini file specifies ESP-IDF as the framework to use when building your program. ESP-IDF has its own WiFi API. If you're using ESP-IDF, use its WiFi functions.
The Arduino framework is built over ESP-IDF, so you can call some ESP-IDF functions from Arduino programs. You cannot, however, call Arduino functions from an ESP-IDF program as ESP-IDF knows nothing about Arduino.
If you want to use Arduino functions, build an Arduino program by setting the framework in your platformio.ini file to be arduino.
framework = arduino
Basically, pick one framework and stick with it. Don't try to mix Arduino functions into your ESP-IDF program.

Related

TTGO ESP32 + GSM 800l - Read SMS - TinyGSM

on my code i can send an sms to my target number but i don't know how to read or receive sms from target number
the tinyGSM library doesn't have the read member function and i don't know how to use AT commands
void setup() {
// Set console baud rate
SerialMon.begin(115200);
// Keep power when running from battery
Wire.begin(I2C_SDA, I2C_SCL);
bool isOk = setPowerBoostKeepOn(1);
SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));
// Set modem reset, enable, power pins
pinMode(MODEM_PWKEY, OUTPUT);
pinMode(MODEM_RST, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_PWKEY, LOW);
digitalWrite(MODEM_RST, HIGH);
digitalWrite(MODEM_POWER_ON, HIGH);
// Set GSM module baud rate and UART pins
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
delay(3000);
// Restart SIM800 module, it takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// use modem.init() if you don't need the complete restart
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
modem.simUnlock(simPIN);
}
// To send an SMS, call modem.sendSMS(SMS_TARGET, smsMessage)
String smsMessage = "Hello from ESP32!";
/*if(modem.sendSMS(SMS_TARGET, smsMessage))
{
SerialMon.println(smsMessage);
}
else{
SerialMon.println("SMS failed to send");
}*/
SerialAT.println("AT"); //Once the handshake test is successful, it will back to OK
SerialAT.println("AT+CMGF=1"); // Configuring TEXT mode
SerialAT.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
}
void loop()
{
//readSMS(1);
//delay(1);
}

canĀ“t emit via ethernet to my server on javascript?

hello, good day, I am making an example with a 5500 chip in esp32 with the socketioclient library, but when I want to send the json to my server, they are only left on the waiting list and I don't know what is happening to me, before all this an error message about invalid mbox appeared and I added the following line of code esp_netif_init(); and it was fixed, but once entering the loop the following happens:
serial monitor:
Starting WebServer on ESP32 with W5x00 using Ethernet_Generic Library with Large Buffer
Ethernet_Generic v2.4.0
[ETG] Default SPI pinout:
[ETG] MOSI: 23
[ETG] MISO: 19
[ETG] SCK: 18
[ETG] SS: 5
[ETG] =========================
[ETG] ESP32 setCsPin: 5
[ETG] W5100 init, using SS_PIN_DEFAULT = 22 , new ss_pin = 10 , W5100Class::ss_pin = 5
[ETG] Chip is W5500
[ETG] W5100::init: W5500, SSIZE = 8192
[ETG] Currently Used SPI pinout:
[ETG] MOSI: 23
[ETG] MISO: 19
[ETG] SCK: 18
[ETG] SS: 5
[ETG] =========================
Using mac index = 1
Connected! IP address: 192.168.10.147
Speed: 100 MB, Duplex: FULL DUPLEX, Link status: LINK
LLego a la parte de initwebsocket y task
termino inits
[SIoC] add packet 42["setRele",{"Dato":"hola"}]
[SIoC] add packet 42["getPrueba",{"name":"hola ese","SERVIDOR":"HOLA MUNDO"}]
[SIoC] Disconnected!
[SIoC] add packet 42["setRele",{"Dato":"hola"}]
[SIoC] add packet 42["getPrueba",{"name":"hola ese","SERVIDOR":"HOLA MUNDO"}]
[SIoC] Disconnected!
[SIoC] add packet 42["setRele",{"Dato":"hola"}]
[SIoC] add packet 42["getPrueba",{"name":"hola ese","SERVIDOR":"HOLA MUNDO"}]
[SIoC] Disconnected!
then the loop remains without emitting it just remains as shown above
sketch:
/****************************************************************************************************************************
WebServer.ino
Ethernet_Generic is a library for the W5x00 Ethernet shields trying to merge the good features of
previous Ethernet libraries
Built by Khoi Hoang https://github.com/khoih-prog/Ethernet_Generic
*****************************************************************************************************************************/
/*
The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno
and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53,
is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.
*/
#include "defines.h"
#include <SocketIoClient.h>
#include <Arduino_JSON.h>
#include <tcpip_adapter.h>
//TaskHandle_t Task1;
SocketIoClient socketIO;
//void Task1code( void * parameter ){
// Serial.print("Task1 is running on core ");
// Serial.println(xPortGetCoreID());
// while(1){
// socketIO.loop();
// delay(100);
// }
//}
//
//
void initWebSocket()
{
// server address, port and URL
socketIO.begin("192.168.10.59",8000);
// event handler for the event message
socketIO.on("asignacion",getresponse);
//socketIO.on("getPrueba",getresponse);
socketIO.loop();
delay(5000);
}
void getresponse(const char *payload, size_t length){
Serial.printf("response: ",payload);
String data = String(payload);
data.replace("\\","");
JSONVar dato = JSON.parse(data);
Serial.println(dato["litros"]);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
Serial.print("\nStarting WebServer on "); Serial.print(BOARD_NAME);
Serial.print(F(" with ")); Serial.println(SHIELD_TYPE);
Serial.println(ETHERNET_GENERIC_VERSION);
#if (USING_SPI2)
#if defined(CUR_PIN_MISO)
ETG_LOGWARN(F("Default SPI pinout:"));
ETG_LOGWARN1(F("MOSI:"), CUR_PIN_MOSI);
ETG_LOGWARN1(F("MISO:"), CUR_PIN_MISO);
ETG_LOGWARN1(F("SCK:"), CUR_PIN_SCK);
ETG_LOGWARN1(F("SS:"), CUR_PIN_SS);
ETG_LOGWARN(F("========================="));
#endif
#else
ETG_LOGWARN(F("Default SPI pinout:"));
ETG_LOGWARN1(F("MOSI:"), MOSI);
ETG_LOGWARN1(F("MISO:"), MISO);
ETG_LOGWARN1(F("SCK:"), SCK);
ETG_LOGWARN1(F("SS:"), SS);
ETG_LOGWARN(F("========================="));
#endif
#if defined(ESP32)
// You can use Ethernet.init(pin) to configure the CS pin
//Ethernet.init(10); // Most Arduino shields
//Ethernet.init(5); // MKR ETH shield
//Ethernet.init(0); // Teensy 2.0
//Ethernet.init(20); // Teensy++ 2.0
//Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet
//Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet
#endif
#ifndef USE_THIS_SS_PIN
#define USE_THIS_SS_PIN 5 //22 // For ESP32
#endif
ETG_LOGWARN1(F("ESP32 setCsPin:"), USE_THIS_SS_PIN);
// Must use library patch for Ethernet, EthernetLarge libraries
// ESP32 => GPIO2,4,5,13,15,21,22 OK with Ethernet, Ethernet2, EthernetLarge
// ESP32 => GPIO2,4,5,15,21,22 OK with Ethernet3
//Ethernet.setCsPin (USE_THIS_SS_PIN);
Ethernet.init (USE_THIS_SS_PIN);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
uint16_t index = millis() % NUMBER_OF_MAC;
// Use Static IP
//Ethernet.begin(mac[index], ip);
Ethernet.begin(mac[index]);
//SPIClass SPI2(HSPI);
//Ethernet.begin(mac[index], &SPI2);
// Just info to know how to connect correctly
// To change for other SPI
#if defined(CUR_PIN_MISO)
ETG_LOGWARN(F("Currently Used SPI pinout:"));
ETG_LOGWARN1(F("MOSI:"), CUR_PIN_MOSI);
ETG_LOGWARN1(F("MISO:"), CUR_PIN_MISO);
ETG_LOGWARN1(F("SCK:"), CUR_PIN_SCK);
ETG_LOGWARN1(F("SS:"), CUR_PIN_SS);
ETG_LOGWARN(F("========================="));
#else
ETG_LOGWARN(F("Currently Used SPI pinout:"));
ETG_LOGWARN1(F("MOSI:"), MOSI);
ETG_LOGWARN1(F("MISO:"), MISO);
ETG_LOGWARN1(F("SCK:"), SCK);
ETG_LOGWARN1(F("SS:"), SS);
ETG_LOGWARN(F("========================="));
#endif
Serial.print(F("Using mac index = "));
Serial.println(index);
Serial.print(F("Connected! IP address: "));
Serial.println(Ethernet.localIP());
if ( (Ethernet.getChip() == w5500) || (Ethernet.getAltChip() == w5100s) )
{
Serial.print(F("Speed: ")); Serial.print(Ethernet.speedReport());
Serial.print(F(", Duplex: ")); Serial.print(Ethernet.duplexReport());
Serial.print(F(", Link status: ")); Serial.println(Ethernet.linkReport());
}
Serial.println("LLego a la parte de initwebsocket y task");
Serial.println("termino inits");
// tcpip_adapter_init();
// for (int i = TCPIP_ADAPTER_IF_STA; i < TCPIP_ADAPTER_IF_MAX; i++) {
// if (tcpip_adapter_is_netif_up((tcpip_adapter_if_t)i))
// ESP_LOGI(TAG, "interface %i up ", i);
// else
// ESP_LOGI(TAG, "interface %i down ", i);
// }
esp_netif_init();//ojo con esta funcion https://gitter.im/espressif/arduino-esp32?at=607b291f06e2e024e85cdf50
initWebSocket();
// xTaskCreatePinnedToCore(Task1code,"Task1",10000,NULL,1,&Task1,0);
}
void loop()
{
//socketio.loop();
//socketIO.emit("getPrueba","{\"hello world\"}");
//socketIO.emit("plainString", "\"this is a plain string\"");
socketIO.emit("setRele","{\"Dato\":\"hola\"}");
delay(500);
//socketIO.emit("app","{\"name\":\"hola ese\",\"chava\":\"hola chava\"}");//esta libreria solo maneja archivos json
socketIO.emit("getPrueba","{\"name\":\"hola ese\",\"SERVIDOR\":\"HOLA MUNDO\"}");
//socketIO.emit("setData","{\"Dato\":\"hola\",\"Dato2\":\"Andre\"}");
//socketIO.on("get",getresponse);
delay(500);
socketIO.loop();
}
i only use two events to emit to the server they are setRele and getprueba as shown in the loop
server java script:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http,{allowEIO3: true ,cors: {origins: ['http://localhost:4200', 'http://localhost']}});
var port = process.env.PORT || 8080;
app.get('/', (req, res) => {
console.log("app works");
});
io.on('connection', (socket) => {
console.log(socket.id);
/**Catalogos */
// socket.emit("GetConfiguracion","{\"code\":\"ECOA-0179\",\"cambio\":\"0\",\"idRespuesta\":\"1\",\"Pines\":[{},{}]}");
// socket.emit("Reiniciar","{\"CodigoMDC\":\"ECOA-0179\"}");
// socket.emit("SetRelee","{\"code\":\"ECOA-0179\",\"f\":\"2022/04/26 03:51:33\",\"p\":\"26\",\"v\":\"1.00\"}");
socket.on("stateChanged", (params) => {
console.log(params); // x8WIv7-mJelg7on_ALbx
});
socket.on("getPrueba", (params) => {
console.log(params); // x8WIv7-mJelg7on_ALbx
});
socket.on("setRele", (params) => {
console.log(params); // x8WIv7-mJelg7on_ALbx
//socket.emit("SetRelee","{\"code\":\"ECOA-0179\",\"f\":\"2022/04/26 03:51:33\",\"p\":\"26\",\"v\":\"1.00\"}");
});
socket.on("ConfiguracionAplicada", (params) => {
console.log(params); // x8WIv7-mJelg7on_ALbx
});
socket.on('disconnect', () =>
{
console.log("Desconectado id: ",socket.id);
});
});
http.listen(port, () => {
console.log('listening on :' + port);
});
If someone could help me, it would be very helpful. Thank you. I'm new to ethernet connectivity. I hope you understand.

Why is this POST request from ESP32 to control KASA smart plug not working?

I am trying to communicate to a KASA HS103 smart plug using an HTTPS POST request sent via ESP32 (LoRa V2). For the actual POST content, I'm quite new to HTTP and have been following the instructions here: https://itnerd.space/2017/01/22/how-to-control-your-tp-link-hs100-smartplug-from-internet/
This is the POST request I am trying to send (with token & IDs modified):
URL: https://use1-wap.tplinkcloud.com/?token=fb2f7209-ATebDhHDOxB2wWc6wslPewO&appName=Kasa_Android&termID=1263f577-4387-4d3e-be79-705445d33bb08&appVer=1.4.4.607&ospf=Android+6.0.1&netType=wifi&locale=en_US
{
"method":"passthrough",
"params":{
"deviceId":"80068FEB5A735A5BB187B4EC309EF1BE1D6D8997",
"requestData":"{\"system\":{\"set_relay_state\":{\"state\":1}}}"
}
}
This will turn on the smart plug. I have verified that the POST request itself works, with both an online API tester (https://reqbin.com/) and through cURL on my MacBook.
I retrieved the URL token and device ID by authenticating with TP-Link server using my credentials through the API tester (also in the instructions linked above).
However, I am unable to control the smart plug when sending with ESP32. I am writing and compiling through the Arduino IDE, using the Heltec framework / libraries. Here is my code (started with the code from Rui Santos here and modified for my application):
/*
Rui Santos
Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
const char* ssid = "XXXXX";
const char* password = "XXXXX";
//Your Domain name with URL path or IP address with path
const char* serverName = "https://use1-wap.tplinkcloud.com/?token=fb2f7209-ATebDhHDOxB2wWc6wslPewO&appName=Kasa_Android&termID=1263f577-4387-4d3e-be79-705445d33bb08&appVer=1.4.4.607&ospf=Android+6.0.1&netType=wifi&locale=en_US HTTP/1.1";
const int port = 443;
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
//Send an HTTP POST request every 10 minutes
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClientSecure *client = new WiFiClientSecure;
if (client) {
Serial.println("Client Created!");
//client -> setCACert(rootCACertificate);
{
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(*client, serverName);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
//int httpResponseCode = http.POST("{\"api_key\":\"tPmAT5Ab3j7F9\",\"sensor\":\"BME280\",\"value1\":\"24.25\",\"value2\":\"49.54\",\"value3\":\"1005.14\"}");
int httpResponseCode = http.POST("{\"method\":\"passthrough\", \"params\": {\"deviceId\": \"80068FEB5A735A5BB187B4EC309EF1BE1D6D8997\", \"requestData\": \"{\"system\":{\"set_relay_state\":{\"state\":0}}}\" }}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.print("HTTP String: ");
Serial.println(payload);
// Free resources
http.end();
}
delete client;
} else {
Serial.println("Unable to create client");
}
} else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}
Here is the output from the serial terminal:
Connected to WiFi network with IP Address: 192.168.X.XXX
Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.
Client Created!
HTTP Response code: 200
HTTP String: {"error_code":-10100,"msg":"JSON format error"}
The smart plug does not turn off when uploading and running on ESP32.
Doing a quick search online for POST response codes, receiving 200 seems to mean the request was processed and OK, yet the error code is negative and message is "JSON format error".
Any ideas why this POST request is not working? Or anything I should try to get more info?
Thanks in advance!
Digging into "JSON format error" - turns out I had an extra "" around the 'requestData' value which parsed fine in cURL but could not be understood when sending raw through ESP32.
Removing those quotes fixed the problem and now I'm able to send POST requests successfully.
Here is the working code now:
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>
const char* ssid = "XXXXX";
const char* password = "XXXXX";
//Your Domain name with URL path or IP address with path
const char* serverName = "https://use1-wap.tplinkcloud.com/?token=fb2f7209-ATebDhHDOxB2wWc6wslPewO&appName=Kasa_Android&termID=1163f577-4288-4d3d-be69-705445d33ba08&appVer=1.4.4.607&ospf=Android+6.0.1&netType=wifi&locale=en_US HTTP/1.1";
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
//Send an HTTP POST request every 10 minutes
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClientSecure *client = new WiFiClientSecure;
if (client) {
{
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(*client, serverName);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST("{\"method\":\"passthrough\",\"params\":{\"deviceId\":\"80068FEB3A733B5BB287B4EC309FE1BE1D7D8997\",\"requestData\":{\"system\":{\"set_relay_state\":{\"state\":1}}}}}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.print("HTTP String: ");
Serial.println(payload);
// Free resources
http.end();
}
delete client;
} else {
Serial.println("Unable to create client");
}
} else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}

Problems receiving (all) LoRa Packets

At the moment I try to send packets between one Heltec WIFI LoRa V2 and another by reading the serial-line and sending the input via LoRa.
Small packets (like 30 bytes) work every time, but as bigger the packet gets the packet won't be received every time or even never.
So I write a little sending loop, where my sender sends at every iteration a packet, which gets every time 10 byte bigger, and surprisingly every packet was received by the sender (I tried that until 500 bytes).
After that, I wanted to send a 80 byte serial input message and this did not work. Do you know what's the problem with that?
void setup() {
// ... LoRa.begin(); ....
LoRa.onReceive(onReceive);
// ... LoRa.receive(); ...
}
void onReceive(int packetSize) { // uses the interrupt pin on the dio0
String packet = "";
packSize = String(packetSize,DEC);
for (int i = 0; i < packetSize; i++) {
packet += (char) LoRa.read();
}
Serial.println(packet);
delay(5);
} ```
``` // writer
boolean sendPacket (String packet) {
Serial.println("Send begin");
LoRa.beginPacket(false); // true: optional implicit mode (--> Set everything on both sides?!)
LoRa.setTxPower(14,RF_PACONFIG_PASELECT_PABOOST);
LoRa.print(packet); // also LoRa.write(byte(, length));
LoRa.endPacket(false); // true: async mode: doas not wair until transmission is completed
delay(250);
// put the radio into receive mode
LoRa.receive(); // set redio back in receive mode
delay(750);
Serial.println("Send end");
return true; // will be changed
}
void loop(){
while(Serial.available() > 0 ){
delay(2); //delay to allow byte to arrive in input buffer
String text = Serial.readString();
digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level)
boolean packetSent = false;
while (!packetSent) {
packetSent = sendPacket(text);
if (packetSent) {
Serial.print("Packet has been sent: ");
Serial.println(text);
} else {
Serial.print("Retry sending packet: ");
Serial.println(text);
}
}
digitalWrite(LED, LOW); // turn the LED off (HIGH is the voltage level)
}
} ```

How to Wake ES8266 from deep sleep on Dev board NodeMCU

Basically, my project uses a force-sensing resistor to detect occupancy on the chair. The ESP8266 WiFi would wake from the sleep mode and send an update to the server. If there is no occupancy, the ESP8266 goes back to sleep.
My project uses Wiolink, a dev board that uses a ESP8266 WiFi chip. Hence, it is quite impossible to connect GPIO 16 to RST to wake up ( or reset ) the device.
Deep sleep is predefined at a set amount of time using this function ESP.deepsleep(). Is it possible to wake up with an external interrupt such as the force sensing resistor?
String apiKey = ""; // const char* ssid = ""; // wifi username const
char* password = ""; // wifi password
void setup() // Defines the initial condition of the hardware board.
{
Serial.begin(115200); delay(10);
}
void loop() // Defines the loop condition of the hardware board. {
sensorReading = analogRead(A0);
if(sensorReading >= 150) // Condition when someone is sitting;
{
//Wake ESP8266
//perform server update
}
if(sensorReading <=149) // Condition for no one sitting;
{
Serial.println("Going into deep sleep");
ESP.deepSleep(); //
}

Resources