witnessmenow / arduino-sample-api-request

24 stars 15 forks source link

Can't connect to Quaver API #5

Closed AdaoH3 closed 10 months ago

AdaoH3 commented 10 months ago

I'm listing my code below. I've been trying to get this working for a few hours tweaking around with different things however I have still been getting connection failed errors. Please lmk if a fix is found, help would be extremely appreciated. Wifi connects fine.

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
//https://
#define SERVER "api.quavergame.com"
#define PATH "/v1/users/609092/achievements"
#define SERVER_FINGERPRINT "19 5d a2 b6 72 f4 c6 7d eb 43 d2 16 e2 a8 a5 5e db ed 6f 76 1f d9 9e d7 41 5c 30 8e c3 d7 29 db"

// Enter your WiFi SSID and password
char ssid[] = "Hotspot1";             // your network SSID (name)
char pass[] = ""; //Removed for post 

WiFiClientSecure client;

// Use dedicated hardware SPI pins
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

void printWifiStatus();
int updateAchievements();

void setup(void) 
{
  Serial.begin(9600);

  Serial.print("Attempting to connect to Wifi");

  // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) 
  {
      delay(500);
      Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connected to WiFi");
  printWifiStatus();

  Serial.print(F("Hello! Feather TFT Test"));

  pinMode(TFT_I2C_POWER, OUTPUT);
  digitalWrite(TFT_I2C_POWER, HIGH);
  delay(10);

  tft.init(135, 240);
  tft.setRotation(3);

  // turn on backlite
  pinMode(TFT_BACKLITE, OUTPUT);
  digitalWrite(TFT_BACKLITE, HIGH);

  //Make Black
  tft.fillScreen(ST77XX_BLACK);

  tft.setTextSize(1);
  tft.setTextColor(ST77XX_WHITE);
  tft.setCursor(0,0);
  tft.setTextWrap(true);

  //client.setFingerprint(SERVER_FINGERPRINT);
  client.setInsecure(); 
}

void loop() 
{
  WiFiClientSecure client;

  Serial.println("\nStarting connection to server...");
  tft.print("Starting Connection");

  Serial.println("Achievements: ");
  Serial.println(updateAchievements());
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

int updateAchievements()
{
  client.setInsecure();
  Serial.println("\nStarting connection to server...");

  client.setTimeout(10000);
  if (!client.connect(SERVER, 443)) 
  {
    Serial.println("Connection Failed");
    return 2;
  }

  yield();

  client.print(F("GET "));
  client.print("PATH");
  client.println(F( "HTTP/1.1"));

  client.print(F("Host: "));
  client.println(SERVER);

  client.println(F("Cache-Control: no-cache"));

  if(client.println() == 0)
  {
    Serial.println(F("Failed to send request"));
    return 3;
  }

  // Check HTTP status
  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
    Serial.print(F("Unexpected response: "));
    Serial.println(status);// Check HTTP status
    return 4;
  }

  char endOfHeaders[] = "\r\n\r\n";
  if(!client.find(endOfHeaders))
  {
    Serial.println("Invalid Response");
    return 5;
  }

  while (client.available() && client.peek() != '{') 
  { 
    char c = 0;
    client.readBytes(&c, 1);
    Serial.print(c);
    Serial.print("BAD");
  }

  while(client.available())
  {
    char c = 0;
    client.readBytes(&c, 1);
    Serial.print(c);
  }

  // Allocate the JSON document
  // Use arduinojson.org/v6/assistant to compute the capacity.
  //const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(8) + 200;
  //DynamicJsonDocument doc(capacity);
  //DynamicJsonDocument doc(1536);

  /*
  StaticJsonDocument<48> filter;
  filter["achievements"][0]["unlocked"] = true;

  StaticJsonDocument<1536> doc;

  DeserializationError error = deserializeJson(doc, client, DeserializationOption::Filter(filter));

  if (error) {
    Serial.print("deserializeJson() failed: ");
    Serial.println(error.c_str());
    return 3;
  }

  int unlockedAchievementCount = 0;

  for (JsonObject achievement : doc["achievements"].as<JsonArray>()) 
  {
    bool achievement_unlocked = achievement["unlocked"]; // true, false, false, false, false, true, false, ...

    if(achievement_unlocked)
    {
      unlockedAchievementCount++;
    }
  }

  return unlockedAchievementCount;

  }
  */
}
AdaoH3 commented 10 months ago

Solved, used a different version of structure of code provided below:

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>

#define SERVER "api.quavergame.com"
#define PATH "/v1/users/609092/achievements"

// Enter your WiFi SSID and password
char ssid[] = "Hotspot1";             // your network SSID (name)
char pass[] = "";                           //Removed for security

// Use dedicated hardware SPI pins
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

void printWifiStatus();
int updateAchievements();
int unlockedCount = 0;
int tempCount;

void setup(void) 
{
  Serial.begin(9600);

  Serial.print("Attempting to connect to Wifi");

  // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) 
  {
      delay(500);
      Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connected to WiFi");
  printWifiStatus();

  Serial.print(F("Hello! Feather TFT Test"));

  pinMode(TFT_I2C_POWER, OUTPUT);
  digitalWrite(TFT_I2C_POWER, HIGH);
  delay(10);

  tft.init(135, 240);
  tft.setRotation(3);

  // turn on backlite
  pinMode(TFT_BACKLITE, OUTPUT);
  digitalWrite(TFT_BACKLITE, HIGH);

  //Make Black
  tft.fillScreen(ST77XX_BLACK);

  tft.setTextSize(1);
  tft.setTextColor(ST77XX_WHITE);
  tft.setCursor(0,0);
  tft.setTextWrap(true);

  //client.setFingerprint(SERVER_FINGERPRINT);

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:

}

uint32_t bytes = 0;

void loop() 
{
  Serial.println(updateAchievements());
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

int updateAchievements()
{
  WiFiClientSecure client;
  client.setInsecure(); 

  if (client.connect(SERVER, 443)) 
  {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET " PATH " HTTP/1.1");
    client.println("Host: " SERVER);
    client.println("Connection: close");
    client.println();
  }
  else
  {
    return 2;
  }

  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
    Serial.print(F("Unexpected response: "));
    Serial.println(status);
    return 3; 
  }

  // wait until we get a double blank line
  client.find("\r\n\r\n", 4);
  client.println();

  // Stream& input;

// Stream& input;

DynamicJsonDocument filter(48);
filter["achievements"][0]["unlocked"] = true;

DynamicJsonDocument doc(1536);

DeserializationError error = deserializeJson(doc, client, DeserializationOption::Filter(filter));

if (error) {
  Serial.print("deserializeJson() failed: ");
  Serial.println(error.c_str());
  return 5;
}

for (JsonObject achievement : doc["achievements"].as<JsonArray>()) {

  bool achievement_unlocked = achievement["unlocked"]; // true, false, false, false, false, true, false, ...

  if (achievement_unlocked) {
    unlockedCount++;
  }
}
  tempCount = unlockedCount;
  unlockedCount = 0;

  return tempCount;

}