Advertisement
nertskull

Untitled

Oct 25th, 2021
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.64 KB | None | 0 0
  1. #define FASTLED_ALLOW_INTERRUPTS 0
  2. #define FASTLED_INTERRUPT_RETRY_COUNT 0
  3. #define FASTLED_ESP8266_RAW_PIN_ORDER
  4. #include <ESP8266WiFi.h>
  5. #include <ESP8266mDNS.h>
  6. #include <ESP8266HTTPUpdateServer.h>
  7. #include <WiFiUdp.h>
  8. #include <ArduinoOTA.h>
  9. #include <PubSubClient.h>
  10. #include <ArduinoJson.h>
  11. #include <FastLED.h>
  12. // In theory you can define a max packet size for MQTT here, but it doesn't work
  13. // You have to find the MQTT source (/home/dan/Arduino) and change it
  14. // there in the .h file. Then it seems to work
  15. //// Actually you can set it as client.setBufferSize(8192); // see below in setup
  16. //#undef MQTT_MAX_PACKET_SIZE
  17. //#define MQTT_MAX_PACKET_SIZE 16384
  18.  
  19. #ifndef STASSID
  20. #define STASSID "wifi"
  21. #define STAPSK "pass"
  22. #endif
  23.  
  24. const char* host = "browner";
  25. const char* ssid = STASSID;
  26. const char* password = STAPSK;
  27.  
  28. ESP8266WebServer httpServer(80);
  29. ESP8266HTTPUpdateServer httpUpdater;
  30.  
  31. //
  32. // LED PIN Setup
  33. //
  34. #define LED_PIN 13
  35. #define NUM_LEDS 292
  36. #define LED_TYPE WS2812B
  37. #define COLOR_ORDER GRB
  38. #define BRIGHTNESS 255
  39. #define SATURATION 255
  40. CRGB leds[NUM_LEDS];
  41.  
  42.  
  43. //
  44. // MQTT Setup
  45. //
  46. const char* mqttServer = "10.11.151.10";
  47. WiFiClient espClient; // defines the wifi clieent
  48. PubSubClient client(espClient); // constructor with partially initializsed client instance (see docs for pubsubclient)
  49. long lastReconnectAttempt = 0;
  50. #define MQTT_CONNECTED_LED 2
  51.  
  52. //
  53. // Individual Selected LEDs Array
  54. //
  55. #define LED_SELECT_ELEMENTS 5
  56. #define OFF_LEAD 0
  57. int selectedLeds[NUM_LEDS][LED_SELECT_ELEMENTS]; // led_select_elements is 5 now, for/// LED# / Brightness / R / G / B
  58. int staticSchema = 0; // 0 = static, lights on/off, 1 = dynamic, flowing/moving/rainbow lights
  59. int dynamicScene = 0; // integers running through all the dynamic scenes you set. Will be updated by MQTT and then assign an effect
  60.  
  61. //
  62. // JSON memory allocation
  63. //
  64. StaticJsonDocument<16384> ledArrayDoc; // For receiving light data;
  65.  
  66.  
  67.  
  68. /*
  69. * Start writing functions below
  70. *
  71. */
  72.  
  73.  
  74.  
  75.  
  76. //
  77. // LED Settings (and GRADIENT PALETTES)
  78. //
  79. // Gradient palettes are setup using palette knife from the FastLED pages.
  80. // http://fastled.io/tools/paletteknife/
  81. CRGBPalette16 currentPalette;
  82. TBlendType currentBlending;
  83. // http://soliton.vm.bytemark.co.uk/pub/cpt-city/rc/tn/purplefly.png.index.html
  84. DEFINE_GRADIENT_PALETTE( purplefly_gp ) {
  85. 0, 0, 0, 0,
  86. 63, 239, 0,122,
  87. 191, 252,255, 78,
  88. 255, 0, 0, 0};
  89. // http://soliton.vm.bytemark.co.uk/pub/cpt-city/rc/tn/autumnrose.png.index.html
  90. DEFINE_GRADIENT_PALETTE( autumnrose_gp ) {
  91. 0, 71, 3, 1,
  92. 45, 128, 5, 2,
  93. 84, 186, 11, 3,
  94. 127, 215, 27, 8,
  95. 153, 224, 69, 13,
  96. 188, 229, 84, 6,
  97. 226, 242,135, 17,
  98. 255, 247,161, 79};
  99. // http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/atmospheric/tn/Sunset_Real.png.index.html
  100. DEFINE_GRADIENT_PALETTE( Sunset_Real_gp ) {
  101. 0, 120, 0, 0,
  102. 22, 179, 22, 0,
  103. 51, 255,104, 0,
  104. 85, 167, 22, 18,
  105. 135, 100, 0,103,
  106. 198, 16, 0,130,
  107. 255, 0, 0,160};
  108. // http://soliton.vm.bytemark.co.uk/pub/cpt-city/bhw/bhw1/tn/bhw1_19.png.index.html
  109. DEFINE_GRADIENT_PALETTE( bhw1_19_gp ) {
  110. 0, 82, 1, 3,
  111. 79, 20, 1, 1,
  112. 181, 139, 1, 0,
  113. 252, 20, 1, 1,
  114. 255, 20, 1, 1};
  115. // http://soliton.vm.bytemark.co.uk/pub/cpt-city/ibcso/tn/ibcso-bath.png.index.html
  116. DEFINE_GRADIENT_PALETTE( ibcso_bath_gp ) {
  117. 0, 1, 4, 13,
  118. 106, 1, 4, 13,
  119. 106, 1, 10, 28,
  120. 127, 1, 10, 28,
  121. 127, 2, 19, 50,
  122. 148, 2, 19, 50,
  123. 148, 4, 31, 79,
  124. 170, 4, 31, 79,
  125. 170, 5, 47,119,
  126. 191, 5, 47,119,
  127. 191, 9, 80,158,
  128. 212, 9, 80,158,
  129. 212, 17,125,203,
  130. 233, 17,125,203,
  131. 233, 19,146,223,
  132. 244, 19,146,223,
  133. 244, 31,152,214,
  134. 249, 31,152,214,
  135. 249, 54,166,216,
  136. 255, 54,166,216};
  137. // http://soliton.vm.bytemark.co.uk/pub/cpt-city/saga/tn/saga-21.png.index.html
  138. DEFINE_GRADIENT_PALETTE( saga_21_gp ) {
  139. 0, 22, 81, 0,
  140. 13, 10,115, 0,
  141. 26, 3,154, 0,
  142. 40, 1,201, 0,
  143. 53, 0,255, 0,
  144. 67, 0,156, 4,
  145. 80, 0, 82, 25,
  146. 93, 0, 33, 71,
  147. 107, 0, 7,145,
  148. 120, 0, 0,255,
  149. 134, 3, 0,145,
  150. 147, 23, 0, 71,
  151. 161, 67, 0, 25,
  152. 174, 142, 0, 4,
  153. 187, 255, 0, 0,
  154. 201, 192, 1, 0,
  155. 214, 140, 7, 0,
  156. 228, 100, 17, 0,
  157. 241, 66, 33, 0,
  158. 255, 41, 55, 0};
  159.  
  160.  
  161.  
  162.  
  163.  
  164.  
  165.  
  166. //
  167. // Clear SelectedLedsArray()
  168. //
  169. void clearSelectedLedsArray() {
  170. for (int i=0; i<NUM_LEDS; i++) {
  171. // First you must put in the number of the led into the array
  172. selectedLeds[i][0] = i;
  173.  
  174. // Now for all three colors make them zero
  175. for (int j=1; j<LED_SELECT_ELEMENTS; j++) {
  176. selectedLeds[i][j] = 0;
  177. }
  178. }
  179. }
  180.  
  181. //
  182. // printSelectedLedArray
  183. //
  184. void printSelectedLedArray() {
  185. for(int i = 0; i<NUM_LEDS; i++) {
  186. Serial.print("Printing Selected Led Array: {{");
  187. for(int j = 0; j<LED_SELECT_ELEMENTS; j++) {
  188. Serial.print(selectedLeds[i][j]);
  189. Serial.print(",");
  190. }
  191. Serial.println("}}");
  192. }
  193. } // end print selected led array
  194.  
  195.  
  196. //
  197. // reconnectMQTT_NonBlock()
  198. //
  199. boolean reconnectMQTT_NonBlock() {
  200. if (client.connect("BookshelfLights")) {
  201. client.publish("connected", "Hello World, We have connected from the bookshelf lights successfully");
  202. client.subscribe("bookshelflights/#");
  203. }
  204. return client.connected();
  205. }
  206.  
  207. //
  208. // mqttCallback()
  209. // callback function to handle incoming mqtt messages
  210. //
  211. // This is also where you assign topics on mqtt to be processed to respective functions
  212. //
  213. void mqttCallback(char* topic, byte* payload, unsigned int length) {
  214. //Serial.print("Payload arrived on topic: ");
  215. //Serial.println(topic);
  216. //Serial.print("Payload size is: ");
  217. //Serial.println(sizeof(payload));
  218. //Serial.print(". Payload msg is: ");
  219.  
  220. /*
  221. for (int i=0; i<length; i++) {
  222. Serial.print((char)payload[i]);
  223. }
  224. Serial.println();
  225. */
  226.  
  227.  
  228. // Parse topics from the MQTT to be parsed accordingly
  229.  
  230. //
  231. // turn LEDs ON individually based on received json data
  232. //
  233. if (strcmp(topic, "bookshelflights/selectedLedsOn") == 0) {
  234. //Serial.println("Here New");
  235. staticSchema = 1; // set scheme to be static instead of dynamic moving lights
  236. processMqttIndividualLedsOnRequest(payload);
  237.  
  238. }
  239.  
  240. //
  241. // turn LEDs OFF
  242. //
  243. if (strcmp(topic, "bookshelflights/ledsOff") == 0) {
  244. //processMqttLedsOff();
  245. staticSchema = 1; // set scheme to be static instead of dynamic moving lights
  246. clearSelectedLedsArray();
  247. }
  248.  
  249. //
  250. // set a dynamic/moving scene
  251. //
  252. if (strcmp(topic, "bookshelflights/dynamicScene") == 0) {
  253. staticSchema = 0;
  254. clearSelectedLedsArray();
  255.  
  256. // Convert payload to int
  257. payload[length] = '\0';
  258. int sceneVal = atoi((char *)payload);
  259. dynamicScene = sceneVal;
  260. //Serial.print("Here is the dynamicScene, set to ");
  261. //Serial.println(dynamicScene);
  262.  
  263. }
  264.  
  265. } // end mqttCallback
  266.  
  267.  
  268.  
  269. //
  270. // updateIndividualLed
  271. //
  272. void updateIndividualLed(int ledNumber, int ledBrightness, int red, int green, int blue) {
  273. Serial.println(ledNumber);
  274. for (int i = 0; i<NUM_LEDS; i++) {
  275. if (selectedLeds[i][0] == ledNumber) {
  276. selectedLeds[i][1] = ledBrightness;
  277. selectedLeds[i][2] = red;
  278. selectedLeds[i][3] = green;
  279. selectedLeds[i][4] = blue;
  280. }
  281. }
  282. }
  283.  
  284. //
  285. // processMqttIndividualLedsOnRequest(byte* payload)
  286. //
  287. void processMqttIndividualLedsOnRequest(byte* payload) {
  288.  
  289. // Using ArduinoJson we put it into the memory
  290. DeserializationError error = deserializeJson(ledArrayDoc, payload);
  291. if (error) {
  292. Serial.print(F("deserializeJson() failed: "));
  293. Serial.println(error.c_str());
  294. return;
  295. }
  296.  
  297. // Clear old ones
  298. //clearSelectedLedsArray();
  299.  
  300. // Now make json array into loacl array
  301. JsonArray arr = ledArrayDoc.as<JsonArray>();
  302.  
  303. // Loop through the d ata and update master led array
  304. for (JsonObject repo : arr) {
  305. int ledNumber = repo["ledNumber"];
  306. int ledBright = repo["data"]["bright"];
  307. int ledR = repo["data"]["R"];
  308. int ledG = repo["data"]["G"];
  309. int ledB = repo["data"]["B"];
  310.  
  311. // Now update the array
  312. updateIndividualLed(ledNumber, ledBright, ledR, ledG, ledB);
  313. }
  314.  
  315. }
  316.  
  317. //
  318. // processMqttLedsOff()
  319. //
  320. void processMqttLedsOff() {
  321. clearSelectedLedsArray();
  322.  
  323. }
  324.  
  325. /*
  326. * fillLEDsFromPalete()
  327. * Fill the array of leds -- using an increasing colorIndex -- based on the current color paelette
  328. */
  329. void fillLEDsFromPalette( int ledStartIndex, int ledStopIndex, uint8_t colorIndex = 1, uint8_t brightness = 255 ) {
  330. for (int i = ledStartIndex; i < ledStopIndex; i++) {
  331. leds[i] = ColorFromPalette( currentPalette, colorIndex, brightness, currentBlending );
  332. // Advance index by 3, for R G B
  333. colorIndex += 3;
  334. }
  335. }
  336.  
  337.  
  338. /*
  339. * setup() loop
  340. *
  341. */
  342. void setup() {
  343. WiFi.setSleepMode(WIFI_NONE_SLEEP);
  344. Serial.begin(115200);
  345. Serial.println("Booting");
  346. WiFi.mode(WIFI_STA);
  347. WiFi.begin(ssid, password);
  348. while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  349. Serial.println("Connection Failed! Rebooting...");
  350. delay(5000);
  351. ESP.restart();
  352. }
  353.  
  354. // Port defaults to 8266
  355. // ArduinoOTA.setPort(8266);
  356.  
  357. // Hostname defaults to esp8266-[ChipID]
  358. // ArduinoOTA.setHostname("myesp8266");
  359.  
  360. // No authentication by default
  361. // ArduinoOTA.setPassword("admin");
  362.  
  363. // Password can be set with it's md5 value as well
  364. // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  365. // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
  366.  
  367. ArduinoOTA.onStart([]() {
  368. String type;
  369. if (ArduinoOTA.getCommand() == U_FLASH) {
  370. type = "sketch";
  371. } else { // U_FS
  372. type = "filesystem";
  373. }
  374.  
  375. // NOTE: if updating FS this would be the place to unmount FS using FS.end()
  376. Serial.println("Start updating " + type);
  377. });
  378.  
  379. ArduinoOTA.onEnd([]() {
  380. Serial.println("\nEnd");
  381. });
  382.  
  383. ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  384. Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  385. });
  386. ArduinoOTA.onError([](ota_error_t error) {
  387. Serial.printf("Error[%u]: ", error);
  388. if (error == OTA_AUTH_ERROR) {
  389. Serial.println("Auth Failed");
  390. } else if (error == OTA_BEGIN_ERROR) {
  391. Serial.println("Begin Failed");
  392. } else if (error == OTA_CONNECT_ERROR) {
  393. Serial.println("Connect Failed");
  394. } else if (error == OTA_RECEIVE_ERROR) {
  395. Serial.println("Receive Failed");
  396. } else if (error == OTA_END_ERROR) {
  397. Serial.println("End Failed");
  398. }
  399. });
  400. ArduinoOTA.begin();
  401. Serial.println("Ready");
  402. Serial.print("IP address: ");
  403. Serial.println(WiFi.localIP());
  404.  
  405.  
  406.  
  407. //************** HTTP UPDATE ******************
  408. Serial.println();
  409. Serial.println("Booting Sketch...");
  410. WiFi.mode(WIFI_STA);
  411. WiFi.softAPdisconnect(true);
  412. //WiFi.begin(ssid, password); // If you uncomment this it will also be in AP mode, from security perspective, you don't want that!
  413.  
  414. while(WiFi.waitForConnectResult() != WL_CONNECTED){
  415. WiFi.begin(ssid, password);
  416. Serial.println("WiFi failed, retrying.");
  417. }
  418.  
  419. MDNS.begin(host);
  420.  
  421. httpUpdater.setup(&httpServer);
  422. httpServer.begin();
  423.  
  424. MDNS.addService("http", "tcp", 80);
  425. Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
  426. Serial.println("");
  427. Serial.print ( "IP address: " );
  428. Serial.println ( WiFi.localIP() );
  429. //************** END HTTP UPDATE **************
  430.  
  431. client.setServer(mqttServer, 1883);
  432. client.setCallback(mqttCallback);
  433. client.setBufferSize(9192); // It seems I just can't get more than 8192 at a time on the wemos d1 mini
  434.  
  435. pinMode(MQTT_CONNECTED_LED, OUTPUT);
  436.  
  437. // Must setup the initial array
  438. clearSelectedLedsArray();
  439.  
  440.  
  441. currentBlending = LINEARBLEND;
  442. FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  443. FastLED.setBrightness( BRIGHTNESS );
  444.  
  445. } // end setup loop
  446.  
  447.  
  448. void loop() {
  449.  
  450. //
  451. // Begin by setting up wifi and http server for over the air updates
  452. // go to 10.11.151.81/update
  453. //
  454. httpServer.handleClient();
  455. ArduinoOTA.handle();
  456.  
  457. //
  458. // Now process MQTT being connected
  459. //
  460. if (!client.connected()) {
  461. digitalWrite(MQTT_CONNECTED_LED,HIGH);
  462. long now = millis();
  463. if (now - lastReconnectAttempt > 3000) {
  464. lastReconnectAttempt = now;
  465. if (reconnectMQTT_NonBlock()) {
  466. lastReconnectAttempt = 0;
  467. }
  468. }
  469. } else {
  470. client.loop();
  471. digitalWrite(MQTT_CONNECTED_LED, LOW);
  472. }
  473.  
  474.  
  475. static uint8_t colorIndex = 0;
  476. colorIndex = colorIndex + 1;
  477. int speed = 10;
  478.  
  479.  
  480. //
  481. // Move on to processing lights
  482. //
  483.  
  484.  
  485. // Process if it's static or still lights
  486. if (staticSchema == 1) {
  487. for(int i = 0; i <NUM_LEDS; i++) {
  488. leds[selectedLeds[i][0]].r = selectedLeds[i][2];
  489. leds[selectedLeds[i][0]].g = selectedLeds[i][3];
  490. leds[selectedLeds[i][0]].b = selectedLeds[i][4];
  491. //leds[selectedLeds[i][0]].fadeLightBy(255 - selectedLeds[i][1]);
  492. }
  493. speed = 100;
  494. }
  495.  
  496.  
  497. // Process if it's for 'moving' lights
  498. if (staticSchema == 0) {
  499. if (dynamicScene == 0) {
  500. currentPalette = bhw1_19_gp;
  501. fillLEDsFromPalette( 0, NUM_LEDS, colorIndex );
  502. speed = 5;
  503. }
  504. if (dynamicScene == 1) {
  505. currentPalette = autumnrose_gp;
  506. fillLEDsFromPalette( 0, NUM_LEDS, colorIndex );
  507. speed = 100;
  508. }
  509. if (dynamicScene == 2) {
  510. currentPalette = Sunset_Real_gp;
  511. fillLEDsFromPalette( 0, NUM_LEDS, colorIndex );
  512. speed = 100;
  513. }
  514. if (dynamicScene == 3) {
  515. currentPalette = ibcso_bath_gp;
  516. fillLEDsFromPalette( 0, NUM_LEDS, colorIndex );
  517. speed = 10;
  518. }
  519. if (dynamicScene == 4) {
  520. currentPalette = saga_21_gp;
  521. fillLEDsFromPalette( 0, NUM_LEDS, colorIndex );
  522. speed = 10;
  523. }
  524.  
  525.  
  526.  
  527. }
  528.  
  529.  
  530. //char str[8];
  531. //itoa( dynamicScene, str, 10 );
  532. //client.publish("temp/hi", str);
  533.  
  534.  
  535. FastLED.show();
  536. FastLED.delay(speed);
  537.  
  538. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement