> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/benz206/SpotifyMacroBoard/llms.txt
> Use this file to discover all available pages before exploring further.

# Functions

> Complete function reference for Spotify MacroBoard firmware

## Core functions

### setup()

Initializes all hardware components and establishes WiFi connection.

```cpp theme={null}
void setup()
```

<Accordion title="Setup sequence">
  1. Configure all button pins as inputs with pull-up resistors
  2. Configure LED and I2C pins
  3. Initialize FastLED library with WS2812B configuration
  4. Set LED brightness to 230 and power limit to 5V @ 500mA
  5. Display white color on all LEDs during initialization
  6. Initialize I2C bus at 400 kHz
  7. Initialize OLED display at I2C address 0x3C
  8. Connect to WiFi network
  9. Set server SSL certificate for secure HTTPS connections
</Accordion>

<Info>
  The setup function blocks until WiFi connection is established. LEDs pulse white during connection.
</Info>

**Error states:**

* **OrangeRed LEDs**: OLED display initialization failed
* **Pulsing white LEDs**: Attempting WiFi connection
* **Solid green LEDs**: Setup completed successfully

### loop()

Main program loop that handles button inputs and periodic updates.

```cpp theme={null}
void loop()
```

<Accordion title="Loop operations">
  1. Read all button states and detect button presses
  2. Call corresponding function when button pressed
  3. Update WiFi signal strength every 10 seconds
  4. Fetch current playback state every 5 seconds
  5. Update progress bar every 1 second
  6. Animate LED color fading when track changes
</Accordion>

**Timing intervals:**

* Button polling: Every loop iteration
* RSSI update: 10,000 ms
* Current state update: 5,000 ms
* Time update: 1,000 ms
* LED fade step: 4 ms

## Button handler functions

### shuffle()

Toggles shuffle mode on the connected Spotify account.

```cpp theme={null}
void shuffle()
```

Sends a shuffle state change request to the server API.

### volumeDecrease()

Decreases Spotify playback volume and updates the display.

```cpp theme={null}
void volumeDecrease()
```

Updates volume icon on screen after sending the decrease request.

### volumeIncrease()

Increases Spotify playback volume and updates the display.

```cpp theme={null}
void volumeIncrease()
```

Updates volume icon on screen after sending the increase request.

### repeat()

Toggles repeat/loop mode for the current track or playlist.

```cpp theme={null}
void repeat()
```

### back()

Skips to the previous track in the playback queue.

```cpp theme={null}
void back()
```

Triggers an immediate playback state update after 100ms to reflect the track change.

### pausePlay()

Toggles between play and pause states.

```cpp theme={null}
void pausePlay()
```

Triggers an immediate playback state update after 100ms to reflect the state change.

### skip()

Skips to the next track in the playback queue.

```cpp theme={null}
void skip()
```

Triggers an immediate playback state update and fetches new track information.

<Tip>
  Track skip functions (back, pausePlay, skip) all schedule an early update check to provide immediate visual feedback.
</Tip>

## Display functions

### updateScreen()

Refreshes the OLED display with WiFi signal and volume indicators.

```cpp theme={null}
void updateScreen()
```

<Accordion title="Display layout">
  * **Top-left (0-18px)**: WiFi signal strength icon
    * No bars: RSSI = 0 (disconnected)
    * One bar: RSSI \< -70 dBm (weak)
    * Two bars: RSSI >= -70 dBm (strong)
  * **Top-right (108-128px)**: Volume level icon
    * Muted: volume = 0
    * Low: volume 1-33
    * Medium: volume 34-66
    * High: volume 67-100
</Accordion>

Draws pixel-perfect icons using bitmap data from SampleCredentials.h.

### updateTime()

Draws the playback progress bar and time display.

```cpp theme={null}
void updateTime(int total, int current)
```

<ParamField path="total" type="int">
  Total track duration in seconds
</ParamField>

<ParamField path="current" type="int">
  Current playback position in seconds
</ParamField>

Displays time in MM:SS format with a horizontal progress bar at the bottom of the screen.

**Progress bar specs:**

* Width: 100 pixels
* Height: 6 pixels
* Position: X=14, Y=56
* Filled proportionally based on current/total ratio

## Network functions

### updateState()

Sends playback control commands to the server API.

```cpp theme={null}
void updateState(char action, int subAction = 0)
```

<ParamField path="action" type="char">
  Command type:

  * `'p'` - Play/pause
  * `'b'` - Back
  * `'s'` - Skip
  * `'r'` - Repeat/loop
  * `'v'` - Volume (requires subAction)
  * `'f'` - Shuffle
</ParamField>

<ParamField path="subAction" type="int" default="0">
  Volume direction:

  * `0` - Decrease
  * `1` - Increase
</ParamField>

<Warning>
  If the connection to benzhou.tech:443 fails, all LEDs turn red to indicate connection error.
</Warning>

Maintains a persistent HTTPS connection using Keep-Alive headers for reduced latency.

### updateCurrent()

Fetches current playback information from the server API.

```cpp theme={null}
void updateCurrent()
```

Retrieves and parses JSON response containing:

* Track title
* Artist name
* Album name
* Duration and progress (seconds)
* Paused state (boolean)
* Volume level (0-100)
* Album art dominant color (RGB)

**Error states:**

* **Red LEDs**: Connection to server failed
* **Yellow LEDs**: Server response timeout (>5 seconds)
* **Orange LEDs**: HTTP headers not found in response

<Info>
  When the track title changes, the display clears and shows new track information. The LED color fades to match the album art's dominant color.
</Info>

## Utility functions

### fadeLED()

Animates RGB LED transition between colors.

```cpp theme={null}
bool fadeLED()
```

**Returns:** `true` if fade is still in progress, `false` when complete.

Fades from previous color to new color over 256 steps using FastLED's blend function. Called every 4ms during active fade.

### extractValue()

Parses JSON responses to extract specific field values.

```cpp theme={null}
void extractValue(const String& key, const String& json, String& result)
```

<ParamField path="key" type="const String&">
  JSON key name to search for
</ParamField>

<ParamField path="json" type="const String&">
  Complete JSON response string
</ParamField>

<ParamField path="result" type="String&">
  Output variable to store the extracted value
</ParamField>

Searches for `"key":` pattern in JSON string and extracts the value between quotes, trimming whitespace.

<Tip>
  This lightweight JSON parser avoids heavy libraries like ArduinoJson to save memory on the ESP32.
</Tip>

## Function pointer array

Button functions are mapped to an array for efficient event handling:

```cpp theme={null}
void (*funcs[7])() = {
    shuffle, volumeDecrease, volumeIncrease, repeat, back, pausePlay, skip
};
```

This array corresponds to the button pin array, allowing the loop to call the correct function using `funcs[i]()` when button `i` is pressed.
