Chewpacker

Multi-threaded Web Server (Edit 1)

Jan 12th, 2021 (edited)
497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.45 KB | None | 0 0
  1. #include <iostream>
  2. #include <chrono>
  3. #include <string>
  4. #include <atomic>
  5. #include <stdlib.h>
  6. #include <WiFi.h>
  7. #include <FastLED.h>
  8.  
  9. #define NUM_LEDS 300
  10. #define DATA_PIN 5
  11. #define LED_TYPE WS2812B
  12. #define COLOUR_ORDER GRB
  13. #define BRIGHTNESS 64
  14.  
  15. int j = NUM_LEDS-1;
  16. int CHECK = 0;
  17. int Q = NUM_LEDS/4;
  18. int H = NUM_LEDS/2;
  19. int T = 3*Q;
  20. CRGB leds[NUM_LEDS];
  21.  
  22. const char* ssid     = "TheDnBCave";
  23. const char* password = "*************";
  24.  
  25. WiFiServer server(80);
  26.  
  27. String redString = "0";
  28. String greenString = "0";
  29. String blueString = "0";
  30. String intensityString = "0";
  31. String checkString = "0";
  32. int pos1 = 0;
  33. int pos2 = 0;
  34. int pos3 = 0;
  35. int pos4 = 0;
  36. int pos5 = 0;
  37.  
  38. String header;
  39. std::atomic_int R(0);
  40. std::atomic_int G(0);
  41. std::atomic_int B(0);
  42. std::atomic_int I(0);
  43. std::atomic_int C(0);
  44. int r_holder;
  45. int g_holder;
  46. int b_holder;
  47. int i_holder;
  48. int c_holder;
  49.  
  50. std::atomic_int Ri(0);
  51. std::atomic_int Gi(0);
  52. std::atomic_int Bi(0);
  53. std::atomic_int Ii(0);
  54. std::atomic_int Ci(0);
  55.  
  56. TaskHandle_t Serv;
  57.  
  58. // Current time
  59. unsigned long currentTime = millis();
  60. // Previous time
  61. unsigned long previousTime = 0;
  62. // Define timeout time in milliseconds (example: 2000ms = 2s)
  63. const long timeoutTime = 2000;
  64.  
  65. void setup() {
  66.   FastLED.addLeds<LED_TYPE, DATA_PIN, COLOUR_ORDER>(leds, NUM_LEDS);
  67.   FastLED.setBrightness(BRIGHTNESS);
  68.  
  69.   Serial.begin(115200);
  70.   Serial.print("Connecting to ");
  71.   Serial.println(ssid);
  72.   WiFi.begin(ssid, password);
  73.   while (WiFi.status() != WL_CONNECTED) {
  74.     delay(500);
  75.     Serial.print(".");
  76.   }
  77.   // Print local IP address and start web server
  78.   Serial.println("");
  79.   Serial.println("WiFi connected.");
  80.   Serial.println("IP address: ");
  81.   Serial.println(WiFi.localIP());
  82.   server.begin();
  83.  
  84.    xTaskCreatePinnedToCore(
  85.       Server, /* Function to implement the task */
  86.       "Server", /* Name of the task */
  87.       50000,  /* Stack size in words */
  88.       NULL,  /* Task input parameter */
  89.       0,  /* Priority of the task */
  90.       &Serv,  /* Task handle. */
  91.       0); /* Core where the task should run */
  92.    leds[0].r = 255;
  93. }
  94.  
  95.  
  96. bool hasChanged(){
  97.   if(R.load(std::memory_order_acquire) != Ri.load(std::memory_order_acquire)
  98.   || G.load(std::memory_order_acquire) != Gi.load(std::memory_order_acquire)
  99.   || B.load(std::memory_order_acquire) != Bi.load(std::memory_order_acquire)
  100.   || I.load(std::memory_order_acquire) != Ii.load(std::memory_order_acquire)
  101.   || C.load(std::memory_order_acquire) != Ci.load(std::memory_order_acquire))
  102.   {
  103.         Ri.store(R.load(std::memory_order_acquire), std::memory_order_release);
  104.         Gi.store(G.load(std::memory_order_acquire), std::memory_order_release);
  105.         Bi.store(B.load(std::memory_order_acquire), std::memory_order_release);
  106.         Ii.store(I.load(std::memory_order_acquire), std::memory_order_release);
  107.         Ci.store(C.load(std::memory_order_acquire), std::memory_order_release);
  108.         return true;
  109.   }
  110.   else{
  111.     return false;
  112.     }
  113. }
  114. void Server(void * pvParameters){
  115. for(;;){
  116.   WiFiClient client = server.available();   // Listen for incoming clients
  117.  
  118.   if (client) {                             // If a new client connects,
  119.     currentTime = millis();
  120.     previousTime = currentTime;
  121.     Serial.println("New Client.");          // print a message out in the serial port
  122.     String currentLine = "";                // make a String to hold incoming data from the client
  123.     while (client.connected() && currentTime - previousTime <= timeoutTime) {            // loop while the client's connected
  124.       currentTime = millis();
  125.       if (client.available()) {             // if there's bytes to read from the client,
  126.         char c = client.read();             // read a byte, then
  127.         Serial.write(c);                    // print it out the serial monitor
  128.         header += c;
  129.         if (c == '\n') {                    // if the byte is a newline character
  130.           // if the current line is blank, you got two newline characters in a row.
  131.           // that's the end of the client HTTP request, so send a response:
  132.           if (currentLine.length() == 0) {
  133.             // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
  134.             // and a content-type so the client knows what's coming, then a blank line:
  135.             client.println("HTTP/1.1 200 OK");
  136.             client.println("Content-type:text/html");
  137.             client.println("Connection: close");
  138.             client.println();
  139.                    
  140.             // Display the HTML web page
  141.             client.println("<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width =device-width, initial-scale=1\"><link rel=\"icon\" href=\"data:,\"><link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"></head><body><div class=\"container\"><div class=\"row\"><h1>ESP Color Picker</h1></div><a class=\"btn btn-primary btn-lg\" href=\"#\" id=\"change_color\" role=\"button\">Change Color</a><input id=\"rgb\" type=\"text\" value=\"7F7F7F\" style=\"background:#7f7f7f\"><div><input id=\"r\" type=\"range\" min=\"0\" max=\"255\" onchange=\"updateColour()\"/><label for=\"r\">Red</label><input id=\"g\" type=\"range\" min=\"0\" max=\"255\" onchange=\"updateColour()\" /><label for=\"g\">Green</label><input id=\"b\" type=\"range\" min=\"0\" max=\"255\" onchange=\"updateColour()\" /><label for=\"b\">Blue</label><input id=\"i\" type=\"range\" min=\"0\" max=\"64\" onchange=\"updateColour()\" /><label for=\"i\">Intensity</label></div><div><a class=\"btn btn-primary btn-lg\" href=\"#\" id=\"change_mode\" role=\"button\">Change Mode</a><input id=\"r1\" type=\"radio\" name=\"mode-type\" onchange=\"updateMode()\"/><label for=\"r1\">Mode 1</label><input id=\"r2\" type=\"radio\" name=\"mode-type\" onchange=\"updateMode()\"/><label for=\"r2\">Mode 2</label></div><script>function updateColour() {var r = parseInt( document.getElementById(\"r\").value, 10);var g = parseInt( document.getElementById(\"g\").value, 10);var b = parseInt(document.getElementById(\"b\").value, 10); var i = document.getElementById(\"i\").value;var hex = r.toString(16) + g.toString(16) + b.toString(16);document.getElementById('rgb').value = hex;document.getElementById('rgb').style.background = \"#\" + hex;document.getElementById(\"change_color\").href = \"?r\" + r + \"g\" + g + \"b\" + b + \"i\" + i + \"&\";}function updateMode(){var r;if(document.getElementById('r1').checked){r = 1}else if(document.getElementById('r2').checked){r = 2;}document.getElementById(\"change_mode\").href = \"?m\"+ r + \"&\";}</script></body></html>");
  142.  
  143.             // The HTTP response ends with another blank line
  144.             client.println();
  145.  
  146.             // Request sample: /?r201g32b255&
  147.             // Red = 201 | Green = 32 | Blue = 255
  148.             if(header.indexOf("GET /?r") >= 0) {
  149.               Serial.println("Static colour selected - calculating RGB Values...");
  150.               pos1 = header.indexOf('r');
  151.               pos2 = header.indexOf('g');
  152.               pos3 = header.indexOf('b');
  153.               pos4 = header.indexOf('i');
  154.               pos4 = header.indexOf('&');
  155.               redString = header.substring(pos1+1, pos2);
  156.               greenString = header.substring(pos2+1, pos3);
  157.               blueString = header.substring(pos3+1, pos4);
  158.               intensityString = header.substring(pos4+1, pos5);
  159.               R.store(redString.toInt(), std::memory_order_release);
  160.               G.store(greenString.toInt(), std::memory_order_release);
  161.               B.store(blueString.toInt(), std::memory_order_release);
  162.               I.store(intensityString.toInt(), std::memory_order_release);
  163.  
  164.               Serial.println(R.load(std::memory_order_acquire));
  165.               Serial.println(G.load(std::memory_order_acquire));
  166.               Serial.println(B.load(std::memory_order_acquire));
  167.             }
  168.  
  169.             else if(header.indexOf("GET /?m") >= 0) {
  170.               Serial.println("Looping mode selected - calculating mode selection...");
  171.               pos1 = header.indexOf('m');
  172.               pos2 = header.indexOf('&');
  173.               checkString = header.substring(pos1+1, pos2);
  174.               C.store(checkString.toInt(), std::memory_order_release);
  175.  
  176.               Serial.println(C.load(std::memory_order_acquire));
  177.             }
  178.             // Break out of the while loop
  179.             break;
  180.           } else { // if you got a newline, then clear currentLine
  181.             currentLine = "";
  182.           }
  183.         } else if (c != '\r') {  // if you got anything else but a carriage return character,
  184.           currentLine += c;      // add it to the end of the currentLine
  185.         }
  186.       }
  187.     }
  188.     header = "";
  189.     // Close the connection
  190.     client.stop();
  191.     Serial.println("Client disconnected.");
  192.     Serial.println("");
  193.     vTaskDelay(3);
  194.   }
  195. }
  196. }
  197.  
  198. /*void Display(void * pvParameters){
  199.   for (;;){
  200.    
  201.   }
  202. }*/
  203.  
  204. void loop() {
  205.  if (hasChanged())
  206.     {
  207.       Serial.println("Change detected!");
  208.       c_holder = C.load(std::memory_order_acquire);
  209.  
  210.   if(c_holder == 0)
  211.   {
  212.     Serial.println("I am in the static display block");
  213.     r_holder = R.load(std::memory_order_acquire);
  214.     g_holder = G.load(std::memory_order_acquire);
  215.     b_holder = B.load(std::memory_order_acquire);
  216.     i_holder = I.load(std::memory_order_acquire);
  217.  
  218.     FastLED.setBrightness(i_holder);
  219.  
  220.     Serial.println("Now updating all elements with the following values: ");
  221.     Serial.println(r_holder);
  222.     Serial.println(g_holder);
  223.     Serial.println(b_holder);
  224.    
  225.     //for(int i=0; i<NUM_LEDS/2; i++)
  226.     for (int i=0; i<NUM_LEDS; i++)
  227.               {
  228.                  leds[i].setRGB(r_holder, g_holder, b_holder);
  229.                  Serial.print("[");
  230.                  Serial.print(i);
  231.                  Serial.print("].R = ");
  232.                  Serial.println(leds[i].r);
  233.                  //leds[j].setRGB(r_holder, g_holder, b_holder);
  234.                  //FastLED.show();
  235.                  //j--;
  236.               }
  237.               Serial.println("All elements updated - showing");
  238.               FastLED.show();
  239.               //j=NUM_LEDS-1;
  240.   }
  241.   else if(c_holder == 1)
  242.   {
  243.     Serial.println("I am in mode 1");
  244.                       for(int i=0; i<50; i++)
  245.                       {
  246.                           if(i==49)
  247.                           {
  248.                               for(int j=49; j>=0; j--)
  249.                               {
  250.                                   leds[j] = CRGB::Red;
  251.                                   leds[j+50] = CRGB::Orange;
  252.                                   leds[j+100] = CRGB::Yellow;
  253.                                   leds[j+150] = CRGB::Green;
  254.                                   leds[j+200] = CRGB::Blue;
  255.                                   leds[j+250] = CRGB::Purple;
  256.                                   FastLED.show();
  257.                                   leds[j] = CRGB::Black;
  258.                                   leds[j+50] = CRGB::Black;
  259.                                   leds[j+100] = CRGB::Black;  
  260.                                   leds[j+150] = CRGB::Black;
  261.                                   leds[j+200] = CRGB::Black;
  262.                                   leds[j+250] = CRGB::Black;
  263.                  
  264.                               }  
  265.                           }
  266.                           else
  267.                           {
  268.                               leds[i] = CRGB::Red;
  269.                               leds[i+50] = CRGB::Orange;
  270.                               leds[i+100] = CRGB::Yellow;
  271.                               leds[i+150] = CRGB::Green;
  272.                               leds[i+200] = CRGB::Blue;
  273.                               leds[i+250] = CRGB::Purple;
  274.                               FastLED.show();
  275.                           }          
  276.                       }
  277.                   }
  278.  else if(c_holder == 2)
  279.                   {
  280.                     Serial.println("I am in mode 2");
  281.                       for(int i=0; i<NUM_LEDS; i++)
  282.                       {
  283.                           leds[i] = CRGB::Red;
  284.                           leds[(i+Q) % NUM_LEDS] = CRGB::Green;
  285.                           leds[(i+H) % NUM_LEDS] = CRGB::Blue;
  286.                           leds[(i+T) % NUM_LEDS] = CRGB::Yellow;
  287.  
  288.                            FastLED.show();
  289.                            delay(20);
  290.  
  291.                            for(int i=0; i<NUM_LEDS; i++)
  292.                            {
  293.                               leds[i] = CRGB::Black;
  294.                            }
  295.                       }
  296.                  
  297.                    }
  298.     }
  299.     vTaskDelay(3);
  300. }
Add Comment
Please, Sign In to add comment