Advertisement
Guest User

tes

a guest
Feb 20th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.30 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include <stdio.h>
  3. #include <ESP8266WebServer.h>
  4. #include <ArduinoJson.h>
  5.  
  6. #define HTTP_REST_PORT 80
  7. #define WIFI_RETRY_DELAY 500
  8. #define MAX_WIFI_INIT_RETRY 50
  9.  
  10. const char* wifi_ssid = "MALWARE";
  11. const char* wifi_passwd = "fikri007";
  12. const char * headerKeys[] = {"Authorization"} ;
  13. const size_t numberOfHeaders = 1;
  14.  
  15. ESP8266WebServer http_rest_server(HTTP_REST_PORT);
  16.  
  17. int init_wifi() {
  18.     int retries = 0;
  19.  
  20.     Serial.println("Connecting to WiFi AP..........");
  21.  
  22.     WiFi.mode(WIFI_STA);
  23.     WiFi.begin(wifi_ssid, wifi_passwd);
  24.     // check the status of WiFi connection to be WL_CONNECTED
  25.     while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
  26.         retries++;
  27.         delay(WIFI_RETRY_DELAY);
  28.         Serial.print("#");
  29.     }
  30.     return WiFi.status(); // return the WiFi connection status
  31. }
  32.  
  33. void get_req()
  34. {
  35.         StaticJsonBuffer<200> jsonBuffer;
  36.         JsonObject& jsonObj = jsonBuffer.createObject();
  37.         char JSONmessageBuffer[200];
  38.         http_rest_server.collectHeaders(headerKeys, numberOfHeaders);
  39.         jsonObj["id"] = "445";
  40.         jsonObj["gpio"] = "kepos";
  41.         jsonObj["status"] = "good";
  42.  
  43.         //print header request
  44.         jsonObj["header_"] = http_rest_server.header("authorization");
  45.         jsonObj.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
  46.         http_rest_server.send(200, "application/json", JSONmessageBuffer);
  47. }
  48.  
  49. void config_rest_server_routing() {
  50.     http_rest_server.on("/", HTTP_GET, []() {
  51.         http_rest_server.send(200, "text/html",
  52.             "Welcome to the ESP8266 REST Web Server");
  53.     });
  54.     http_rest_server.on("/req", HTTP_GET, get_req);
  55. }
  56.  
  57. void setup(void) {
  58.   // put your setup code here, to run once:
  59.    Serial.begin(9600);
  60.  
  61.     if (init_wifi() == WL_CONNECTED) {
  62.         Serial.print("Connetted to ");
  63.         Serial.print(wifi_ssid);
  64.         Serial.print("--- IP: ");
  65.         Serial.println(WiFi.localIP());
  66.     }
  67.     else {
  68.         Serial.print("Error connecting to: ");
  69.         Serial.println(wifi_ssid);
  70.     }
  71.     config_rest_server_routing();
  72.  
  73.     http_rest_server.begin();
  74.     Serial.println("HTTP REST Server Started");
  75.  
  76. }
  77.  
  78. void loop(void) {
  79.   // put your main code here, to run repeatedly:
  80.   http_rest_server.handleClient();
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement