/* * ------------------------------------------------------------ * "THE BEERWARE LICENSE" (Revision 42): * DerGrubengräber / Carl Hinze wrote this code. As long as you retain this * notice, you can do whatever you want with this stuff. If we * meet someday, and you think this stuff is worth it, you can * buy me a beer in return. * ------------------------------------------------------------ */ #include #include #include #include #include #include #include #include #include #include #include #include #include "idle_gif.h" #include "birthday_gif.h" #include #include #include "secrets.h" #include // What the fuck was the best way to declare variables again? // Do i care about optimizing with defines, idk man volatile bool switchState = 0; // Time things WiFiUDP wifiUdp; NTP ntp(wifiUdp); // Light sensor BH1750 GY302; float lux = 1.00f; // ADC / Brightness type shit const int potPin = GPIO_NUM_6; int adcResult = 0; uint8_t targetBrightness = 255; #define NUM_SAMPLES 64 // Gang i don't know JPEGDEC jpeg; volatile bool playing = false; volatile bool paused = false; // Do i even still need that? SemaphoreHandle_t albumArtMutex = xSemaphoreCreateMutex(); #define MUTEX_TIMEOUT 5000 uint16_t albumArt[64 * 64]; float rotation = 0.0; const float ROTATION_SPEED = 0.5f; Preferences preferences; // Task handles in case i need them again TaskHandle_t taskSpotifyHandle; TaskHandle_t taskPanelHandle; TaskHandle_t taskIOHandle; AnimatedGIF gif; uint16_t idleGifBuffer[64 * 64]; // Spotify API String access_token = ""; const String refresh_token = SPOTIFY_REFRESH_TOKEN; const String encoded = SPOTIFY_ENCODED; String urlPrev = ""; String url; // Wifi const char *ssid = WIFI_SSID; const char *password = WIFI_PASSWORD; // LED Matrix #define PANEL_RES_X 64 // Number of pixels wide of each INDIVIDUAL panel module. #define PANEL_RES_Y 64 // Number of pixels tall of each INDIVIDUAL panel module. #define PANEL_CHAIN 1 // Total number of panels chained one to another horizontally only. MatrixPanel_I2S_DMA *dma_display = nullptr; uint16_t myBLACK; uint16_t myWHITE; uint16_t myRED; uint16_t myGREEN; uint16_t myBLUE; int x_offset, y_offset; #define R1_PIN GPIO_NUM_46 //B0 #define G1_PIN GPIO_NUM_21 //D10 #define B1_PIN GPIO_NUM_1 //A0 #define R2_PIN GPIO_NUM_18 //D9 #define G2_PIN GPIO_NUM_2 //A1 #define B2_PIN GPIO_NUM_17 //D8 #define A_PIN GPIO_NUM_10 //D7 #define B_PIN GPIO_NUM_4 //A3 #define C_PIN GPIO_NUM_9 //D6 #define D_PIN GPIO_NUM_11 //A4 #define E_PIN GPIO_NUM_3 // required for 1/32 scan panels, like 64x64px. Any available pin would do, i.e. IO32 A2 #define LAT_PIN GPIO_NUM_12 // A5 #define OE_PIN GPIO_NUM_7 // D4 #define CLK_PIN GPIO_NUM_8 // D5 HUB75_I2S_CFG::i2s_pins _pins = { R1_PIN, G1_PIN, B1_PIN, R2_PIN, G2_PIN, B2_PIN, A_PIN, B_PIN, C_PIN, D_PIN, E_PIN, LAT_PIN, OE_PIN, CLK_PIN }; void setupSwitch() { pinMode(GPIO_NUM_0, OUTPUT); digitalWrite(GPIO_NUM_0, HIGH); pinMode(GPIO_NUM_5, INPUT); } void setupLightSensor() { Wire.begin(GPIO_NUM_14, GPIO_NUM_13); GY302.begin(); } void connectWifi() { WiFi.mode(WIFI_STA); //Optional WiFi.begin(ssid, password); Serial.println("\nConnecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(100); } Serial.println("\nConnected to the WiFi network"); Serial.print("Local ESP32 IP: "); Serial.println(WiFi.localIP()); } void loadPreferences() { // Doesn't really make sense anymore. Serial.println("Loading Preferences..."); preferences.begin("spotify", false); access_token = preferences.getString("Access", ""); //refresh_token = preferences.getString("Refresh", ""); preferences.end(); Serial.println("Preferences loaded."); } void setupPanel() { HUB75_I2S_CFG mxconfig( PANEL_RES_X, // module width PANEL_RES_Y, // module height PANEL_CHAIN // Chain of panels - Horizontal width only. , _pins); mxconfig.double_buff = true; dma_display = new MatrixPanel_I2S_DMA(mxconfig); dma_display->begin(); dma_display->setBrightness8(targetBrightness); //0-255 dma_display->flipDMABuffer(); delay(1000 / dma_display->calculated_refresh_rate); myBLACK = dma_display->color565(0, 0, 0); myWHITE = dma_display->color565(255, 255, 255); myRED = dma_display->color565(255, 0, 0); myGREEN = dma_display->color565(0, 255, 0); myBLUE = dma_display->color565(0, 0, 255); dma_display->clearScreen(); dma_display->println("Booting..."); dma_display->flipDMABuffer(); delay(1000 / dma_display->calculated_refresh_rate); } struct JPEGTuple { uint8_t *address; size_t size; }; struct JPEGTuple downloadJPEG(String url) { Serial.println("Downloading: " + url); WiFiClientSecure client; client.setInsecure(); HTTPClient http; http.setTimeout(15000); http.begin(client, url); int httpReturnCode = http.GET(); if (httpReturnCode != 200) { Serial.println("Image Download aborted with code " + httpReturnCode); return { nullptr, 0 }; } Serial.println(httpReturnCode); int contentLength = http.getSize(); if (contentLength <= 0) { Serial.println("Invalid or unknown content length."); http.end(); return { nullptr, 0 }; } Serial.println("Size is: " + String(contentLength)); uint8_t *jpegBuffer = (uint8_t *)heap_caps_malloc(contentLength, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); if (!jpegBuffer) { Serial.println("Malloc failed."); http.end(); return { nullptr, 0 }; } WiFiClient &stream = http.getStream(); size_t downloadedData = 0; Serial.println("Downloading"); unsigned long timeoutStart = millis(); while (downloadedData < contentLength && http.connected()) { size_t sizeAvailable = stream.available(); if (sizeAvailable) { size_t bytesRead = stream.readBytes(&jpegBuffer[downloadedData], min(sizeAvailable, (size_t)(contentLength - downloadedData))); downloadedData += bytesRead; timeoutStart = millis(); Serial.println(downloadedData + String("B")); } else { if (millis() - timeoutStart > 5000) { Serial.println("Download timeout."); break; } delay(1); } } http.end(); //delete client; if (downloadedData != contentLength) { Serial.println("Incomplete JPEG download!"); free(jpegBuffer); return { nullptr, 0 }; } Serial.println("Download completed. Size was: " + downloadedData); return { jpegBuffer, downloadedData }; } int storeJPEG(JPEGDRAW *pDraw) { xSemaphoreTake(albumArtMutex, portMAX_DELAY); for (int y = 0; y < pDraw->iHeight; y++) { int destY = pDraw->y + y; if (destY < 0 || destY >= 64) continue; for (int x = 0; x < pDraw->iWidth; x++) { int destX = pDraw->x + x; if (destX < 0 || destX >= 64) continue; // Compression kept giving me extremely dark artifacts which were visible on the Matrix tho so i added this threshhold. Adjust if it kills shadows etc. uint16_t color = pDraw->pPixels[y * pDraw->iWidthUsed + x]; uint8_t r = (color >> 11) & 0x1F; uint8_t g = (color >> 5) & 0x3F; uint8_t b = color & 0x1F; if (r <= 2 && g <= 3 && b <= 2) { color = 0; } albumArt[destY * 64 + destX] = color; } } xSemaphoreGive(albumArtMutex); return 1; } bool decodeJPEG(uint8_t *jpegData, size_t jpegSize) { xSemaphoreTake(albumArtMutex, portMAX_DELAY); memset(albumArt, 0, sizeof(albumArt)); xSemaphoreGive(albumArtMutex); if (!jpeg.openRAM(jpegData, jpegSize, storeJPEG)) { Serial.printf( "JPEG open failed, error = %d\n", jpeg.getLastError()); return false; } bool result = jpeg.decode(0, 0, 0); jpeg.close(); if (!result) { Serial.printf( "JPEG decode failed, error = %d\n", jpeg.getLastError()); return false; } return true; } void drawCD(float angle) { dma_display->clearScreen(); const int cx = 31; const int cy = 31; const float cosA = cos(angle); const float sinA = sin(angle); const int radius = 31; const int radiusSquared = radius * radius; xSemaphoreTake(albumArtMutex, portMAX_DELAY); for (int y = 0; y < 64; y++) { for (int x = 0; x < 64; x++) { int dx = x - cx; int dy = y - cy; if ((dx * dx + dy * dy) > radiusSquared) continue; float srcX = cosA * dx + sinA * dy + cx; float srcY = -sinA * dx + cosA * dy + cy; int sx = (int)srcX; int sy = (int)srcY; if (sx < 0 || sx >= 64 || sy < 0 || sy >= 64) continue; // Ugly af but idk how to do it without redoing all the math if ((x == 0 && y == 31) || (x == 31 && y == 0) || (x == 31 && y == 62) || (x == 62 && y == 31)) { continue; } uint16_t color = albumArt[sy * 64 + sx]; dma_display->drawPixel(x, y, color); } } xSemaphoreGive(albumArtMutex); // Center hole const int holeRadius = 4; for (int y = cy - holeRadius; y <= cy + holeRadius; y++) { for (int x = cx - holeRadius; x <= cx + holeRadius; x++) { int dx = x - cx; int dy = y - cy; /*if ((x == 31 && y == 27) || (x == 31 && y == 35) || (x == 27 && y == 31) || (x == 35 && y == 31)){ continue; } */ if (dx * dx + dy * dy <= holeRadius * holeRadius) { dma_display->drawPixel(x, y, myBLACK); } } } // Small center spindle dma_display->drawPixel(cx, cy, myWHITE); dma_display->flipDMABuffer(); } void GIFDraw(GIFDRAW *pDraw) { const uint8_t *src = pDraw->pPixels; const uint16_t *palette = pDraw->pPalette; int y = pDraw->iY + pDraw->y; int xStart = pDraw->iX; if (y < 0 || y >= 64) return; for (int x = 0; x < pDraw->iWidth; x++) { int destX = xStart + x; if (destX < 0 || destX >= 64) continue; uint8_t colorIndex = src[x]; if (pDraw->ucHasTransparency && colorIndex == pDraw->ucTransparent) { continue; } idleGifBuffer[y * 64 + destX] = palette[colorIndex]; } } void refreshToken() { Serial.println("Refreshing Token..."); HTTPClient http; http.begin("https://accounts.spotify.com/api/token"); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); http.addHeader("Authorization", "Basic " + encoded); int httpResponseCode = http.POST("grant_type=refresh_token&refresh_token=" + refresh_token + "&client_id=" + SPOTIFY_CLIENT_ID); if (httpResponseCode > 0) { Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); JSONVar payload = JSON.parse(http.getString()); access_token = String(payload["access_token"]); preferences.begin("spotify", false); preferences.putString("Access", access_token); preferences.end(); } else { Serial.print("Failed refresh with Error code: "); Serial.println(httpResponseCode); Serial.println(http.errorToString(httpResponseCode)); } http.end(); } String getTrack() { HTTPClient http; http.begin("https://api.spotify.com/v1/me/player/currently-playing"); http.addHeader("Authorization", "Bearer " + access_token); int httpResponseCode = http.GET(); if (httpResponseCode > 0) { //String payload = http.getString(); if (httpResponseCode == 200) { String payload = http.getString(); http.end(); JSONVar JSONPayload = JSON.parse(payload); paused = !JSONPayload["is_playing"]; playing = true; return String(JSONPayload["item"]["album"]["images"][2]["url"]); } else if (httpResponseCode == 401) { Serial.println("Token expired!"); http.end(); return "EXPIRED"; } else if (httpResponseCode == 204) { http.end(); Serial.println("Nothing Playing."); return "NOTHING"; } else { String payload = http.getString(); http.end(); Serial.print("Unhandled response. "); Serial.println(payload); return "ERROR"; } } else { Serial.print("Failed to get track with Error code: "); Serial.println(httpResponseCode); Serial.println(http.errorToString(httpResponseCode)); http.end(); return "ERROR"; } } void spotifyTask(void *parameter) { while (true) { if (lux > 0.00 || switchState) { url = getTrack(); if (url == "EXPIRED") { refreshToken(); vTaskDelay(1000 / portTICK_PERIOD_MS); continue; } if (url == "ERROR" || url == "NOTHING") { playing = false; } else if (urlPrev != url) { urlPrev = url; JPEGTuple buffer = downloadJPEG(url); if (buffer.address != nullptr) { if (decodeJPEG(buffer.address, buffer.size)) { Serial.println("Album art loaded."); } heap_caps_free(buffer.address); } } } vTaskDelay(1000 / portTICK_PERIOD_MS); } } void panelTask(void *parameter) { const TickType_t framePeriod = pdMS_TO_TICKS(33); ; String time = ntp.formattedTime("%m%e"); if (time == String("11 1")) { Serial.println("HAPPY BIRTHDAY"); if (gif.open((uint8_t *)birthday_gif, sizeof(birthday_gif), GIFDraw)) { int start = millis(); Serial.printf("Successfully opened GIF; Canvas size = %d x %d\n", gif.getCanvasWidth(), gif.getCanvasHeight()); while (millis() - start < 5000) { dma_display->setBrightness(targetBrightness); while (gif.playFrame(true, NULL)) { dma_display->clearScreen(); for (int y = 0; y < 64; y++) { for (int x = 0; x < 64; x++) { dma_display->drawPixel(x, y, idleGifBuffer[y * 64 + x]); } } dma_display->flipDMABuffer(); } gif.reset(); } } } TickType_t lastWake = xTaskGetTickCount(); TickType_t previousFrame = lastWake; while (true) { TickType_t now = xTaskGetTickCount(); float deltaTime = (now - previousFrame) * portTICK_PERIOD_MS / 1000.0f; previousFrame = now; if (lux > 0.00 || switchState) { dma_display->setBrightness(targetBrightness); if (!playing) { Serial.println("Entering Idle."); if (gif.open((uint8_t *)idle_gif, sizeof(idle_gif), GIFDraw)) { Serial.printf("Successfully opened GIF; Canvas size = %d x %d\n", gif.getCanvasWidth(), gif.getCanvasHeight()); while (!playing) { if (lux == 0.00 && !switchState) { break; } dma_display->setBrightness(targetBrightness); while (gif.playFrame(true, NULL)) { dma_display->clearScreen(); for (int y = 0; y < 64; y++) { for (int x = 0; x < 64; x++) { dma_display->drawPixel(x, y, idleGifBuffer[y * 64 + x]); } } dma_display->flipDMABuffer(); } gif.reset(); } } Serial.println("Closing Gif."); gif.close(); lastWake = xTaskGetTickCount(); drawCD(0); //So it doesn't get stuck on the last frame of the gif if paused continue; } if (!paused && playing) { rotation += ROTATION_SPEED * deltaTime; if (rotation >= TWO_PI) rotation -= TWO_PI; drawCD(rotation); } } else { dma_display->clearScreen(); dma_display->flipDMABuffer(); } vTaskDelayUntil(&lastWake, framePeriod); } } void iOTask(void *parameter) { TickType_t lastWake = xTaskGetTickCount(); while (true) { switchState = digitalRead(GPIO_NUM_5); lux = GY302.readLightLevel(); if (lux < 0) { //This needs proper error handling. lux = 1; } /* Serial.print("Light: "); Serial.print(lux); Serial.print(" lx"); Serial.print("Switch is: "); Serial.println(switchState); */ uint32_t adcSum = 0; for (int i = 0; i < NUM_SAMPLES; i++) { adcSum += analogRead(potPin); } adcResult = adcSum / NUM_SAMPLES; if (adcResult <= 10) { adcResult = 0; } targetBrightness = map(adcResult, 0, 4095, 0, 255); //Serial.print("Pot: "); //Serial.println(adcResult); vTaskDelayUntil(&lastWake, pdMS_TO_TICKS(100)); } } void setup() { Serial.begin(9600); delay(1000); analogReadResolution(12); setupLightSensor(); setupSwitch(); setupPanel(); loadPreferences(); dma_display->clearScreen(); dma_display->print("Connecting..."); dma_display->flipDMABuffer(); connectWifi(); ntp.begin(); ntp.update(); Serial.println(ntp.formattedTime("%m%e")); gif.begin(LITTLE_ENDIAN_PIXELS); // Memory allocation is fine ish, Spotify could prolly do with a kb less. xTaskCreatePinnedToCore( spotifyTask, "SpotifyTask", 5120, NULL, 1, &taskSpotifyHandle, 0); xTaskCreatePinnedToCore( panelTask, "panelTask", 2048, NULL, 1, &taskPanelHandle, 1); xTaskCreatePinnedToCore( iOTask, "IOTask", 2048, NULL, 1, &taskIOHandle, 0); } void loop() { delay(60000); Serial.println("60 Second Memory Update:"); Serial.print("TASK: "); Serial.print(pcTaskGetName(taskPanelHandle)); // Get task name with handler Serial.print(", High Watermark: "); Serial.print(uxTaskGetStackHighWaterMark(taskPanelHandle)); Serial.println(); Serial.print("TASK: "); Serial.print(pcTaskGetName(taskSpotifyHandle)); // Get task name with handler Serial.print(", High Watermark: "); Serial.print(uxTaskGetStackHighWaterMark(taskSpotifyHandle)); Serial.println(); Serial.print("TASK: "); Serial.print(pcTaskGetName(taskIOHandle)); // Get task name with handler Serial.print(", High Watermark: "); Serial.print(uxTaskGetStackHighWaterMark(taskIOHandle)); Serial.println(); }