├── screenshot.png ├── readme.md └── usermod_pixelart_client.cpp /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hughc/wled-pixelart-client/HEAD/screenshot.png -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Pixel Art Client usermod 2 | 3 | ## Description 4 | This usermod is a client built to request images from the [Pixelart Exchange](https://app.pixelart-exchange.au/) or a [custom server](https://github.com/hughc/pixel-art-server). It can 5 | - perform cross fades between images 6 | - does optional 8-bit transparency over other WLED effects 7 | - understands multi-frame images / animated gifs (memory limitations apply). 8 | 9 | Due to limitations in the way that WLED handles refreshes, you need to select an effect to get higher frame rates. The usermod includes a custom effect (Pixel Art) that does nothing, but ups the refresh rate to improve cross-fade performance. Select it, and drag the Transition Speed slider to the right to speed up redraw performance. 10 | 11 | ## Hardware requirements 12 | An ESP32 is recommended, for the extra memory requirements to parse multi-frame images for larger matrixes (tested up to 32x32 pixels). 13 | 14 | ## Compilation 15 | 16 | These instructions assume that you are already comfortable with compiling WLED from source. 17 | 18 | 1. create a directory within `usermods` to hold the usermod. Suggested: `pixelart_client` and add `usermod_pixelart_client.cpp` to it. 19 | 20 | 2. To the `wled00/usermods_list.cpp` file, add the following 2 blocks of code 21 | 22 | At the top of the file where other usermods are #included: 23 | 24 | ``` 25 | #ifdef PIXELART_CLIENT_ENABLED 26 | #if defined(ESP8266) 27 | #include // Include the Wi-Fi library 28 | #include 29 | #else 30 | #include 31 | #include 32 | #endif 33 | #include 34 | #include "../usermods/pixelart_client/usermod_pixelart_client.cpp" 35 | #endif 36 | ``` 37 | 38 | Inside the `registerUsermods()` function: 39 | 40 | ``` 41 | #ifdef PIXELART_CLIENT_ENABLED 42 | usermods.add(new PixelArtClient()); 43 | #endif 44 | ``` 45 | 46 | 3. You can then trigger inclusion of the usermod with the following build flag: 47 | ``` 48 | -D PIXELART_CLIENT_ENABLED 49 | ``` 50 | added to your `platformio.ini` 51 | 52 | ## Configuration 53 | 54 | Once compiled and flashed to your device, head into Config -> Usermods. There should be a PixelArtClient section, like so: 55 | 56 | ![screenshot](/screenshot.png) 57 | 58 | By default, the client is configure to connect to the [Pixelart Exchange](https://app.pixelart-exchange.au/) server. You can configure it to connect to a local server if you have one set up. 59 | 60 | ### Pixelart Exchange 61 | The client will, out of the box, be served random images. If you [register](https://app.pixelart-exchange.au/register) for an account, you can go to Account Settings, copy the API key found there, and paste it into the usermod settings to associate your WLED device with your account. You can then set up a 'screen' in your account to uniquely identity the WLED client, allowing you to set unique playback modes or associate playlists of images with the screen. Once the screen is created, you can copy the Screen Id back into the usermod settings to associate your WLED device with the screen. 62 | 63 | ### local server 64 | With a [custom server](https://github.com/hughc/pixel-art-server) set up on your LAN, enter its URL. In the Usermod settings, enter a unique Screen Id. When you hit save a request to the server's `/checkin` endpoint will occur. If this is successful the client should start requesting and recieving images. If not, it will continue to periodically request the `/checkin` url until the server responds. 65 | 66 | Once checked in the client can be configured in the admin interface on the server to assign a playlist to it, otherwise it will be served random images. 67 | 68 | ## Debugging 69 | 70 | Some useful messages around what the client is doing are printed to the serial port, including the URLs it is requesting and how its memory use is faring. The URLs can be tested in a web browser. 71 | 72 | ## To do 73 | 74 | - switch to an asynchronous http client to stop animations freezing each time a request is made 75 | - write the results of each request to the file system (if space allows) and then read back to reduce the number of requests made -------------------------------------------------------------------------------- /usermod_pixelart_client.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #if defined(ESP8266) 5 | #include // Include the Wi-Fi library 6 | #include 7 | #include 8 | #else 9 | #include 10 | #include 11 | #include 12 | #endif 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | // Library inclusions. 24 | /* 25 | * Usermods allow you to add own functionality to WLED more easily 26 | * See: https://github.com/Aircoookie/WLED/wiki/Add-own-functionality 27 | * 28 | * This is an example for a v2 usermod. 29 | * v2 usermods are class inheritance based and can (but don't have to) implement more functions, each of them is shown in this example. 30 | * Multiple v2 usermods can be added to one compilation easily. 31 | * 32 | * Creating a usermod: 33 | * This file serves as an example. If you want to create a usermod, it is recommended to use usermod_v2_empty.h from the usermods folder as a template. 34 | * Please remember to rename the class and file to a descriptive name. 35 | * You may also use multiple .h and .cpp files. 36 | * 37 | * Using a usermod: 38 | * 1. Copy the usermod into the sketch folder (same folder as wled00.ino) 39 | * 2. Register the usermod by adding #include "usermod_filename.h" in the top and registerUsermod(new MyUsermodClass()) in the bottom of usermods_list.cpp 40 | */ 41 | 42 | /// Representation of an RGBA pixel (Red, Green, Blue, Alpha) 43 | struct CRGBA 44 | { 45 | union 46 | { 47 | struct 48 | { 49 | union 50 | { 51 | uint8_t r; 52 | uint8_t red; 53 | }; 54 | union 55 | { 56 | uint8_t g; 57 | uint8_t green; 58 | }; 59 | union 60 | { 61 | uint8_t b; 62 | uint8_t blue; 63 | }; 64 | union 65 | { 66 | uint8_t a; 67 | uint8_t alpha; 68 | }; 69 | }; 70 | uint8_t raw[4]; 71 | }; 72 | 73 | /// allow copy construction 74 | inline CRGBA(const CRGBA &rhs) __attribute__((always_inline)) = default; 75 | 76 | /// allow assignment from one RGB struct to another 77 | inline CRGBA& operator= (const CRGBA& rhs) __attribute__((always_inline)) = default; 78 | 79 | // default values are UNINITIALIZED 80 | inline CRGBA() __attribute__((always_inline)) = default; 81 | 82 | /// allow construction from R, G, B, A 83 | inline CRGBA(uint8_t ir, uint8_t ig, uint8_t ib, uint8_t ia) __attribute__((always_inline)) 84 | : r(ir), g(ig), b(ib), a(ia) 85 | { 86 | } 87 | 88 | /// allow assignment from R, G, and B 89 | inline CRGBA &setRGB(uint8_t nr, uint8_t ng, uint8_t nb) __attribute__((always_inline)) 90 | { 91 | r = nr; 92 | g = ng; 93 | b = nb; 94 | return *this; 95 | } 96 | 97 | CRGB toCRGB() 98 | { 99 | return CRGB(this->red, this->green, this->blue); 100 | } 101 | }; 102 | 103 | CRGBA &nblend_a(CRGBA &existing, const CRGBA &overlay, fract8 amountOfOverlay) 104 | { 105 | if (amountOfOverlay == 0) 106 | { 107 | return existing; 108 | } 109 | 110 | if (amountOfOverlay == 255) 111 | { 112 | existing = overlay; 113 | return existing; 114 | } 115 | 116 | // Corrected blend method, with no loss-of-precision rounding errors 117 | existing.red = blend8(existing.red, overlay.red, amountOfOverlay); 118 | existing.green = blend8(existing.green, overlay.green, amountOfOverlay); 119 | existing.blue = blend8(existing.blue, overlay.blue, amountOfOverlay); 120 | existing.alpha = blend8(existing.alpha, overlay.alpha, amountOfOverlay); 121 | 122 | return existing; 123 | } 124 | 125 | CRGBA blend_a(const CRGBA &p1, const CRGBA &p2, fract8 amountOfP2) 126 | { 127 | CRGBA nu(p1); 128 | nblend_a(nu, p2, amountOfP2); 129 | return nu; 130 | } 131 | 132 | CRGB flatten(CRGBA &overlay, CRGB &existing) 133 | { 134 | int const amountOfOverlay = overlay.alpha; 135 | if (amountOfOverlay == 0) 136 | { 137 | return existing; 138 | } 139 | 140 | if (amountOfOverlay == 255) 141 | { 142 | return overlay.toCRGB(); 143 | } 144 | // Corrected blend method, with no loss-of-precision rounding errors 145 | CRGB rCRGB = CRGB( blend8(existing.red, overlay.red, amountOfOverlay), blend8(existing.green, overlay.green, amountOfOverlay), blend8(existing.blue, overlay.blue, amountOfOverlay)); 146 | 147 | return rCRGB; 148 | } 149 | 150 | // class name. Use something descriptive and leave the ": public Usermod" part :) 151 | class PixelArtClient : public Usermod 152 | { 153 | 154 | private: 155 | // Private class members. You can declare variables and functions only accessible to your usermod here 156 | bool enabled = false; 157 | bool initDone = false; 158 | unsigned long refreshTime = 0; 159 | unsigned long lastRequestTime = 0; 160 | 161 | // set your config variables to their boot default value (this can also be done in readFromConfig() or a constructor if you prefer) 162 | String serverName = "https://app.pixelart-exchange.au/"; 163 | String apiKey = "your_api_key"; 164 | String clientName = "WLED"; 165 | bool transparency = false; 166 | bool serverUp = false; 167 | long unsigned int serverTestRepeatTime = 10; 168 | 169 | // These config variables have defaults set inside readFromConfig() 170 | int testInt; 171 | long testLong; 172 | int8_t testPins[2]; 173 | int crossfadeIncrement = 10; 174 | int crossfadeFrameRate = 40; 175 | std::vector>> image1; 176 | std::vector>> image2; 177 | std::vector image1durations; 178 | std::vector image2durations; 179 | 180 | std::vector>> *currentImage; 181 | std::vector>> *nextImage; 182 | std::vector *nextImageDurations; 183 | std::vector *currentImageDurations; 184 | 185 | // need a struct to hold all this (pixels, frameCount, frame timings ) 186 | int nextImageFrameCount = 1; 187 | int currentImageFrameCount = 1; 188 | CRGB nextImageBackgroundColour; 189 | CRGB currentImageBackgroundColour; 190 | int numFrames; 191 | 192 | int currentFrameIndex = 0; 193 | // within the image, we may have one or more frames 194 | std::vector> currentFrame; 195 | unsigned int currentFrameDuration; 196 | // within the next image,cache the first frame for a transition 197 | std::vector> nextFrame; 198 | int nextBlend = 0; 199 | 200 | // time betwwen images 201 | int duration; 202 | // in seconds 203 | unsigned int imageDuration = 10; 204 | bool imageLoaded = false; 205 | int imageIndex = 0; 206 | 207 | HTTPClient http; 208 | WiFiClient client; 209 | 210 | String playlist; 211 | String name; 212 | 213 | // string that are used multiple time (this will save some flash memory) 214 | static const char _name[]; 215 | static const char _enabled[]; 216 | 217 | // any private methods should go here (non-inline methosd should be defined out of class) 218 | void publishMqtt(const char *state, bool retain = false); // example for publishing MQTT message 219 | 220 | public: 221 | // non WLED related methods, may be used for data exchange between usermods (non-inline methods should be defined out of class) 222 | 223 | /** 224 | * Enable/Disable the usermod 225 | */ 226 | inline void enable(bool enable) { enabled = enable; } 227 | 228 | /** 229 | * Get usermod enabled/disabled state 230 | */ 231 | inline bool isEnabled() { return enabled; } 232 | 233 | // in such case add the following to another usermod: 234 | // in private vars: 235 | // #ifdef USERMOD_EXAMPLE 236 | // MyExampleUsermod* UM; 237 | // #endif 238 | // in setup() 239 | // #ifdef USERMOD_EXAMPLE 240 | // UM = (MyExampleUsermod*) usermods.lookup(USERMOD_ID_EXAMPLE); 241 | // #endif 242 | // somewhere in loop() or other member method 243 | // #ifdef USERMOD_EXAMPLE 244 | // if (UM != nullptr) isExampleEnabled = UM->isEnabled(); 245 | // if (!isExampleEnabled) UM->enable(true); 246 | // #endif 247 | 248 | 249 | 250 | 251 | 252 | static uint16_t dummyEffect() 253 | { 254 | return FRAMETIME; 255 | } 256 | 257 | static uint16_t mode_pixelart(void) 258 | { 259 | return PixelArtClient::dummyEffect(); 260 | } 261 | 262 | void requestImageFrames() 263 | { 264 | // Your Domain name with URL path or IP address with path 265 | 266 | 267 | currentImage = imageIndex ? &image1 : &image2; 268 | nextImage = imageIndex ? &image2 : &image1; 269 | currentImageDurations = imageIndex ? &image1durations : &image2durations; 270 | nextImageDurations = imageIndex ? &image2durations : &image1durations; 271 | const String serverPath = "api/image/pixels"; 272 | const String clientPhrase = "screen_id=" + clientName; 273 | const String keyPhrase = "&key=" + apiKey; 274 | 275 | const String width = String(strip._segments[strip.getCurrSegmentId()].maxWidth); 276 | const String height = String(strip._segments[strip.getCurrSegmentId()].maxHeight); 277 | const String getUrl = serverName + (serverName.endsWith("/") ? "" : "/") + serverPath + "?" + clientPhrase + keyPhrase + "&width=" + width + "&height=" + height; 278 | ; 279 | 280 | Serial.print("requestImageFrames: "); 281 | Serial.println(getUrl); 282 | http.begin(client, (getUrl).c_str()); 283 | 284 | // Send HTTP GET request, turn back to http 1.0 for streaming 285 | http.useHTTP10(true); 286 | int httpResponseCode = http.GET(); 287 | // Serial.print("HTTP Response code: "); 288 | // Serial.println(httpResponseCode); 289 | if (httpResponseCode != 200) 290 | { 291 | Serial.print("image fetch failed, request returned code "); 292 | Serial.println(httpResponseCode); 293 | http.end(); 294 | return; 295 | } 296 | // payload = http.getStream(); 297 | 298 | // Serial.print("total stream length: "); 299 | // Serial.println(http.getString().length()); 300 | 301 | // Serial.print("parseResponse() start: remaining heap: "); 302 | // Serial.println(ESP.getFreeHeap(), DEC); 303 | 304 | DynamicJsonDocument doc(2048); 305 | Stream &client = http.getStream(); 306 | 307 | client.find("\"meta\""); 308 | client.find(":"); 309 | // meta 310 | DeserializationError error = deserializeJson(doc, client); 311 | 312 | if (error) 313 | { 314 | Serial.print("deserializeJson() failed: "); 315 | Serial.println(error.c_str()); 316 | imageLoaded = false; 317 | return; 318 | } 319 | 320 | const unsigned int totalFrames = doc["frames"]; 321 | nextImageBackgroundColour = hexToCRGB(doc["backgroundColor"]); 322 | const unsigned int returnHeight = doc["height"]; 323 | const unsigned int returnWidth = doc["width"]; 324 | const char *path = doc["path"]; // "ms-pacman.gif" 325 | name = String(path); 326 | 327 | Serial.print("nextImage.resize: "); 328 | Serial.println(totalFrames); 329 | (*nextImage).resize(totalFrames); 330 | 331 | Serial.print("nextImage.size: "); 332 | Serial.println((*nextImage).size()); 333 | 334 | for (size_t i = 0; i < totalFrames; i++) 335 | { 336 | (*nextImage)[i].resize(returnHeight); 337 | Serial.print("nextImage[i].resize: "); 338 | Serial.println(returnHeight); 339 | for (size_t j = 0; j < returnHeight; j++) 340 | { 341 | Serial.print("nextImage[i][j].resize: "); 342 | Serial.println(returnWidth); 343 | (*nextImage)[i][j].resize(returnWidth); 344 | } 345 | } 346 | 347 | nextImageDurations->resize(totalFrames); 348 | 349 | client.find("\"rows\""); 350 | client.find("["); 351 | do 352 | { 353 | DeserializationError error = deserializeJson(doc, client); 354 | // ...extract values from the document... 355 | 356 | // Serial.print("pixelsJson.size: "); 357 | // Serial.println(rowPixels.size()); 358 | 359 | // read row metadata 360 | int frame_duration = doc["duration"]; // 200, 200, 200 361 | int frameIndex = doc["frame"]; // 200, 200, 200 362 | (*nextImageDurations)[frameIndex] = frame_duration; 363 | int rowIndex = doc["row"]; // 200, 200, 200 364 | 365 | // const JsonArray rows = frame["pixels"]; 366 | 367 | JsonArray rowPixels = doc["pixels"].as(); 368 | int colIndex = 0; 369 | 370 | (*nextImage)[frameIndex][rowIndex].resize(returnWidth); 371 | 372 | for (JsonVariant pixel : rowPixels) 373 | { 374 | const char *pixelStr = (pixel.as()); 375 | const CRGBA color = hexToCRGBA(String(pixelStr));\ 376 | (*nextImage)[frameIndex][rowIndex][colIndex] = color; 377 | colIndex++; 378 | } 379 | 380 | } while (client.findUntil(",", "]")); 381 | 382 | // Free resources 383 | http.end(); 384 | 385 | if (error) 386 | { 387 | Serial.print("deserializeJson() failed: "); 388 | Serial.println(error.c_str()); 389 | imageLoaded = false; 390 | return; 391 | } 392 | 393 | nextImageFrameCount = totalFrames; 394 | 395 | // imageDuration = doc["duration"]; // 10 396 | // JsonArray framesJson = doc["frames"].as(); 397 | // Serial.print("framesJson.size: "); 398 | // Serial.println(framesJson.size()); 399 | 400 | // Once the values have been parsed, resize the frames vector to the appropriate size 401 | 402 | // int frameIndex = 0; 403 | // for (JsonObject frame : framesJson) 404 | // { 405 | // // parse a frame, which is rows > column nested arrays 406 | 407 | // int frame_duration = frame["duration"]; // 200, 200, 200 408 | // const JsonArray rows = frame["pixels"]; 409 | // int totalRows = rows.size(); 410 | // int rowIndex = 0; 411 | // (*nextImageDurations)[frameIndex] = frame_duration; 412 | // (*nextImage)[frameIndex].resize(totalRows); 413 | 414 | // for (JsonArray column : rows) 415 | // { 416 | // // int totalColumns = column.size(); 417 | // int colIndex = 0; 418 | // (*nextImage)[frameIndex][rowIndex].resize(totalRows); 419 | // for (JsonVariant pixel : column) 420 | // { 421 | // const char *pixelStr = (pixel.as()); 422 | // const CRGB color = hexToCRGB(String(pixelStr)); 423 | // (*nextImage)[frameIndex][rowIndex][colIndex] = color; 424 | // colIndex++; 425 | // } 426 | // rowIndex++; 427 | // } 428 | // frameIndex++; 429 | // } 430 | // nextImageFrameCount = totalFrames; 431 | 432 | Serial.print("parseResponse() done: remaining heap: "); 433 | Serial.println(ESP.getFreeHeap(), DEC); 434 | imageLoaded = true; 435 | 436 | Serial.print("requestImageFrames finished, remaining heap: "); 437 | Serial.println(ESP.getFreeHeap(), DEC); 438 | // return payload; 439 | } 440 | 441 | CRGB hexToCRGB(String hexString) 442 | { 443 | // Convert the hex string to an integer value 444 | uint32_t hexValue = strtoul(hexString.c_str(), NULL, 16); 445 | 446 | // Extract the red, green, and blue components from the hex value 447 | uint8_t red = (hexValue >> 16) & 0xFF; 448 | uint8_t green = (hexValue >> 8) & 0xFF; 449 | uint8_t blue = hexValue & 0xFF; 450 | 451 | // Create a CRGB object with the extracted components 452 | CRGB color = CRGB(red, green, blue); 453 | 454 | return color; 455 | } 456 | CRGBA hexToCRGBA(String hexString) 457 | { 458 | // Convert the hex string to an integer value 459 | uint32_t hexValue = strtoul(hexString.c_str(), NULL, 16); 460 | 461 | // Extract the red, green, and blue components from the hex value 462 | uint8_t red = (hexValue >> 24) & 0xFF; 463 | uint8_t green = (hexValue >> 16) & 0xFF; 464 | uint8_t blue = (hexValue >> 8) & 0xFF; 465 | uint8_t alpha = hexValue & 0xFF; 466 | 467 | // Create a CRGB object with the extracted components 468 | CRGBA color = CRGBA(red, green, blue, alpha); 469 | 470 | return color; 471 | } 472 | 473 | void parseResponse(std::vector>> &frames, const Stream &response, String playlist, String &pathStr, int &durationInt) 474 | { 475 | 476 | ; 477 | // path, playlist,duration, totalFrame 478 | 479 | // char* input; 480 | // size_t inputLength; (optional) 481 | } 482 | 483 | void completeImageTransition() 484 | { 485 | 486 | // flip to the next image for the next request 487 | imageIndex = imageIndex == 0 ? 1 : 0; 488 | // and flip which image is which, so nextImage -> currentImage 489 | // used in next redraw 490 | currentImage = imageIndex ? &image1 : &image2; 491 | currentImageDurations = imageIndex ? &image1durations : &image2durations; 492 | 493 | // reuse this for the next image load 494 | nextImage = imageIndex ? &image2 : &image1; 495 | nextImageDurations = imageIndex ? &image2durations : &image1durations; 496 | currentImageFrameCount = nextImageFrameCount; 497 | currentImageBackgroundColour = nextImageBackgroundColour; 498 | 499 | currentFrameIndex = 0; 500 | currentFrame = (*currentImage)[currentFrameIndex]; 501 | currentFrameDuration = (*currentImageDurations)[currentFrameIndex]; 502 | } 503 | 504 | void getImage() 505 | { 506 | Serial.print("getImage() start: remaining heap: "); 507 | Serial.println(ESP.getFreeHeap(), DEC); 508 | // Send request 509 | requestImageFrames(); 510 | 511 | // String playlist; 512 | // String name; 513 | Serial.print("getImage() after requestImageFrames: remaining heap: "); 514 | Serial.println(ESP.getFreeHeap(), DEC); 515 | 516 | // parseResponse(frames, rawResponse, playlist, name, duration); 517 | 518 | Serial.print("requestImageFrames new image: "); 519 | Serial.println(name); 520 | 521 | // prime these for next redraw 522 | if (imageLoaded) 523 | { 524 | if (image1.size() > 0 && image2.size() > 0) 525 | { 526 | // we have 2 images, crossfade them 527 | nextBlend = crossfadeIncrement; 528 | nextFrame = (*nextImage)[0]; 529 | } 530 | else 531 | { 532 | // first load? just show it; 533 | completeImageTransition(); 534 | } 535 | } 536 | } 537 | 538 | // methods called by WLED (can be inlined as they are called only once but if you call them explicitly define them out of class) 539 | 540 | /* 541 | * setup() is called once at boot. WiFi is not yet connected at this point. 542 | * readFromConfig() is called prior to setup() 543 | * You can use it to initialize variables, sensors or similar. 544 | */ 545 | void setup() 546 | { 547 | // do your set-up here 548 | Serial.print("Hello from pixel art grabber! WLED matrix mode on? "); 549 | Serial.println(strip.isMatrix); 550 | initDone = true; 551 | strip.addEffect(255, &PixelArtClient::mode_pixelart, "Pixel Art@Transition Speed;;;2"); 552 | } 553 | 554 | void checkin() 555 | { 556 | const String width = String(strip._segments[strip.getCurrSegmentId()].maxWidth); 557 | const String height = String(strip._segments[strip.getCurrSegmentId()].maxHeight); 558 | const String getUrl = serverName + (serverName.endsWith("/") ? "api/client/checkin?id=" : "/api/client/checkin?id=") + clientName + "&width=" + width + "&height=" + height; 559 | Serial.println(getUrl); 560 | http.begin(client, (getUrl).c_str()); 561 | 562 | // Send HTTP GET request 563 | int httpResponseCode = http.GET(); 564 | serverUp = (httpResponseCode == 200); 565 | if (!serverUp) 566 | { 567 | Serial.print("Pixel art client failed to checkin, request returned "); 568 | Serial.println(httpResponseCode); 569 | } 570 | else 571 | { 572 | Serial.print("Pixel art client checked in OK"); 573 | } 574 | http.end(); 575 | } 576 | 577 | /* 578 | * connected() is called every time the WiFi is (re)connected 579 | * Use it to initialize network interfaces 580 | */ 581 | void connected() 582 | { 583 | Serial.println("Connected to WiFi, checking in!"); 584 | checkin(); 585 | } 586 | 587 | /* 588 | * loop() is called continuously. Here you can check for events, read sensors, etc. 589 | * 590 | * Tips: 591 | * 1. You can use "if (WLED_CONNECTED)" to check for a successful network connection. 592 | * Additionally, "if (WLED_MQTT_CONNECTED)" is available to check for a connection to an MQTT broker. 593 | * 594 | * 2. Try to avoid using the delay() function. NEVER use delays longer than 10 milliseconds. 595 | * Instead, use a timer check as shown here. 596 | */ 597 | void loop() 598 | { 599 | // if usermod is disabled or called during strip updating just exit 600 | // NOTE: on very long strips strip.isUpdating() may always return true so update accordingly 601 | 602 | // Serial.println("looping"); 603 | // Serial.println(!enabled); 604 | // Serial.println(strip.isUpdating()); 605 | // Serial.println(!strip.isMatrix); 606 | if (!enabled || !strip.isMatrix) 607 | return; 608 | 609 | if (!serverUp && ((millis() - lastRequestTime) > serverTestRepeatTime * 1000)) 610 | { 611 | lastRequestTime = millis(); 612 | checkin(); 613 | return; 614 | } 615 | 616 | // request next image 617 | if (millis() - lastRequestTime > imageDuration * 1000) 618 | { 619 | Serial.println("in loop, getting image"); 620 | lastRequestTime = millis(); 621 | getImage(); 622 | } 623 | } 624 | 625 | void setPixelsFrom2DVector(const std::vector> &pixelValues, CRGB backgroundColour) 626 | { 627 | 628 | // iterate through the 2D vector of CRGBA values 629 | int whichRow = 0; 630 | for (std::vector row : pixelValues) 631 | { 632 | int whichCol = 0; 633 | for (CRGBA pixel : row) 634 | { 635 | CRGB finalColour; 636 | if (transparency) 637 | { 638 | CRGB existing = strip.getPixelColorXY(whichCol, whichRow); 639 | finalColour = flatten(pixel, existing); 640 | } 641 | else 642 | { 643 | finalColour = flatten(pixel, backgroundColour); 644 | } 645 | strip.setPixelColorXY(whichCol, whichRow, finalColour); 646 | whichCol++; 647 | } 648 | whichRow++; 649 | } 650 | } 651 | 652 | void setPixelsFrom2DVector(std::vector> ¤tPixels, std::vector> &nextPixels, int &blendPercent, CRGB &backgroundColour) 653 | { 654 | 655 | // iterate through the 2D vector of CRGB values 656 | int whichRow = 0; 657 | for (std::vector row : currentPixels) 658 | { 659 | int whichCol = 0; 660 | for (CRGBA pixel : row) 661 | { 662 | const CRGBA targetPixel = nextFrame[whichRow][whichCol]; 663 | CRGBA newPixel = blend_a(pixel, targetPixel, blendPercent); 664 | CRGB finalColour; 665 | if (transparency) 666 | { 667 | CRGB existing = strip.getPixelColorXY(whichCol, whichRow); 668 | finalColour = flatten(newPixel, existing); 669 | } 670 | else 671 | { 672 | finalColour = flatten(newPixel, backgroundColour); 673 | } 674 | strip.setPixelColorXY(whichCol, whichRow, finalColour); 675 | whichCol++; 676 | } 677 | whichRow++; 678 | } 679 | } 680 | 681 | /* 682 | * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. 683 | * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. 684 | * Below it is shown how this could be used for e.g. a light sensor 685 | */ 686 | void addToJsonInfo(JsonObject &root) 687 | { 688 | // if "u" object does not exist yet wee need to create it 689 | JsonObject user = root["u"]; 690 | if (user.isNull()) 691 | user = root.createNestedObject("u"); 692 | 693 | // this code adds "u":{"ExampleUsermod":[20," lux"]} to the info object 694 | // int reading = 20; 695 | // JsonArray lightArr = user.createNestedArray(FPSTR(_name))); //name 696 | // lightArr.add(reading); //value 697 | // lightArr.add(F(" lux")); //unit 698 | 699 | // if you are implementing a sensor usermod, you may publish sensor data 700 | // JsonObject sensor = root[F("sensor")]; 701 | // if (sensor.isNull()) sensor = root.createNestedObject(F("sensor")); 702 | // temp = sensor.createNestedArray(F("light")); 703 | // temp.add(reading); 704 | // temp.add(F("lux")); 705 | } 706 | 707 | /* 708 | * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). 709 | * Values in the state object may be modified by connected clients 710 | */ 711 | void addToJsonState(JsonObject &root) 712 | { 713 | if (!initDone || !enabled) 714 | return; // prevent crash on boot applyPreset() 715 | 716 | JsonObject usermod = root[FPSTR(_name)]; 717 | if (usermod.isNull()) 718 | usermod = root.createNestedObject(FPSTR(_name)); 719 | 720 | // usermod["user0"] = userVar0; 721 | } 722 | 723 | /* 724 | * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). 725 | * Values in the state object may be modified by connected clients 726 | */ 727 | void readFromJsonState(JsonObject &root) 728 | { 729 | if (!initDone) 730 | return; // prevent crash on boot applyPreset() 731 | 732 | JsonObject usermod = root[FPSTR(_name)]; 733 | if (!usermod.isNull()) 734 | { 735 | // expect JSON usermod data in usermod name object: {"ExampleUsermod:{"user0":10}"} 736 | userVar0 = usermod["user0"] | userVar0; // if "user0" key exists in JSON, update, else keep old value 737 | } 738 | // you can as well check WLED state JSON keys 739 | // if (root["bri"] == 255) Serial.println(F("Don't burn down your garage!")); 740 | } 741 | 742 | /* 743 | * addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object. 744 | * It will be called by WLED when settings are actually saved (for example, LED settings are saved) 745 | * If you want to force saving the current state, use serializeConfig() in your loop(). 746 | * 747 | * CAUTION: serializeConfig() will initiate a filesystem write operation. 748 | * It might cause the LEDs to stutter and will cause flash wear if called too often. 749 | * Use it sparingly and always in the loop, never in network callbacks! 750 | * 751 | * addToConfig() will make your settings editable through the Usermod Settings page automatically. 752 | * 753 | * Usermod Settings Overview: 754 | * - Numeric values are treated as floats in the browser. 755 | * - If the numeric value entered into the browser contains a decimal point, it will be parsed as a C float 756 | * before being returned to the Usermod. The float data type has only 6-7 decimal digits of precision, and 757 | * doubles are not supported, numbers will be rounded to the nearest float value when being parsed. 758 | * The range accepted by the input field is +/- 1.175494351e-38 to +/- 3.402823466e+38. 759 | * - If the numeric value entered into the browser doesn't contain a decimal point, it will be parsed as a 760 | * C int32_t (range: -2147483648 to 2147483647) before being returned to the usermod. 761 | * Overflows or underflows are truncated to the max/min value for an int32_t, and again truncated to the type 762 | * used in the Usermod when reading the value from ArduinoJson. 763 | * - Pin values can be treated differently from an integer value by using the key name "pin" 764 | * - "pin" can contain a single or array of integer values 765 | * - On the Usermod Settings page there is simple checking for pin conflicts and warnings for special pins 766 | * - Red color indicates a conflict. Yellow color indicates a pin with a warning (e.g. an input-only pin) 767 | * - Tip: use int8_t to store the pin value in the Usermod, so a -1 value (pin not set) can be used 768 | * 769 | * See usermod_v2_auto_save.h for an example that saves Flash space by reusing ArduinoJson key name strings 770 | * 771 | * If you need a dedicated settings page with custom layout for your Usermod, that takes a lot more work. 772 | * You will have to add the setting to the HTML, xml.cpp and set.cpp manually. 773 | * See the WLED Soundreactive fork (code and wiki) for reference. https://github.com/atuline/WLED 774 | * 775 | * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! 776 | */ 777 | void addToConfig(JsonObject &root) 778 | { 779 | JsonObject top = root.createNestedObject(FPSTR(_name)); 780 | top[FPSTR(_enabled)] = enabled; 781 | // save these vars persistently whenever settings are saved 782 | top["server url"] = serverName; 783 | top["api key"] = apiKey; 784 | top["screen id"] = clientName; 785 | top["transparent"] = transparency; 786 | } 787 | 788 | /* 789 | * readFromConfig() can be used to read back the custom settings you added with addToConfig(). 790 | * This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page) 791 | * 792 | * readFromConfig() is called BEFORE setup(). This means you can use your persistent values in setup() (e.g. pin assignments, buffer sizes), 793 | * but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup. 794 | * If you don't know what that is, don't fret. It most likely doesn't affect your use case :) 795 | * 796 | * Return true in case the config values returned from Usermod Settings were complete, or false if you'd like WLED to save your defaults to disk (so any missing values are editable in Usermod Settings) 797 | * 798 | * getJsonValue() returns false if the value is missing, or copies the value into the variable provided and returns true if the value is present 799 | * The configComplete variable is true only if the "exampleUsermod" object and all values are present. If any values are missing, WLED will know to call addToConfig() to save them 800 | * 801 | * This function is guaranteed to be called on boot, but could also be called every time settings are updated 802 | */ 803 | bool readFromConfig(JsonObject &root) 804 | { 805 | // default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor 806 | // setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed) 807 | 808 | JsonObject top = root[FPSTR(_name)]; 809 | 810 | bool configComplete = !top.isNull(); 811 | 812 | configComplete &= getJsonValue(top["enabled"], enabled); 813 | configComplete &= getJsonValue(top["server url"], serverName); 814 | configComplete &= getJsonValue(top["screen id"], clientName); 815 | configComplete &= getJsonValue(top["api key"], apiKey); 816 | configComplete &= getJsonValue(top["transparent"], transparency); 817 | return configComplete; 818 | } 819 | 820 | /* 821 | * appendConfigData() is called when user enters usermod settings page 822 | * it may add additional metadata for certain entry fields (adding drop down is possible) 823 | * be careful not to add too much as oappend() buffer is limited to 3k 824 | */ 825 | void appendConfigData() 826 | { 827 | oappend(SET_F("addInfo('PixelArtClient:server url', 1, '');")); 828 | oappend(SET_F("addInfo('PixelArtClient:screen id', 1, '');")); 829 | oappend(SET_F("addInfo('PixelArtClient:api key', 1, '');")); 830 | oappend(SET_F("addField('PixelArtClient:transparent', 1, true);")); 831 | } 832 | 833 | /* 834 | * handleOverlayDraw() is called just before every show() (LED strip update frame) after effects have set the colors. 835 | * Use this to blank out some LEDs or set them to a different color regardless of the set effect mode. 836 | * Commonly used for custom clocks (Cronixie, 7 segment) 837 | */ 838 | void handleOverlayDraw() 839 | { 840 | // draw currently cached image again 841 | if (enabled && imageLoaded) 842 | { 843 | // redrawing 844 | // Serial.println("handleOverlayDraw() -> redrawing"); 845 | 846 | // cycle frames within a multi-frame image (ie animated gif) 847 | if (millis() - refreshTime > currentFrameDuration) 848 | { 849 | // Serial.print("flipping frames: "); 850 | // Serial.print(currentFrameIndex); 851 | // Serial.print(" of "); 852 | // Serial.print(currentImageFrameCount); 853 | // Serial.println(""); 854 | refreshTime = millis(); 855 | currentFrameIndex++; 856 | currentFrameIndex = currentFrameIndex % currentImageFrameCount; 857 | // choose next frame in set to update 858 | currentFrame = (*currentImage)[currentFrameIndex]; 859 | currentFrameDuration = (*currentImageDurations)[currentFrameIndex]; 860 | } 861 | 862 | if (nextBlend > 0) 863 | { 864 | setPixelsFrom2DVector(currentFrame, nextFrame, nextBlend, currentImageBackgroundColour); 865 | nextBlend += crossfadeIncrement; 866 | // while(nextBlend<=255) { 867 | 868 | // busses.show(); 869 | // delay(1000/crossfadeFrameRate); 870 | // } 871 | if (nextBlend > 255) 872 | { 873 | nextBlend = 0; 874 | completeImageTransition(); 875 | } 876 | } 877 | else 878 | { 879 | setPixelsFrom2DVector(currentFrame, currentImageBackgroundColour); 880 | } 881 | } 882 | } 883 | 884 | /** 885 | * handleButton() can be used to override default button behaviour. Returning true 886 | * will prevent button working in a default way. 887 | * Replicating button.cpp 888 | */ 889 | bool handleButton(uint8_t b) 890 | { 891 | yield(); 892 | // ignore certain button types as they may have other consequences 893 | if (!enabled || buttonType[b] == BTN_TYPE_NONE || buttonType[b] == BTN_TYPE_RESERVED || buttonType[b] == BTN_TYPE_PIR_SENSOR || buttonType[b] == BTN_TYPE_ANALOG || buttonType[b] == BTN_TYPE_ANALOG_INVERTED) 894 | { 895 | return false; 896 | } 897 | 898 | bool handled = false; 899 | // do your button handling here 900 | return handled; 901 | } 902 | 903 | #ifndef WLED_DISABLE_MQTT 904 | /** 905 | * handling of MQTT message 906 | * topic only contains stripped topic (part after /wled/MAC) 907 | */ 908 | bool onMqttMessage(char *topic, char *payload) 909 | { 910 | // check if we received a command 911 | // if (strlen(topic) == 8 && strncmp_P(topic, PSTR("/command"), 8) == 0) { 912 | // String action = payload; 913 | // if (action == "on") { 914 | // enabled = true; 915 | // return true; 916 | // } else if (action == "off") { 917 | // enabled = false; 918 | // return true; 919 | // } else if (action == "toggle") { 920 | // enabled = !enabled; 921 | // return true; 922 | // } 923 | //} 924 | return false; 925 | } 926 | 927 | /** 928 | * onMqttConnect() is called when MQTT connection is established 929 | */ 930 | void onMqttConnect(bool sessionPresent) 931 | { 932 | // do any MQTT related initialisation here 933 | // publishMqtt("I am alive!"); 934 | } 935 | #endif 936 | 937 | /** 938 | * onStateChanged() is used to detect WLED state change 939 | * @mode parameter is CALL_MODE_... parameter used for notifications 940 | */ 941 | void onStateChange(uint8_t mode) 942 | { 943 | // do something if WLED state changed (color, brightness, effect, preset, etc) 944 | } 945 | 946 | /* 947 | * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). 948 | * This could be used in the future for the system to determine whether your usermod is installed. 949 | */ 950 | uint16_t getId() 951 | { 952 | return USERMOD_ID_EXAMPLE; 953 | } 954 | 955 | // More methods can be added in the future, this example will then be extended. 956 | // Your usermod will remain compatible as it does not need to implement all methods from the Usermod base class! 957 | }; 958 | 959 | // add more strings here to reduce flash memory usage 960 | const char PixelArtClient::_name[] PROGMEM = "PixelArtClient"; 961 | const char PixelArtClient::_enabled[] PROGMEM = "enabled"; 962 | 963 | // implementation of non-inline member methods 964 | 965 | void PixelArtClient::publishMqtt(const char *state, bool retain) 966 | { 967 | #ifndef WLED_DISABLE_MQTT 968 | // Check if MQTT Connected, otherwise it will crash the 8266 969 | if (WLED_MQTT_CONNECTED) 970 | { 971 | char subuf[64]; 972 | strcpy(subuf, mqttDeviceTopic); 973 | strcat_P(subuf, PSTR("/example")); 974 | mqtt->publish(subuf, 0, retain, state); 975 | } 976 | #endif 977 | } 978 | --------------------------------------------------------------------------------