Problem in Django cooperation with esp 8266 - django

Hello i need help with my django project . I want to run program on ESP 8266 from django website. To test I create simple program with blink diode on ESP and I made button on my django website and it works but I use "webbrowser()" in views.py and it is not looks perfect (I need to stay on this webiste, a webiste made in django, not open a new one). I need help to create something what will work like:
I click the button on my django website, program in "views.py" send something to esp what runs program on it or change something in the ESP code, which is only going to run the code, and it won't open web browser.
my views.py:
def espON(request):
on = On.objects.all()
off = Off.objects.all()
menu = menu.objects.all()
webbrowser.open("http://my_ip/turnOn")
d = {'on':on, 'off':off, 'menu':menu,}
return render(request, 'on/index.html', d)
ESP code:
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <Math.h>
const char* ssid = "my_ssid"; //nazwa ssid sieci
const char* password = "my_password"; //haslo
#define LED 5
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(LED, OUTPUT);
//Laczenie z siecia wifi
Serial.println();
Serial.println();
Serial.print("Laczenie z: ");
Serial.println(ssid);
IPAddress ip(my_ip); //ip
IPAddress gateway(my_ip2);
IPAddress subnet(my_ip3);
WiFi.config(ip, gateway, subnet);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi polaczone");
// Start
server.begin();
Serial.println("Serwer uruchomiony");
}
void loop() {
while (WiFi.status() == WL_CONNECTED){
WiFiClient client = server.available();
if (!client) {
return;
}
String request = client.readStringUntil('\r');
client.flush();
//condition
if (request.indexOf("/turnOn") > 0)
{
digitalWrite(LED, HIGH); //work
}
if (request.indexOf("/turnOff") > 0) //not
{
digitalWrite(LED, LOW);
}
}
}

Related

Compilation error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url), How can i solve this issue?

I run this code and get the massage:
Compilation error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
what can I do?
//----------------------------------------Include the NodeMCU ESP8266 Library
//----------------------------------------see here: https://www.youtube.com/watch?v=8jMr94B8iN0 to add NodeMCU ESP8266 library and board
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
//----------------------------------------
#define ON_Board_LED 2 //--> Defining an On Board LED (GPIO2 = D4), used for indicators when the process of connecting to a wifi router
#define LED_D8 15 //--> Defines an LED Pin. D8 = GPIO15
//---------------------------------------SSID and Password of your WiFi router.
const char* ssid = "*wifi name*"; //--> Your wifi name or SSID.
const char* password = "*Wfif password*"; //--> Your wifi password.
//----------------------------------------
//----------------------------------------Web Server address / IPv4
// If using IPv4, press Windows key + R then type cmd, then type ipconfig (If using Windows OS).
const char *host = "https://localhost/";
//----------------------------------------
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
delay(500);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password); //--> Connect to your WiFi router
Serial.println("");
pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output
digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board
pinMode(LED_D8,OUTPUT); //--> LED port Direction output
digitalWrite(LED_D8, LOW); //--> Turn off Led
//----------------------------------------Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
//----------------------------------------Make the On Board Flashing LED on the process of connecting to the wifi router.
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
//----------------------------------------
}
//----------------------------------------
digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected to the wifi router.
//----------------------------------------If successfully connected to the wifi router, the IP Address that will be visited is displayed in the serial monitor
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
//----------------------------------------
}
void loop() {
// put your main code here, to run repeatedly:
HTTPClient http; //--> Declare object of class HTTPClient
WiFiClient WiFiClient;
//----------------------------------------Getting Data from MySQL Database
String GetAddress, LinkGet, getData;
int id = 0; //--> ID in Database
GetAddress = "rafael/GetData.php";
LinkGet = host + GetAddress; //--> Make a Specify request destination
getData = "ID=" + String(id);
Serial.println("----------------Connect to Server-----------------");
Serial.println("Get LED Status from Server or Database");
Serial.print("Request Link : ");
Serial.println(LinkGet);
http.begin("LinkGet");
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCodeGet = http.POST(getData); //--> Send the request
String payloadGet = http.getString(); //--> Get the response payload from server
Serial.print("Response Code : "); //--> If Response Code = 200 means Successful connection, if -1 means connection failed. For more information see here : https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Serial.println(httpCodeGet); //--> Print HTTP return code
Serial.print("Returned data from Server : ");
Serial.println(payloadGet); //--> Print request response payload
if (payloadGet == "1") {
digitalWrite(LED_D8, HIGH); //--> Turn off Led
}
if (payloadGet == "0") {
digitalWrite(LED_D8, LOW); //--> Turn off Led
}
//----------------------------------------
Serial.println("----------------Closing Connection----------------");
http.end(); //--> Close connection
Serial.println();
Serial.println("Please wait 5 seconds for the next connection.");
Serial.println();
delay(5000); //--> GET Data at every 5 seconds
}
I want my esp8266 to connect to my database(MySql) and get a value to turn on/off a led light.
The esp im using is the NodeMCU epp8266.
Apart from the actual issue that causes the compile error there are several other things wrong with this code. I fixed the most obvious ones. See the explanations for the callouts below the code.
// <1>
#include <ESP8266WiFi.h>
//#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
//#include <ESP8266WiFi.h>
//#include <WiFiClient.h>
//#include <ESP8266WebServer.h>
//#include <ESP8266HTTPClient.h>
//#include <WiFiClientSecureBearSSL.h>
#define ON_Board_LED 2
#define LED_D8 15
const char* ssid = "********";
const char* password = "********";
// <2>
// <3>
const char* host = "http://192.168.1.1/";
// <4>
String GetAddress, LinkGet, getData;
int id = 0;
// <5>
HTTPClient http;
WiFiClient client;
// <6>
void connectWiFi() {
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
}
digitalWrite(ON_Board_LED, HIGH);
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
}
void setup() {
Serial.begin(115200);
delay(500);
// <7>
GetAddress = "rafael/GetData.php";
LinkGet = host + GetAddress;
getData = "ID=" + String(id);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
pinMode(ON_Board_LED, OUTPUT);
digitalWrite(ON_Board_LED, HIGH);
pinMode(LED_D8, OUTPUT);
digitalWrite(LED_D8, LOW);
}
void loop() {
// <8>
// // put your main code here, to run repeatedly:
// HTTPClient http; //--> Declare object of class HTTPClient
// WiFiClient WiFiClient;
// <9>
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
Serial.println("----------------Connect to Server-----------------");
Serial.println("Get LED Status from Server or Database");
Serial.print("Request Link : ");
Serial.println(LinkGet);
// <10>
http.begin(client, LinkGet);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCodeGet = http.POST(getData);
String payloadGet = http.getString();
Serial.print("Response Code : ");
Serial.println(httpCodeGet);
Serial.print("Returned data from Server : ");
Serial.println(payloadGet);
if (payloadGet == "1") {
digitalWrite(LED_D8, HIGH);
}
if (payloadGet == "0") {
digitalWrite(LED_D8, LOW);
}
Serial.println("----------------Closing Connection----------------");
http.end();
Serial.println();
Serial.println("Please wait 5 seconds for the next connection.");
Serial.println();
delay(5000);
}
Clean up the includes such that only those remain which you actually need.
With this sketch your host cannot be (and likely is not) reachable using SSL/TLS encryption (https -> http).
localhost is wrong as this would point to the ESP8266 itself (loopback). You need the PC IP address or possibly its hostname here.
Declare global variables globally i.e. outside loop().
Declare and initialize the HTTPClient and WiFiClient globally rather than inside the loop(). See my answer here https://stackoverflow.com/a/59701884/131929 for more.
Put the WiFi-connecting code in a separate function - you'll need it later.
Initialize the global variables in setup() rather than loop(); goes along with <4>.
Don't instantiate those over and over again; goes along with <5>.
Verify the device is still connected to WiFi every time loop() is invoked and re-connect if not.
Compile error: http.begin() takes a WiFiClient plus that actual HTTP address. This is what the compile error message tells you.

Problem with MQTT server: Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

I'am hosting MQTT server on rPi, server works fine and i'am able to connect to it using different machine (PC-ubuntu), but arduino(wemos d1 mini) has a problem with that.
I have already set allow_anonymous to true in config file, and run sudo ufw allow 1883.
Nothing seems to work for me :c
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>
#include "arduino_secrets.h"
// Connect to the WiFi
const char* ssid = SECRET_SSID;
const char* password = SECRET_PASS;
//const char* mqtt_server = "192.168.0.158"; //at first was using this
IPAddress ip(192, 168, 1, 100); //then switched to this, but with no effect
IPAddress server(192, 168, 0, 158);
IPAddress mqtt_server = {192, 168, 0, 158};
WiFiClient espClient;
PubSubClient client(espClient);
const byte ledPin = D4; // digital pin 4 on a weMos D1 mini is next to ground so easy to stick a LED in.
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
char receivedChar = (char)payload[i];
Serial.print(receivedChar);
if (receivedChar == '1')
digitalWrite(ledPin, HIGH);
if (receivedChar == '0')
digitalWrite(ledPin, LOW);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("DUPADUPA")) {
delay(2000);
Serial.println("connected");
client.subscribe("real_unique_topic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(9600);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
delay(5000);
digitalWrite(ledPin, LOW);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
Also checked another lib: <ArduinoMqttClient.h>, but the same error appears.
PS: Also tried code from here: https://docs.arduino.cc/tutorials/uno-wifi-rev2/uno-wifi-r2-mqtt-device-to-device - works for "test.mosquitto.org", but not with rPi ip

ESP32 with Rest Api in Cloud Firestore

I'm working with ESP32 with Cloud Firestore. I'm attempting to make a request to get the data from a certain collection and document.
I have been able to access a single collection but, I'm having problems accessing a subcollection.
This is my ESP32 code to get the collection data:
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#define lamp 13
const char* ssid = "SSID";
const char* password = "Ok";
void setup() {
Serial.begin(115200);
pinMode(lamp, OUTPUT);
WiFi.begin(ssid, password);
delay(5000);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED){
delay(1000);
Serial.print(".");
}
}
void loop() {
if (WiFi.status() == WL_CONNECTED){
HTTPClient http;
http.begin("stuff.net/app/api/read/5j5UF0lFovW8g5QSXXymWYsz0QB2");
int httpCode = http.GET();
if (httpCode > 0){
String payload = http.getString(); //ISSO É PARA GET REQUEST
Serial.println(httpCode);
Serial.println(payload);
char json[500];
payload.toCharArray(json, 500);
StaticJsonDocument<1024> doc;
deserializeJson(doc, json);
String device0 = doc["device0"];
}
http.end();
}else{
Serial.println("Erro com conexão, chekar conexão ao WiFi");
}
delay(1000);
}
This is how my Firestore looks:
I have attempted:
https://stuff.net/app/api/read/5j5UF0lFovW8g5QSXXymWYsz0QB2/buttons/button0
Won't work

ESP32 to ESP32 AP/client WiFi connection problem

Trying to communicate from one ESP32 to another ESP32 ,with one acting as a AP and another acting as Client but cant seem to connect the esp client to the esp AP, but connecting to AP using my smartphone works.Sorry if this seems to be a simple questions, I am new to esp32s and WiFI communication.
Code for the Access-point
#include <WiFi.h>
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
Serial.println("Setting AP (Access Point)…");
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
Serial.print("MAC address: ");
Serial.println(WiFi.softAPmacAddress());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client)
{ Serial.println("New Client.");
while (client.connected())
{
Serial.println(client.connected());
Serial.println("Client connected.");
Serial.println("");
}
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Code for the Client
#include <WiFi.h>
#include <SPI.h>
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
scanNetworks();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
}
void loop() {
}
void scanNetworks() {
// scan for nearby networks:
Serial.println("** Scan Networks **");
byte numSsid = WiFi.scanNetworks();
// print the list of networks seen:
Serial.print("SSID List:");
Serial.println(numSsid);
// print the network number and name for each network found:
for (int thisNet = 0; thisNet<numSsid; thisNet++) {
Serial.print(thisNet);
Serial.print(") Network: ");
Serial.println(WiFi.SSID(thisNet));
}
}
As #juraj mentions, in the Arduino code for ESP32, you cannot initiate a scan while an attempt to connect to AP is already ongoing.
Call scanNetworks() before attempting to connect (before the WiFi.begin(ssid, password);).
or
Call scanNetworks() after the connection to the AP has been established (after the while (WiFi.status() != WL_CONNECTED){}).
I don't see any point to scan networks while trying to connect to a known WiFi AP anyway.
ESPnow (see example here ) is easy for ESP to ESP communication. (also ESP8266 etc)

led light is not responding over wifi from esp8266

Im trying to switch on and off led from from a local server created by esp8266.
Everything is working fine even esp also. Setup is working without ESP8266.
ESP is flashed with ESP8266_NONOS_SDK-2.2.0
Board used "Generic ESP8266 Module"
at COM Port 6
Arduino to bread board setup:-
pin 13 -> led
GND -> led
Arduino to ESP setup before burning sketch:-
Arduino - ESP8266
3.3v -> vcc + CH_PD
GND+RST -> GND + GPIO0
TXD -> TX
RXD -> RX
Arduino to ESP setup before burning sketch:-
Arduino - ESP8266
3.3v -> vcc + CH_PD
GND -> GND
TXD -> TX
RXD -> RX
COM output:
Connecting to lan
.......
WiFi connected
Server started
Use this URL to connect: http://192.168.43.80/
I already tried:-
using different pinsand also tried switching
RXD->TX and TXD->RX
the problem what i think im getting is the communication between ESP and arduino. Although blue led in ESP flashes when i click on ON or OFF and im getting response in SERIAL MONITOR also:-
COM OUTPUT:-
new client
GET /LED=OFF HTTP/1.1
Client disonnected
new client
GET /favicon.ico HTTP/1.1
Client disonnected
new client
GET /LED=ON HTTP/1.1
Client disonnected
new client
GET /favicon.ico HTTP/1.1
Client disonnected
Code I'm using:-
#include <ESP8266WiFi.h>
const char* ssid = "papa";
const char* password = "12345678ab";
int ledPin = 12; // GPIO13
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
digitalWrite(ledPin, HIGH);
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match the request
int value = LOW;
if (request.indexOf("/LED=ON") != -1) {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(ledPin, LOW);
value = LOW;
}
// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("Led pin is now: ");
if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
client.println("<br><br>");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button><br />");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}