Yaptığım projede ESP8266 ile bir web server'ına hem veri gondermem hem de veri almam gerekiyor. Bunun için Node.js'i kullanıyorum. ESP8266'dan Node.js sunucusuna veri göndermeyi yaptım fakat bir turlu Node.js sunucusundan ESP8266'ta veri gönderemiyorum ne yapmam lazım.
Şimdiye kadar yazdığım kodlar:
Node.js server kodları:
ESP8266'nın kodları:
Şimdiye kadar yazdığım kodlar:
Node.js server kodları:
JavaScript:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors()); // CORS ayarlarını ekleyin.
app.use(bodyParser.json());
// Basit HTML dosyası sunma.
app.get('/', (req, res) => {
res.send(`
<html>
<head><title>Data Display</title></head>
<body>
<h1>Data from ESP8266</h1>
<p id="key1">Key1: N/A</p>
<p id="key2">Key2: N/A</p>
<script>
async function fetchData() {
try {
const response = await fetch('/api/endpoint');
if (!response.ok) {
throw new Error('HTTP error: ' + response.status);
}
const data = await response.json();
document.getElementById('key1').textContent = 'Key1: ' + data.key1;
document.getElementById('key2').textContent = 'Key2: ' + data.key2;
} catch (error) {
console.error('Error fetching data:', error);
document.getElementById('key1').textContent = 'Key1: Error';
document.getElementById('key2').textContent = 'Key2: Error';
}
}
window.onload = fetchData;
</script>
</body>
</html>
`);
});
// POST isteği ile verileri alıyoruz.
app.post('/api/endpoint', (req, res) => {
receivedData = req.body;
console.log('Data received:', receivedData);
res.send('Data received');
});
// GET isteği ile verileri döndürüyoruz.
app.get('/api/endpoint', (req, res) => {
if (!receivedData) {
return res.status(404).json({ error: 'No data available' });
}
res.json(receivedData);
});
// Sunucuyu başlatıyoruz.
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
ESP8266'nın kodları:
C++:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "Conkara_wifi";
const char* password = "Bahattin4535";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
WiFiClient client;
// POST request.
http.begin(client, "http://192.168.1.4:3000/api/endpoint");
http.addHeader("Content-Type", "application/json");
StaticJsonDocument<200> doc;
doc["key1"] = "MERHABA";
doc["key2"] = "DUNYA";
String requestBody;
serializeJson(doc, requestBody);
int httpResponseCode = http.POST(requestBody);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
// GET request.
http.begin(client, "http://192.168.1.4:3000/api/endpoint");
httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
StaticJsonDocument<200> responseDoc;
DeserializationError error = deserializeJson(responseDoc, response);
if (!error) {
const char* value1 = responseDoc["key1"];
const char* value2 = responseDoc["key2"];
Serial.print("Key1: ");
Serial.println(value1);
Serial.print("Key2: ");
Serial.println(value2);
} else {
Serial.println("Failed to parse response");
}
} else {
Serial.print("Error on sending GET: ");
Serial.println(httpResponseCode);
}
http.end();
}
delay(10000); // 10 seconds delay between requests.
}