Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2018
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ESP8266WebServer.h>
  3.  
  4. #define HTTP_REST_PORT 80
  5. #define WIFI_RETRY_DELAY 500
  6. #define MAX_WIFI_INIT_RETRY 50
  7.  
  8. struct Pulsanti {
  9. byte id;
  10. byte status1;
  11. byte status2;
  12. } pulsanti_resource;
  13.  
  14. const char* wifi_ssid = "xxx";
  15. const char* wifi_passwd = "xx";
  16.  
  17. ESP8266WebServer http_rest_server(HTTP_REST_PORT);
  18.  
  19. void init_pulsanti_resource()
  20. {
  21. pulsanti_resource.id = 1;
  22. pulsanti_resource.status1 = LOW;
  23. pulsanti_resource.status2 = LOW;
  24. }
  25.  
  26. int init_wifi() {
  27. int retries = 0;
  28.  
  29. Serial.println("Connecting to WiFi AP..........");
  30.  
  31. WiFi.mode(WIFI_STA);
  32. WiFi.begin(wifi_ssid, wifi_passwd);
  33. // check the status of WiFi connection to be WL_CONNECTED
  34. while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
  35. retries++;
  36. delay(WIFI_RETRY_DELAY);
  37. Serial.print("#");
  38. }
  39. return WiFi.status(); // return the WiFi connection status
  40. }
  41.  
  42. void get_pulsanti() {
  43. if (pulsanti_resource.id == 0)
  44. http_rest_server.send(204);
  45. else {
  46. http_rest_server.send(200, "text/html", String(pulsanti_resource.status1) + " " + String(pulsanti_resource.status2));
  47. }
  48. }
  49.  
  50. void config_rest_server_routing() {
  51. http_rest_server.on("/", HTTP_GET, []() {
  52. http_rest_server.send(200, "text/html",
  53. "Welcome to the ESP8266 REST Web Server");
  54. });
  55. http_rest_server.on("/pulsanti", HTTP_GET, get_pulsanti);
  56. }
  57.  
  58. void setup(void) {
  59. Serial.begin(115200);
  60.  
  61. init_pulsanti_resource();
  62. if (init_wifi() == WL_CONNECTED) {
  63. Serial.print("Connetted to ");
  64. Serial.print(wifi_ssid);
  65. Serial.print("--- IP: ");
  66. Serial.println(WiFi.localIP());
  67. }
  68. else {
  69. Serial.print("Error connecting to: ");
  70. Serial.println(wifi_ssid);
  71. }
  72.  
  73. config_rest_server_routing();
  74.  
  75. http_rest_server.begin();
  76. Serial.println("HTTP REST Server Started");
  77. }
  78.  
  79. void loop(void) {
  80. http_rest_server.handleClient();
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement