Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
Mohamed Jinas
Published © MIT

Making A Bridge Between Cloudflare And Nodemcu

Building a bridge between Cloudflare and nodemcu.

AdvancedShowcase (no instructions)3 hours343
Making A Bridge Between Cloudflare And Nodemcu

Story

Read more

Code

Code snippet #1

Plain text
/*
============================================
        Routes
============================================
*/

use App\Controllers\AnalyticsController;

$analytics = new AnalyticsController();

Flight::route('/analytics', array($analytics, 'analytics'));

Code snippet #2

Plain text
/*
============================================
        Routes
============================================
*/

use App\Controllers\AnalyticsController;

$analytics = new AnalyticsController();

Flight::route('/analytics', array($analytics, 'analytics'));

Code snippet #3

Plain text
namespace App\Controllers;

use Jinas\Jsonify\Util;
use Phpfastcache\Helper\Psr16Adapter;

class AnalyticsController
{
    public function analytics()
    {
        //Response Utility
        $response = new Util();

        $defaultDriver = 'Files';
        $Psr16Adapter = new Psr16Adapter($defaultDriver);

        if (!$Psr16Adapter->has('cloudflaredata')) {
            // Setter action
            $client = new \Cloudflare\Api(getenv('CLOUDFLARE_EMAIL'), getenv('CLOUDFLARE_APIKEY'));

            $analytic = new \Cloudflare\Zone\Analytics($client);
            //First argument is the zone id in the cloudflare.
            $array = json_decode(json_encode($analytic->dashboard('50515cfef4495e8bb32f79f6b28b1b54')), true);

            $index = $array["result"]["timeseries"][6];
            $Psr16Adapter->set('cloudflaredata', $index, 120); // 2 minutes before cache expire
        } else {
            // Getter action
            $index = $Psr16Adapter->get('cloudflaredata');
        }

        $request = $index["requests"]["all"];
        $bandwidth = $index["bandwidth"]["all"];
        $pageviews = $index["pageviews"]["all"];
        $uniques = $index["uniques"]["all"];


        if (!array_key_exists("MV", $index["bandwidth"]["country"])) {
            $country_bandwidth = null;
        } else {
            $country_bandwidth = $index["bandwidth"]["country"]["MV"];
        }


        $data = [
            'total_request' => $request,
            'total_bandwidth' => $bandwidth,
            'total_pageviews' => $pageviews,
            'total_unique_users' => $uniques,
            'total_bandwidth_local' => $country_bandwidth
        ];

        echo $response->sendResponse($data, 'data retrieved successfully');
    }
}

Code snippet #4

Plain text
namespace App\Controllers;

use Jinas\Jsonify\Util;
use Phpfastcache\Helper\Psr16Adapter;

class AnalyticsController
{
    public function analytics()
    {
        //Response Utility
        $response = new Util();

        $defaultDriver = 'Files';
        $Psr16Adapter = new Psr16Adapter($defaultDriver);

        if (!$Psr16Adapter->has('cloudflaredata')) {
            // Setter action
            $client = new \Cloudflare\Api(getenv('CLOUDFLARE_EMAIL'), getenv('CLOUDFLARE_APIKEY'));

            $analytic = new \Cloudflare\Zone\Analytics($client);
            //First argument is the zone id in the cloudflare.
            $array = json_decode(json_encode($analytic->dashboard('50515cfef4495e8bb32f79f6b28b1b54')), true);

            $index = $array["result"]["timeseries"][6];
            $Psr16Adapter->set('cloudflaredata', $index, 120); // 2 minutes before cache expire
        } else {
            // Getter action
            $index = $Psr16Adapter->get('cloudflaredata');
        }

        $request = $index["requests"]["all"];
        $bandwidth = $index["bandwidth"]["all"];
        $pageviews = $index["pageviews"]["all"];
        $uniques = $index["uniques"]["all"];


        if (!array_key_exists("MV", $index["bandwidth"]["country"])) {
            $country_bandwidth = null;
        } else {
            $country_bandwidth = $index["bandwidth"]["country"]["MV"];
        }


        $data = [
            'total_request' => $request,
            'total_bandwidth' => $bandwidth,
            'total_pageviews' => $pageviews,
            'total_unique_users' => $uniques,
            'total_bandwidth_local' => $country_bandwidth
        ];

        echo $response->sendResponse($data, 'data retrieved successfully');
    }
}

Code snippet #5

Plain text
// Importing the libraries
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

#define LEDRED D8
#define LEDYELLOW D7
#define LEDGREEN D6

const char* ssid = "";
const char* password = "";

void setup() {

pinMode(LEDRED, OUTPUT);
pinMode(LEDYELLOW, OUTPUT);
pinMode(LEDGREEN, OUTPUT);

Serial.begin(9600);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(1000);
Serial.println("Connecting..");

}


}

void loop() {

if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

HTTPClient http;  //Declare an object of class HTTPClient

http.begin("http://192.168.1.8:8000/analytics");  //Specify request destination
int httpCode = http.GET();                                                                  //Send the request

if (httpCode > 0) { //Check the returning code

String payload = http.getString();   //Get the request response payload
StaticJsonDocument<500> doc;

DeserializationError error = deserializeJson(doc,payload);   //Parse message
  if (error) {      //Check for errors in parsing
    Serial.print("deserializeJson() failed with code ");
    Serial.println(error.c_str());
    delay(5000);
    return;

  }

int totalrequest = doc["data"]["total_request"];

  if(totalrequest >= 300)
  {
  digitalWrite(LEDRED, HIGH);
  delay(400);
  digitalWrite(LEDRED, LOW);
  delay(400);
  }

  if(totalrequest < 300 && totalrequest >= 250)
  {
    digitalWrite(LEDYELLOW, HIGH);
    delay(400);
    digitalWrite(LEDYELLOW, LOW);
    delay(400);
  }

  if(totalrequest < 250)
  {
    digitalWrite(LEDGREEN, HIGH);
    delay(400);
    digitalWrite(LEDGREEN, LOW);
    delay(400);
  }
Serial.println(totalrequest);

}

http.end();   //Close connection

}

delay(10000);
}

Code snippet #6

Plain text
// Importing the libraries
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

#define LEDRED D8
#define LEDYELLOW D7
#define LEDGREEN D6

const char* ssid = "";
const char* password = "";

void setup() {

pinMode(LEDRED, OUTPUT);
pinMode(LEDYELLOW, OUTPUT);
pinMode(LEDGREEN, OUTPUT);

Serial.begin(9600);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(1000);
Serial.println("Connecting..");

}


}

void loop() {

if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

HTTPClient http;  //Declare an object of class HTTPClient

http.begin("http://192.168.1.8:8000/analytics");  //Specify request destination
int httpCode = http.GET();                                                                  //Send the request

if (httpCode > 0) { //Check the returning code

String payload = http.getString();   //Get the request response payload
StaticJsonDocument<500> doc;

DeserializationError error = deserializeJson(doc,payload);   //Parse message
  if (error) {      //Check for errors in parsing
    Serial.print("deserializeJson() failed with code ");
    Serial.println(error.c_str());
    delay(5000);
    return;

  }

int totalrequest = doc["data"]["total_request"];

  if(totalrequest >= 300)
  {
  digitalWrite(LEDRED, HIGH);
  delay(400);
  digitalWrite(LEDRED, LOW);
  delay(400);
  }

  if(totalrequest < 300 && totalrequest >= 250)
  {
    digitalWrite(LEDYELLOW, HIGH);
    delay(400);
    digitalWrite(LEDYELLOW, LOW);
    delay(400);
  }

  if(totalrequest < 250)
  {
    digitalWrite(LEDGREEN, HIGH);
    delay(400);
    digitalWrite(LEDGREEN, LOW);
    delay(400);
  }
Serial.println(totalrequest);

}

http.end();   //Close connection

}

delay(10000);
}

Github

https://github.com/jinas123/cloudflare-flight

Credits

Mohamed Jinas
3 projects • 3 followers
Student, a Software developer based in Maldives.
Contact

Comments

Please log in or sign up to comment.