Instagram Follow Counter (ESP-32)

Veröffentlicht von

Text

Sketch

/* StartCode
*
*   1 = Display-Test
*   2 = versuche WiFi Verbindung herzustellen
*   3 = WiFi Verbindung hergestellt
*   4 = stelle eine Verbindung zum Json-File auf der Website her
*   5 = das Json-File auslesen
*/

/*  Pins
*   
*   3V3 - Rot
*   22  - Weiss
*   21  - Braun
*   GND - Schwarz
*/

#include <WiFi.h>
#include <ArduinoJson.h>
#include <Wire.h> // Enable this line if using Arduino Uno, Mega, etc.
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"

struct {
  uint8_t           addr;         // I2C address
  Adafruit_7segment seg7;         // 7segment object
} disp[] = {
  { 0x71, Adafruit_7segment() },  // High digits Instagram
  { 0x70, Adafruit_7segment() }   // Low digits Instagram
};


//------- Replace the following! ------
//String instagramUser = "inge_tenneberg";
String instagramUser = "patrick__exc500";

char ssid[] = "ssid";       // your network SSID (name)
char password[] = "password";  // your network key

char servername[] = "url or IP";

String urlJsonFile = "/instagram/json/" + instagramUser + ".json";

unsigned long delayBetweenChecks = 60000; //mean time between api requests
unsigned long whenDueToCheck = 0;

String sensorReadings;

unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

long follower = 0;

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

  initDisplays();
  clearDisplays();

  setStartCode(1); // Display-Test
  delay(5000);
  
  setDisplay(88888888);
  delay(5000);
  
  setStartCode(2); // versuche WiFi Verbindung herzustellen 
  delay(5000);
  connectToWiFi(); 
  delay(5000);  
  
  setStartCode(4); // stelle eine Verbindung zum Json-File auf der Website her
  WiFiClient client = getJsonFile();
  delay(5000);

  setStartCode(5); // das Json-File auslesen
  readJson(client);
  delay(5000);

  setDisplay(follower);
}

void loop() {

  if(!WL_CONNECTED) {
    connectToWiFi();
  }
  
  delay(5000);
  //createJsonFile();
 
  delay(5000);
  WiFiClient client = getJsonFile();

  delay(5000);  
  readJson(client);
  
  setDisplay(follower);
}

void initDisplays() {
  for (uint8_t i = 0; i < 2; i++) {  // Initialize displays
    disp[i].seg7.begin(disp[i].addr);
  }
}

void clearDisplays() {
  for (uint8_t i = 0; i < 2; i++) {  // Initialize displays
    disp[i].seg7.clear();
    disp[i].seg7.writeDisplay();
  }
}

void connectToWiFi() {
  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  int countTryConnetion = 0;


  //while (true) {
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    showTryConnection(countTryConnetion++);
    delay(500);

    if(countTryConnetion >= 10){
      countTryConnetion = 0;
    }
  } 

  if(WL_CONNECTED) {
    setStartCode(3);    //  WiFi Verbindung hergestellt
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("IP address: ");
    IPAddress ip = WiFi.localIP();
    Serial.println(ip);
  } 
}

void showTryConnection(int versuche) {
  if(versuche == 0){
      clearDisplays();                            // leere Display
  }

  if(versuche < 5){
    disp[1].seg7.writeDigitRaw(4 - versuche, 64); // setze den Strich in der Mitte
    disp[1].seg7.writeDisplay();                  // gib alles auf dem Display aus
  } else {
    disp[0].seg7.writeDigitRaw(9 - versuche, 64); // setze den Strich in der Mitte
    disp[0].seg7.writeDisplay();                  // gib alles auf dem Display aus
  }
}

void setErrorCode(int errorCode) {
  clearDisplays();                     // lösche den Buffer
  disp[1].seg7.print(errorCode);            // schreibe die Zahl
  disp[1].seg7.writeDigitRaw(0, 121);       // schreibe das E
  disp[1].seg7.writeDigitRaw(1, 0x80);      // schreibe den Punkt
  disp[1].seg7.writeDisplay();              // gib alles auf dem Display aus
}

void setStartCode(int startCode) {
  clearDisplays();                     // lösche den Buffer
  disp[1].seg7.print(startCode);            // schreibe die Zahl
  disp[1].seg7.writeDigitRaw(0, 109);        // schreibe das S
  disp[1].seg7.writeDigitRaw(1, 0x80);      // schreibe den Punkt
  disp[1].seg7.writeDisplay();              // gib alles auf dem Display aus
}

void setDisplay(long followerCount){
    uint16_t hi = followerCount / 10000, // Value on left (high digits) display
             lo = followerCount % 10000; // Value on right (low digits) display
    
    //        uint16_t hi = 5678, // Value on left (high digits) display
    //                 lo = 1234; // Value on right (low digits) display
    
    disp[0].seg7.print(hi, DEC);   // Write values to each display...
    disp[1].seg7.print(lo, DEC);
    
    // print() does not zero-pad the displays; this may produce a gap
    // between the high and low sections. Here we add zeros where needed...
    if(hi) {
      if(lo < 1000) {
        disp[1].seg7.writeDigitNum(0, 0);
        if(lo < 100) {
          disp[1].seg7.writeDigitNum(1, 0);
          if(lo < 10) {
            disp[1].seg7.writeDigitNum(3, 0);
          }
        }
      }
     } else {
       disp[0].seg7.clear(); // Clear 'hi' display
     }
     disp[0].seg7.writeDisplay(); // Push data to displays
     disp[1].seg7.writeDisplay();
}

void readJson(WiFiClient client){

   boolean httpBody = false;
   String json = "";
  
   while (client.available()) {
    String line = client.readStringUntil('\r');
    if (!httpBody && line.charAt(1) == '{') {
      httpBody = true;
    }
    if (httpBody) {
      json += line;
    }
  }

  Serial.println("Got data:");
  Serial.println(json);

  StaticJsonDocument<256> doc;
  deserializeJson(doc, json);
  
  follower = doc["socialMedia"]["instagram"]["follower"].as<long>();
  // follower = doc["edge_followed_by"]["count"].as<long>();
  Serial.print("Json Follower: ");
  Serial.println(follower);

//  Beispiele
//  auto name = doc["name"].as<const char*>();
//  auto stars = doc["stargazers"]["totalCount"].as<long>();
//  auto issues = doc["issues"]["totalCount"].as<int>()
}


WiFiClient getJsonFile(){

    WiFiClient client;
    
    Serial.println("");
    Serial.print("Connecting WebServer: ");
    if (client.connect(servername, 80)) {
      Serial.println("connected");
      // Make a HTTP request:
            client.print("GET " + urlJsonFile + " HTTP/1.1\r\n" +
                   "Host: " + servername + "\r\n" +
                   "ApiCode: 8273\r\n" +
                   "Content-Type: application/json\r\n" + 
                   "Connection: close\r\n\r\n");
      // client.println();
      Serial.print("read Json File: ");
      Serial.println("success");
    } else {
      Serial.println("connection Failed");
    }

    return client;
}Code-Sprache: PHP (php)