type or paste code #include "WiFi.h"
#include <HTTPClient.h>
#include <U8g2lib.h>
#include <Wire.h>
#define OLED_SDA 21
#define OLED_SCL 22
#define BUTTON_UP 23
#define BUTTON_DOWN 19
#define BUTTON_SELECT 18
WiFiServer server(80);
WiFiClient client1;
HTTPClient https;
String chatgpt_Q;
String chatgpt_A;
String json_String;
uint16_t dataStart = 0;
uint16_t dataEnd = 0;
String dataStr;
int httpCode = 0;
typedef enum
{
do_webserver_index,
send_chatgpt_request,
get_chatgpt_list,
} STATE_;
STATE_ currentState;
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE, OLED_SCL, OLED_SDA);
const int MAX_NETWORKS = 20; // Maximum number of networks to display
String ssidList[MAX_NETWORKS];
int numNetworks = 0;
int selectedNetwork = 0;
boolean enteringPassword = false;
String password = "";
boolean connected = false;
const char* chatgpt_token = "sk-VymEZEqsWN6xxxxxTKo6PcY";
const char* chatgpt_server = "https://api.openai.com/v1/completions";
//1
const char html_page[] PROGMEM = {
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Connection: close\r\n" // the connection will be closed after completion of the response
//"Refresh: 1\r\n" // refresh the page automatically every n sec
"\r\n"
"<!DOCTYPE HTML>\r\n"
"<html>\r\n"
"<head>\r\n"
"<meta charset=\"UTF-8\">\r\n"
"<title>EVIANT: Espressif Voice Intelligence Assistant Navigation Technology</title>\r\n"
"<link rel=\"icon\" href=\"https://files.seeedstudio.com/wiki/xiaoesp32c3-chatgpt/chatgpt-logo.png\" type=\"image/x-icon\">\r\n"
"</head>\r\n"
"<body>\r\n"
"<img alt=\"SEEED\" src=\"https://files.seeedstudio.com/wiki/xiaoesp32c3-chatgpt/logo.png\" height=\"100\" width=\"410\">\r\n"
"<p style=\"text-align:center;\">\r\n"
"<img alt=\"ChatGPT\" src=\"https://files.seeedstudio.com/wiki/xiaoesp32c3-chatgpt/chatgpt-logo.png\" height=\"200\" width=\"200\">\r\n"
"<h1 align=\"center\">EVIANT</h1>\r\n"
"<h1 align=\"center\">by Belocura, Caga, Deocos, Palomera</h1>\r\n"
"<div style=\"text-align:center;vertical-align:middle;\">"
"<form action=\"/\" method=\"post\">"
"<input type=\"text\" placeholder=\"Please enter your question\" size=\"35\" name=\"chatgpttext\" required=\"required\"/>\r\n"
"<input type=\"submit\" value=\"Submit\" style=\"height:30px; width:80px;\"/>"
"</form>"
"</div>"
"</p>\r\n"
"</body>\r\n"
"<html>\r\n"
};
// Function prototypes
void setup();
void loop();
void scanNetworks();
void displayNetworks();
void displayPasswordInput();
void addNextChar();
void removeLastChar();
char getNextChar();
void connectToNetwork(String ssid, String password);
void setup() {
Serial.begin(115200);
Wire.begin();
u8g2.begin();
u8g2.setFont(u8g2_font_ncenB08_tr); // Adjust font as needed
pinMode(BUTTON_UP, INPUT_PULLUP);
pinMode(BUTTON_DOWN, INPUT_PULLUP);
pinMode(BUTTON_SELECT, INPUT_PULLUP);
scanNetworks();
}
void loop() {
if (!enteringPassword && !connected) {
handleNetworkSelection();
} else if (enteringPassword && !connected) {
handlePasswordEntry();
} else {
handleConnectionStatus();
}
}
void wrapText(String text, int startX, int startY, int maxWidth) {
int lineHeight = u8g2.getFontAscent() - u8g2.getFontDescent();
int y = startY + lineHeight; // Start at the first line
String line = "";
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
int charWidth = u8g2.getUTF8Width(&c);
if (charWidth + u8g2.getUTF8Width(line.c_str()) <= maxWidth) {
line += c;
} else {
// Print the line and move to the next line
u8g2.setCursor(startX, y);
u8g2.print(line);
y += lineHeight;
line = c;
}
}
// Print the last line
u8g2.setCursor(startX, y);
u8g2.print(line);
}
void scanNetworks() {
Serial.println("Scanning networks...");
u8g2.clearBuffer();
u8g2.setCursor(0, 10);
u8g2.print("Scanning networks...");
u8g2.sendBuffer();
numNetworks = WiFi.scanNetworks();
if (numNetworks == 0) {
Serial.println("No networks found");
u8g2.clearBuffer();
u8g2.setCursor(0, 10);
u8g2.print("No networks found");
u8g2.sendBuffer();
} else {
Serial.print(numNetworks);
Serial.println(" networks found");
for (int i = 0; i < numNetworks && i < MAX_NETWORKS; ++i) {
ssidList[i] = WiFi.SSID(i);
}
displayNetworks();
}
}
void displayNetworks() {
u8g2.clearBuffer();
u8g2.setFont(u8g2_font_ncenB08_tr); // Set font size as needed
int lineHeight = u8g2.getFontAscent() - u8g2.getFontDescent();
int y = 10; // Initial y position
for (int i = 0; i < numNetworks; ++i) {
if (i == selectedNetwork) {
u8g2.setCursor(0, y);
u8g2.print(">");
} else {
u8g2.setCursor(0, y);
u8g2.print(" ");
}
u8g2.setCursor(10, y); // Set x position for each network name
u8g2.println(ssidList[i]);
y += lineHeight + 2; // Adjust line spacing as needed
}
u8g2.sendBuffer();
}
void displayPasswordInput() {
u8g2.clearBuffer();
u8g2.setCursor(0, 10);
u8g2.print("Enter password:");
u8g2.setCursor(0, 20);
u8g2.print(password);
u8g2.sendBuffer();
}
void addNextChar() {
char nextChar = getNextChar();
if (password.length() < 16) // Max password length
{
password += nextChar;
}
}
void removeLastChar() {
if (password.length() > 0) {
password.remove(password.length() - 1);
}
}
char getNextChar() {
static int charIndex = 0;
char nextChar = "Mics2002abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+"[charIndex];
charIndex = (charIndex + 1) % strlen("Mics2002abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+");
return nextChar;
}
void connectToNetwork(String ssid, String password) {
u8g2.clearBuffer();
u8g2.setCursor(0, 10);
u8g2.print("Connecting to ");
u8g2.println(ssid);
u8g2.sendBuffer();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid.c_str(), password.c_str());
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 10) {
delay(1000);
++attempts;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Connected to WiFi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
u8g2.clearBuffer();
u8g2.setCursor(0, 10);
u8g2.print("Connected to ");
u8g2.println(ssid);
u8g2.sendBuffer();
connected = true;
delay(3000);
// Clear buffer and set font for "EVIANT"
u8g2.clearBuffer();
u8g2.setFont(u8g2_font_profont29_mr);
int16_t x = (u8g2.getDisplayWidth() - u8g2.getStrWidth("EVIANT")) / 2;
int16_t y = u8g2.getAscent() + (u8g2.getDisplayHeight() - u8g2.getAscent() - u8g2.getDescent()) / 2;
u8g2.drawStr(x, y, "EVIANT");
// Set font size for IP address
u8g2.setFont(u8g2_font_profont15_mr);
// Calculate position to center horizontally
x = (u8g2.getDisplayWidth() - u8g2.getUTF8Width(WiFi.localIP().toString().c_str())) / 2;
// Set vertical position below "EVIANT"
y = y + u8g2.getAscent() + 10; // Adjust the value 10 to increase or decrease the space between "EVIANT" and IP address
u8g2.setCursor(x, y);
u8g2.print(WiFi.localIP().toString().c_str());
u8g2.sendBuffer();
// Set WiFi to station mode and disconnect from an AP if it was previously connected
WiFi.mode(WIFI_STA);
WiFi.disconnect();
while(!Serial);
Serial.println("WiFi Setup done!");
void connectToNetwork(String ssid, String password);
// Start the TCP server server
server.begin();
Serial.println("server started");
currentState = do_webserver_index;
} else {
Serial.println("Failed to connect to WiFi");
u8g2.clearBuffer();
u8g2.setCursor(0, 10);
u8g2.println("Failed to connect");
u8g2.sendBuffer();
}
}
void handleNetworkSelection() {
if (!digitalRead(BUTTON_UP)) {
selectedNetwork = (selectedNetwork == 0) ? numNetworks - 1 : selectedNetwork - 1;
displayNetworks();
delay(200);
} else if (!digitalRead(BUTTON_DOWN)) {
selectedNetwork = (selectedNetwork + 1) % numNetworks;
displayNetworks();
delay(200);
} else if (!digitalRead(BUTTON_SELECT)) {
// Enter password mode
enteringPassword = true;
displayPasswordInput();
}
}
void handlePasswordEntry() {
if (!digitalRead(BUTTON_UP)) {
addNextChar();
displayPasswordInput();
delay(200);
} else if (!digitalRead(BUTTON_DOWN)) {
removeLastChar();
displayPasswordInput();
delay(200);
} else if (!digitalRead(BUTTON_SELECT)) {
// Connect to network with entered password
connectToNetwork(ssidList[selectedNetwork], password);
}
}
void handleConnectionStatus() {
switch(currentState){
case do_webserver_index:
Serial.println("Web Production Task Launch");
client1 = server.available(); // Check if the client is connected
if (client1){
Serial.println("New Client."); // print a message out the serial port
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client1.connected()){
if (client1.available()){
char c = client1.read(); // Read the rest of the content, used to clear the cache
json_String += c;
if (c == '\n' && currentLineIsBlank) {
dataStr = json_String.substring(0, 4);
Serial.println(dataStr);
if(dataStr == "GET "){
client1.print(html_page); //Send the response body to the client
}
else if(dataStr == "POST"){
json_String = "";
while(client1.available()){
json_String += (char)client1.read();
}
Serial.println(json_String);
dataStart = json_String.indexOf("chatgpttext=") + strlen("chatgpttext="); // parse the request for the following content
chatgpt_Q = json_String.substring(dataStart, json_String.length());
client1.print(html_page);
Serial.print("Your Question is: ");
Serial.println(chatgpt_Q);
// close the connection:
delay(10);
client1.stop();
currentState = send_chatgpt_request;
}
json_String = "";
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
}
delay(1000);
break;
case send_chatgpt_request:
Serial.println("Ask ChatGPT a Question Task Launch");
if (https.begin(chatgpt_server)) { // HTTPS
https.addHeader("Content-Type", "application/json");
String token_key = String("Bearer ") + chatgpt_token;
https.addHeader("Authorization", token_key);
String payload = String("{\"model\": \"gpt-3.5-turbo-instruct-0914\", \"prompt\": \"") + chatgpt_Q + String("\", \"temperature\": 0, \"max_tokens\": 100}"); //Instead of TEXT as Payload, can be JSON as Paylaod
httpCode = https.POST(payload); // start connection and send HTTP header
payload = "";
currentState = get_chatgpt_list;
}
else {
Serial.println("[HTTPS] Unable to connect");
delay(1000);
}
break;
case get_chatgpt_list:
Serial.println("Get ChatGPT Answers Task Launch");
// httpCode will be negative on error
// file found at server
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = https.getString();
dataStart = payload.indexOf("\\n\\n") + strlen("\\n\\n");
dataEnd = payload.indexOf("\",\"", dataStart);
chatgpt_A = payload.substring(dataStart, dataEnd);
Serial.print("ChatGPT Answer is: ");
Serial.println(chatgpt_A);
// Display on OLED
u8g2.clearBuffer();
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setCursor(0, 10);
u8g2.print("EVIANT's Answer:");
wrapText(chatgpt_A, 0, 25, 128); // Wrap text if exceeds screen width
u8g2.sendBuffer();
currentState = do_webserver_index;
}
else {
Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
while(1);
}
https.end();
delay(10000);
break;
}
}
`**Use code tags to format code for the forum**`here