home-assistant/core · warning · ValueError

Invalid code: {code!r}

Error message

Invalid code: {code!r}

What it means

ValueError(f"Invalid code: {code!r}") from _extract_codes: the stored or supplied code string failed data_packet() decoding, which base64-decodes and validates the Broadlink packet (padding fix-up included in helpers). It means the code exists but its content is not a valid base64 Broadlink data packet.

Source

Thrown at homeassistant/components/broadlink/remote.py:165

            else:
                if device is None:
                    raise ValueError("You need to specify a device")

                try:
                    codes = self._codes[device][cmd]
                except KeyError as err:
                    raise ValueError(f"Command not found: {cmd!r}") from err

                if isinstance(codes, list):
                    codes = codes[:]
                else:
                    codes = [codes]

            for idx, code in enumerate(codes):
                try:
                    codes[idx] = data_packet(code)
                except ValueError as err:
                    raise ValueError(f"Invalid code: {code!r}") from err

            code_list.append(codes)
        return code_list

    @callback
    def _get_codes(self):
        """Return a dictionary of codes."""
        return self._codes

    @callback
    def _get_flags(self):
        """Return a dictionary of toggle flags.

        A toggle flag indicates whether the remote should send an
        alternative code.
        """
        return self._flags

View on GitHub (pinned to 58a3fdb3ea)

Solutions

  1. Re-learn the command so a fresh valid code is stored.
  2. If supplying b64: codes manually, validate the base64 payload (length % 4 padding, no whitespace) before sending.
  3. Keep long base64 strings on one line in YAML or use proper quoting/folding.
  4. Avoid hand-editing the broadlink codes storage; use learn/delete services.

Example fix

# before (broken paste with newline)
command: "b64:JgBQAAABKU5RExERExERExE
KU5Q..."

# after (single line, valid base64)
command: "b64:JgBQAAABKU5RExERExERExEKU5Q=="
Defensive patterns

Strategy: validation

Validate before calling

import base64, binascii

def is_valid_b64_packet(code: str) -> bool:
    """True if the string is clean base64 that decodes to a Broadlink packet."""
    try:
        base64.b64decode(code, validate=True)
        return True
    except (binascii.Error, ValueError):
        return False

Type guard

def is_decodable_code(value: object) -> bool:
    """Narrow to non-empty, whitespace-free base64 strings."""
    return (
        isinstance(value, str)
        and value != ""
        and not any(ch.isspace() for ch in value)
    )

Try / catch

try:
    codes = remote._extract_codes(commands, device)
except ValueError as err:
    if "Invalid code" in str(err):
        # drop the corrupt entry and re-learn it later
        commands = [c for c in commands if c not in str(err)]
    else:
        raise

Prevention

When it happens

Trigger: A learned code string got corrupted (truncated, whitespace/newlines, bad base64 chars), or a hand-copied 'b64:'-style code from the internet is malformed. codes[idx] = data_packet(code) raises ValueError and it is re-raised with the offending code shown.

Common situations: Copy-paste of codes from forums with smart quotes/line wraps, YAML mangling of long base64 strings, partial writes to the storage file, editing .storage by hand.

Related errors


AI-assisted analysis of home-assistant/core@58a3fdb3ea (2026-08-14). Data as JSON: /api/errors/54f6c71942b4b679. Report an issue: GitHub.