Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions infrared_protocols/commands/panasonic_ac.py
Comment thread
sam0737 marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""Generic Panasonic air-conditioner IR protocol.

Panasonic A/C remotes share a common framing: a state byte list split into two
sections (an 8-byte section 1 followed by a variable section 2), each encoded
LSB-first at 38 kHz with a fixed leader, per-bit mark/space, and a trailing
mark plus gap. Individual models differ only in the byte layout and checksum
range, so :class:`PanasonicAcCommand` encodes an already-built state and leaves
the layout to subclasses.
"""

from typing import override

from . import Command

# Physical-layer timings, in microseconds (canonical Panasonic values).
HEADER_MARK = 3456
HEADER_SPACE = 1728
BIT_MARK = 432
ZERO_SPACE = 432
ONE_SPACE = 1296
SECTION_GAP = 10000
MESSAGE_GAP = 100000

MODULATION_HZ = 38000

# Section 1 is always the first 8 bytes; section 2 is the remainder.
SECTION1_LENGTH = 8


def checksum(state: list[int], start: int, end: int) -> int:
Comment thread
sam0737 marked this conversation as resolved.
Outdated
"""Sum bytes ``state[start..end]`` (inclusive) modulo 256."""
total = 0
for i in range(start, end + 1):
total = (total + state[i]) & 0xFF
return total


def _bits_lsb(byte: int) -> list[int]:
"""Return the 8 bits of ``byte``, least-significant first."""
return [(byte >> j) & 1 for j in range(8)]


def _section_timings(section: list[int], trailing_gap: int) -> list[int]:
"""Encode one section (header + LSB-first bits + trailing mark/gap)."""
timings: list[int] = [HEADER_MARK, -HEADER_SPACE]
for byte in section:
for bit in _bits_lsb(byte):
timings.append(BIT_MARK)
timings.append(-(ONE_SPACE if bit else ZERO_SPACE))
timings.append(BIT_MARK)
timings.append(-trailing_gap)
return timings


def state_to_timings(state: list[int]) -> list[int]:
Comment thread
sam0737 marked this conversation as resolved.
Outdated
"""Convert a state byte list into signed microsecond timings.

Positive values are pulse (carrier on) durations; negative values are space
(carrier off) durations. The state is split into section 1 (the first
:data:`SECTION1_LENGTH` bytes) and section 2 (the remainder).
"""
section1 = state[:SECTION1_LENGTH]
section2 = state[SECTION1_LENGTH:]
return [
*_section_timings(section1, SECTION_GAP),
*_section_timings(section2, MESSAGE_GAP),
]


class PanasonicAcCommand(Command):
"""Generic Panasonic air-conditioner IR command."""

_state: list[int]

def __init__(self, *, state: list[int], modulation: int = MODULATION_HZ) -> None:
"""Wrap a pre-built Panasonic A/C state byte list."""
super().__init__(modulation=modulation, repeat_count=0)
self._state = state

@override
def get_raw_timings(self) -> list[int]:
"""Get raw timings for the command."""
return state_to_timings(self._state)
140 changes: 140 additions & 0 deletions infrared_protocols/commands/panasonic_ac_hk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""Panasonic air-conditioner IR protocol for Hong Kong / Macau models.

Reverse-engineered protocol for Panasonic air conditioners sold in Hong Kong
and Macau (CW-HU / CW-HZ / CW-SU / CW-SUL families). Builds a 27-byte full
state frame (power/mode/temperature/fan/swing/nanoeX) or a 16-byte
Quiet/Powerful short frame, then reuses the generic
:class:`~infrared_protocols.commands.panasonic_ac.PanasonicAcCommand` framing to
encode it to signed microsecond timings at 38 kHz.
"""

from typing import Literal, Self

from .panasonic_ac import PanasonicAcCommand, checksum

MIN_TEMP = 16
MAX_TEMP = 30
Comment thread
sam0737 marked this conversation as resolved.
Outdated

AcMode = Literal["auto", "dry", "cool", "heat"]
FanSpeed = Literal["auto", "low", "mediumLow", "medium", "mediumHigh", "high"]
SwingMode = Literal["auto", "fixed"]
ShortFrameKind = Literal["quiet", "powerful"]
Comment thread
sam0737 marked this conversation as resolved.
Outdated

_MODE_NIBBLE: dict[AcMode, int] = {
Comment thread
sam0737 marked this conversation as resolved.
Outdated
"auto": 0x0,
"dry": 0x2,
"cool": 0x3,
"heat": 0x4,
}
_FAN_NIBBLE: dict[FanSpeed, int] = {
"auto": 0xA,
"low": 0x3,
"mediumLow": 0x4,
"medium": 0x5,
"mediumHigh": 0x6,
"high": 0x7,
}
_SWING_NIBBLE: dict[SwingMode, int] = {"auto": 0xF, "fixed": 0x5}

_NANOEX_MASK = 0x04

_SHORT_PAYLOAD: dict[ShortFrameKind, list[int]] = {
"quiet": [0x80, 0x81, 0x33],
"powerful": [0x80, 0x86, 0x35],
}


def build_full_frame(
*,
off: bool = False,
mode: AcMode,
temp: float,
fan: FanSpeed,
swing: SwingMode,
nanoex: bool,
) -> list[int]:
"""Build the 27-byte full state frame from semantic parameters.

``temp`` is in degrees Celsius; byte 14 stores ``round(temp * 2)`` so the
protocol's 0.5 °C step is preserved.
"""
state = [0] * 27
for i, value in enumerate([0x02, 0x20, 0xE0, 0x04, 0x00, 0x00, 0x00, 0x06]):
state[i] = value
state[8] = 0x02
state[9] = 0x20
state[10] = 0xE0
state[11] = 0x04
state[12] = 0x00
state[13] = (_MODE_NIBBLE[mode] << 4) | (0 if off else 1)
state[14] = round(temp * 2)
state[15] = 0x80
state[16] = (_FAN_NIBBLE[fan] << 4) | _SWING_NIBBLE[swing]
state[17] = 0x0D
state[18] = 0x00
state[19] = 0x0E
state[20] = 0xE0
state[21] = 0x00
state[22] = 0x00
state[23] = 0x81
state[24] = 0x00
state[25] = 0x02 | (_NANOEX_MASK if nanoex else 0x00)
state[26] = checksum(state, 8, 25)
return state


def build_short_frame(kind: ShortFrameKind) -> list[int]:
"""Build the 16-byte Quiet/Powerful toggle frame."""
try:
payload = _SHORT_PAYLOAD[kind]
except KeyError:
raise ValueError(f"unknown short-frame kind: {kind!r}") from None
state = [
0x02,
0x20,
0xE0,
0x04,
0x00,
0x00,
0x00,
0x06,
0x02,
0x20,
0xE0,
0x04,
*payload,
]
state.append(checksum(state, 8, 14))
return state


class PanasonicAcHkCommand(PanasonicAcCommand):
Comment thread
sam0737 marked this conversation as resolved.
Outdated
"""Panasonic air-conditioner IR command for Hong Kong / Macau models."""

@classmethod
def full(
Comment thread
sam0737 marked this conversation as resolved.
Outdated
cls,
*,
off: bool = False,
mode: AcMode,
temp: float,
fan: FanSpeed,
swing: SwingMode,
nanoex: bool,
) -> Self:
"""Build a full state command (power/mode/temp/fan/swing/nanoeX)."""
return cls(
state=build_full_frame(
off=off,
mode=mode,
temp=temp,
fan=fan,
swing=swing,
nanoex=nanoex,
)
)

@classmethod
def short(cls, *, kind: ShortFrameKind) -> Self:
"""Build a Quiet/Powerful toggle command."""
return cls(state=build_short_frame(kind))
62 changes: 62 additions & 0 deletions tests/commands/test_panasonic_ac.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Tests for the generic Panasonic A/C IR protocol."""

from infrared_protocols.commands.panasonic_ac import (
MODULATION_HZ,
PanasonicAcCommand,
checksum,
state_to_timings,
)

# A minimal two-section state: 8-byte section 1 + 4-byte section 2.
SAMPLE_STATE: list[int] = [
0x02,
0x20,
0xE0,
0x04,
0x00,
0x00,
0x00,
0x06,
0x02,
0x20,
0xE0,
0x04,
]


def test_checksum_sum_mod_256() -> None:
"""Test checksum sums the inclusive byte range modulo 256."""
state = [0x00, 0xFF, 0x01, 0x05]
assert checksum(state, 1, 3) == (0xFF + 0x01 + 0x05) & 0xFF
Comment thread
sam0737 marked this conversation as resolved.
Outdated


def test_state_to_timings_leader() -> None:
"""Test encoding starts with the Panasonic leader."""
timings = state_to_timings(SAMPLE_STATE)
Comment thread
sam0737 marked this conversation as resolved.
Outdated
assert timings[:2] == [3456, -1728]


def test_state_to_timings_section_split() -> None:
"""Test both sections are encoded with their own leader and gap.

Each byte is 8 bits (2 timings/bit); each section adds a leader pair and a
trailing mark/gap pair. The first section gap is the inter-section gap and
the final gap is the message gap.
"""
timings = state_to_timings(SAMPLE_STATE)
Comment thread
sam0737 marked this conversation as resolved.
Outdated
bits_per_section1 = 8 * 8 * 2
section1_len = 2 + bits_per_section1 + 2
# Section 1 trailing gap is the inter-section gap.
assert timings[section1_len - 1] == -10000
# Section 2 leader follows immediately.
assert timings[section1_len : section1_len + 2] == [3456, -1728]
# Final timing is the message gap.
assert timings[-1] == -100000


def test_command_get_raw_timings_matches_helper() -> None:
"""Test the command wrapper returns the same timings as the helper."""
command = PanasonicAcCommand(state=SAMPLE_STATE)
Comment thread
sam0737 marked this conversation as resolved.
Outdated
assert command.modulation == MODULATION_HZ
assert command.repeat_count == 0
assert command.get_raw_timings() == state_to_timings(SAMPLE_STATE)
Loading