I'm trying to send JSON messages to https://api.openai.com/v1/completions using ESP8266. The problem is why when the program is run it always results in bad requests?
This is my code:
#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>
//#include <HttpClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ArduinoJson.h> // library untuk menangani JSON
const char* ssid = "DIVA MEDIA";
const char* password = "media1213";
const char* host = "api.openai.com";
const int httpsPort = 443;
WiFiClient client;
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");
if (!client.connect(host, httpsPort)) {
Serial.println("Connection failed");
return;
}
HTTPClient http;
WiFiClient client;
// JSON data yang akan dikirim
String jsonData = "{\"prompt\":\"What is the capital of France?\",\"model\":\"text-davinci-002\"}";
// Kirim permintaan ke API OpenAI
http.begin(client,"https://api.openai.com/v1/completions");
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Bearer api");
int httpCode = http.POST(jsonData);
// Cek kode respon
if (httpCode > 0) {
String response = http.getString();
Serial.println(response);
} else {
Serial.println("Error: " + http.errorToString(httpCode));
}
http.end();
// Delay sebelum mengirim permintaan berikutnya
delay(5000);
}
void loop() {
// nothing to do here
}
and this is error:
Related
I'm trying to POST data to a URL using the ESP8266HTTPClient library, but I keep getting 400 errors. I verified that I can POST to that URL via Postman, so I'm not sure why it keeps failing with this sketch.
The output is:
Sending data to https://my-project.firebaseio.com/users/MY_USER_ID.json
{"timestamp":"2021-10-28 14:20:00","duration":"1"}
HTTP Response code: 400
Full code below:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
// WiFi configuration
const char *ssid = "MY_SSID";
const char *password = "MY_PASSWORD";
// Database configuration
const String userId = "MY_USER_ID";
const String baseUrl = "https://my-project.firebaseio.com";
void setup()
{
delay(1000);
Serial.begin(9600);
Serial.print("Configuring access point...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
}
bool shouldSendData = true;
void loop()
{
if (shouldSendData)
{
Serial.println("Attempting to send data...");
if (WiFi.status() == WL_CONNECTED)
{
WiFiClient client;
HTTPClient http;
String url = baseUrl + "/users/" + userId + ".json";
http.begin(client, url);
http.addHeader("Content-Type", "application/json");
String data = "{\"timestamp\":\"2021-10-28 14:20:00\",\"duration\":\"1\"}";
int httpResponseCode = http.POST(data);
Serial.print("Sending data to ");
Serial.println(url);
Serial.println(data);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
}
else
{
Serial.println("Unable to send data. WiFi is not connected.");
}
shouldSendData = false;
}
}
I tried to Run this code but the connection fails and HTTPCode returns -1 , I'm using WIFI manager and it works sucessfully connected to the network
the link is worked successfully on POSTman and data posted in Database
Hi All, I tried to Run this code but the connection fails and HTTPCode returns -1 , I'm using WIFI manager and it works sucessfully connected to the network
the link is worked successfully on POSTman and data posted in Database
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <WiFiManager.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>
IPAddress staticIP750_100(192,168,1,16);
IPAddress gateway750_100(192,168,1,1);
IPAddress subnet750_100(255,255,255,0);
HTTPClient http;
#define ONE_WIRE_BUS 2 // DS18B20 on NodeMCU pin D4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float temp_0;
const char* host = "http://mysite2020.info";
void setup()
{
Serial.begin(115200);
WiFiManager wifimanger ;
DS18B20.begin();
Wire.begin(D2, D1)
readTemp();
WiFi.mode(WIFI_STA);
wifimanger.autoConnect("Inlet Device","12345");
while ((!(WiFi.status() == WL_CONNECTED))){
delay(300);
Serial.println("...");
}
Serial.println("WiFi connected");
WiFi.config(staticIP750_100, gateway750_100, subnet750_100);
WiFi.hostname("Inlet Device") ;
delay(3000);
Serial.println("Welcome To Device No : 1");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Your Gateway is : ");
Serial.println((WiFi.gatewayIP().toString().c_str()));
Serial.println("Your Hostname is : ");
Serial.println((WiFi.hostname()));
delay(3000);
Serial.println("Welcome to my Project!");
delay(3000);
}
void loop() {
Serial.println(host); // Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort))
{
Serial.println("connection failed");
return;
}
Serial.print("Requesting URL: ");
sendtemp ();
}
void sendtemp ()
{
temp_0=23.26;
String url = "http://mysite2020.info/Api/insert_mssqlserver.php?Reading=" + String(temp_0);
Serial.println(url);
http.begin(url);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
auto httpCode = http.GET();
Serial.println(httpCode); //Print HTTP return code
String payload = http.getString();
Serial.println(payload); //Print request response payload
http.end(); //Close connection Serial.println();
Serial.println("closing connection");
delay(500);
}
I am communicating two ESP32 boards which are connected to a Wifi Network. One ESP32 board is the Server and the other is the client. I want to measure the ESP32 CPU utlization on the client ESP32. I have no idea how to do it and have not yet found any useful resources on the internet. Can someone help me with this?
This is the code on server
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
const char* ssid = "XXXXX";
const char* password = "XXXX";
AsyncWebServer server(80);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid,password);
while (WiFi.status()!= WL_CONNECTED){
delay(200);
Serial.println("Connecting to Wifi...");
}
Serial.println("Connected to Wifi");
Serial.println(WiFi.localIP());
server.on("/test", HTTP_GET, [](AsyncWebServerRequest *request){
Serial.println("Request received from esp32client");
request->send(200, "text/plain", "Hello from ESP32Server to ESP32Client");
});
server.on("/test1", HTTP_GET, [](AsyncWebServerRequest *request){
Serial.println("Request received from PC-Client");
request->send(300, "text/plain", "Hello from ESP32Server to PC");
});
server.begin();
}
void loop() {
// put your main code here, to run repeatedly:
}
This is the code on Client
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "XXXXX";
const char* password ="XXXXX";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid,password);
while (WiFi.status()!= WL_CONNECTED){
delay(500);
Serial.println("Connecting to Wifi...");
}
Serial.println("Connected to Wifi Network...");
Serial.println(WiFi.localIP());
}
void loop() {
HTTPClient http;
http.begin("http://192.168.43.35/test");
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end();
delay(30000);
}
Use this function to get CPU load
vTaskGetRunTimeStats(char *buffer);
It tells CPU utilization by currently running task on esp32.
API documentation here.
I can't use the POST() function properly or don't know how to
I get this error message
no matching function for call to 'HTTPClient::POST(ArduinoJson::JsonObject&)
When I try to send a JSON object inside the POST() function, I get the following return message:
{
"error": "ParseError",
"description": "Errors found in incoming JSON buffer"
}
When I try to simply write JSON as string in POST() function and try to send it that way
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h> //v5.13.5
const char* ssid = "**";
const char* password = "**";
void setup() {
Serial.begin(115200);
delay(4000);
WiFi.begin(ssid,password);
while (WiFi.status() != WL_CONNECTED) { //Check for the connection
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
Serial.println("Connected to the WiFi network");
}
void loop() {
if(WiFi.status() == WL_CONNECTED){
HTTPClient http;
http.begin("http://172.20.10.13:1026/v2/entities"); //My docker
http.addHeader("Content-Type", "application/json");
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["id"] = "urn:ngsi-ld:Sensor:001";
root["type"] = "motion";
root["value"] = "No";
root.printTo(Serial);
/*int httpResponseCode = http.POST("{\n\t\"id\":\"urn:ngsi-ld:Sensor:001\", \"type\":\"MotionSensor\",\n\t\"value\":\"NO\"\n}"); */
int httpResponseCode = http.POST(root);
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();
}
else{
Serial.println("Error in WiFi connection");
}
delay(300000);
}
Result should be a functioning POST request into docker and data stored, while i can read that data with GET command in terminal on my VM
The argument for HTTPClient.POST is Arduino String (or a C string) and you can't simply pass your JSON object. You need to use prettyPrintTo to convert your json object to a standard JSON string and next pass it to the POST function.
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h> //v5.13.5
const char *ssid = "**";
const char *password = "**";
void setup()
{
Serial.begin(115200);
delay(4000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{ //Check for the connection
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
Serial.println("Connected to the WiFi network");
}
void loop()
{
if (WiFi.status() == WL_CONNECTED)
{
HTTPClient http;
http.begin("http://172.20.10.13:1026/v2/entities"); //My docker
http.addHeader("Content-Type", "application/json");
StaticJsonBuffer<200> jsonBuffer;
JsonObject &root = jsonBuffer.createObject();
root["id"] = "urn:ngsi-ld:Sensor:001";
root["type"] = "motion";
root["value"] = "No";
root.printTo(Serial);
/*int httpResponseCode = http.POST("{\n\t\"id\":\"urn:ngsi-ld:Sensor:001\", \"type\":\"MotionSensor\",\n\t\"value\":\"NO\"\n}"); */
char json_str[100];
root.prettyPrintTo(json_str, sizeof(json_str));
int httpResponseCode = http.POST(json_str);
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();
}
else
{
Serial.println("Error in WiFi connection");
}
delay(300000);
}
I am trying to make a simple esp01 wifi hotspot + a simple webpage with 3 buttons that send ints(1,2,3) over serial when pressed. But the wifi hotspot isn't working.
Here is the code:
#include <ESP8266WiFi>;
#include <WiFiClient>;
#include <ESP8266WebServer>;
const char *ssid = "test";
const char *password = "password";
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);
void setup() {
delay(1000);
Serial.begin(9600);
WiFi.softAPConfig(local_IP, gateway, subnet);
WiFi.softAP(ssid, password);
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (!client)
{
return;
}
while(!client.available())
{
delay(1);
}
String request = client.readStringUntil('\r');
client.flush();
if (request.indexOf("/R1") != -1)
{
Serial.println("1");
}else if (request.indexOf("/R2") != -1)
{
Serial.println("2");
}else if (request.indexOf("/R3") != -1)
{
Serial.println("3");
}
client.println("Content-Type: text/html");
client.println("");
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<head><title>ESP01 RELAY Control</title></head>");
client.println("<body>");
client.println("<br>");
client.println("<button href=\"/R1\">R:1</button>");
client.println("<button href=\"/R2\">R:2</button>");
client.println("<button href=\"/R3\">R:3</button>");
client.println("<br>");
client.println("<button href=\"/T1\">T:1</button>");
client.println("<button href=\"/T2\">T:2</button>");
client.println("<button href=\"/T3\">T:3</button>");
client.println("</body>");
client.println("</html>");
delay(1);
}
To program an ESP8622 it is best practice to use the Serial.println() command to debug your code. For setting up a working access point (AP) on a ESP8622 module, use the following code;
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char *ssid = "test";
const char *password = "password";
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);
void setup() {
delay(1000);
Serial.begin(9600);
Serial.print("Setting soft-AP configuration ... ");
Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");
Serial.print("Setting soft-AP ... ");
Serial.println(WiFi.softAP(ssid, password) ? "Ready" : "Failed!");
Serial.print("Soft-AP IP address = ");
Serial.println(WiFi.softAPIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if(client){
while (client.connected()) {
if(client.available()){
Serial.println("Connected to client");
}
}
// close the connection:
client.stop();
}
}