Add NAD Infrared integration (#187250)

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
rrooggiieerr
2026-11-18 00:05:24 -05:00
committed by GitHub
co-authored by Copilot Autofix powered by AI
parent 628ec27619
commit edf0221853
20 changed files with 1791 additions and 10 deletions
+1
View File
@@ -439,6 +439,7 @@ homeassistant.components.my.*
homeassistant.components.my_pv.*
homeassistant.components.mysensors.*
homeassistant.components.myuplink.*
homeassistant.components.nad_infrared.*
homeassistant.components.nam.*
homeassistant.components.namecheapdns.*
homeassistant.components.nasweb.*
Generated
+2
View File
@@ -1299,6 +1299,8 @@ AGENTS.md @home-assistant/core
/tests/components/mystrom/ @fabaff
/homeassistant/components/myuplink/ @pajzo @astrandb
/tests/components/myuplink/ @pajzo @astrandb
/homeassistant/components/nad_infrared/ @rrooggiieerr
/tests/components/nad_infrared/ @rrooggiieerr
/homeassistant/components/nam/ @bieniu
/tests/components/nam/ @bieniu
/homeassistant/components/namecheapdns/ @tr4nt0r
+5
View File
@@ -0,0 +1,5 @@
{
"domain": "nad",
"name": "NAD",
"integrations": ["nad", "nad_infrared"]
}
@@ -0,0 +1,28 @@
"""NAD Infrared integration for Home Assistant."""
from homeassistant.components.infrared import async_get_emitters
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryError
from homeassistant.helpers import entity_registry as er
from .const import CONF_INFRARED_ENTITY_ID, DOMAIN
PLATFORMS = [Platform.MEDIA_PLAYER]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Set up NAD Infrared from a config entry."""
if er.async_get(hass).async_get(
entry.data[CONF_INFRARED_ENTITY_ID]
) is None and entry.data[CONF_INFRARED_ENTITY_ID] not in async_get_emitters(hass):
raise ConfigEntryError(
translation_domain=DOMAIN, translation_key="emitter_not_found"
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Unload a NAD Infrared config entry."""
await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS)
@@ -0,0 +1,86 @@
"""Config flow for NAD Infrared integration."""
from typing import Any, override
import probatio
from homeassistant.components.infrared import (
DOMAIN as INFRARED_DOMAIN,
async_get_emitters,
)
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.helpers.selector import EntitySelector, EntitySelectorConfig
from .const import (
CONF_DEVICE_TYPE,
CONF_INFRARED_ENTITY_ID,
DEVICE_NAMES,
DOMAIN,
NADDeviceType,
)
class NadIrConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle config flow for NAD Infrared."""
VERSION = 1
@override
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle device type selection."""
if not async_get_emitters(self.hass):
return self.async_abort(reason="no_infrared_emitters")
return self.async_show_menu(
step_id="user",
menu_options=[device_type.value for device_type in NADDeviceType],
)
async def async_step_receiver(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle receiver emitter selection."""
return await self._async_step_device(NADDeviceType.RECEIVER, user_input)
async def async_step_amplifier(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle amplifier emitter selection."""
return await self._async_step_device(NADDeviceType.AMPLIFIER, user_input)
async def async_step_cd_player(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle CD player emitter selection."""
return await self._async_step_device(NADDeviceType.CD_PLAYER, user_input)
async def async_step_cassette_deck(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle cassette deck emitter selection."""
return await self._async_step_device(NADDeviceType.CASSETTE_DECK, user_input)
async def _async_step_device(
self, device_type: NADDeviceType, user_input: dict[str, Any] | None
) -> ConfigFlowResult:
"""Select the emitter for a device type and create the entry."""
if user_input is not None:
data = {CONF_DEVICE_TYPE: device_type, **user_input}
self._async_abort_entries_match(data)
return self.async_create_entry(title=DEVICE_NAMES[device_type], data=data)
return self.async_show_form(
step_id=device_type.value,
data_schema=probatio.Schema(
{
probatio.Required(CONF_INFRARED_ENTITY_ID): EntitySelector(
EntitySelectorConfig(
domain=INFRARED_DOMAIN,
include_entities=async_get_emitters(self.hass),
)
),
}
),
)
@@ -0,0 +1,24 @@
"""Constants for the NAD Infrared integration."""
from enum import StrEnum
DOMAIN = "nad_infrared"
CONF_DEVICE_TYPE = "device_type"
CONF_INFRARED_ENTITY_ID = "infrared_entity_id"
class NADDeviceType(StrEnum):
"""NAD device types."""
RECEIVER = "receiver"
AMPLIFIER = "amplifier"
CD_PLAYER = "cd_player"
CASSETTE_DECK = "cassette_deck"
DEVICE_NAMES: dict[NADDeviceType, str] = {
NADDeviceType.RECEIVER: "NAD receiver",
NADDeviceType.AMPLIFIER: "NAD amplifier",
NADDeviceType.CD_PLAYER: "NAD CD player",
NADDeviceType.CASSETTE_DECK: "NAD cassette deck",
}
@@ -0,0 +1,33 @@
"""Common entity for NAD Infrared integration."""
from infrared_protocols.codes.nad.amplifier import NADAmplifierCode
from infrared_protocols.codes.nad.cd import NADCDCode
from infrared_protocols.codes.nad.tape import NADTapeCode
from homeassistant.components.infrared import InfraredEmitterConsumerEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.device_registry import DeviceInfo
from .const import CONF_DEVICE_TYPE, CONF_INFRARED_ENTITY_ID, DEVICE_NAMES, DOMAIN
class NadIrEntity(InfraredEmitterConsumerEntity):
"""NAD Infrared base entity."""
_attr_has_entity_name = True
def __init__(self, entry: ConfigEntry, unique_id_suffix: str) -> None:
"""Initialize NAD Infrared entity."""
self._infrared_emitter_entity_id = entry.data[CONF_INFRARED_ENTITY_ID]
self._attr_unique_id = f"{entry.entry_id}_{unique_id_suffix}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, entry.entry_id)},
name=DEVICE_NAMES[entry.data[CONF_DEVICE_TYPE]],
manufacturer="NAD",
)
async def _send_nad_command(
self, code: NADAmplifierCode | NADCDCode | NADTapeCode
) -> None:
"""Send an IR command to the NAD device."""
await self._send_command(code.to_command())
@@ -0,0 +1,12 @@
{
"domain": "nad_infrared",
"name": "NAD Infrared",
"categories": ["media_entertainment.speakers_audio"],
"codeowners": ["@rrooggiieerr"],
"config_flow": true,
"dependencies": ["infrared"],
"documentation": "https://www.home-assistant.io/integrations/nad_infrared",
"integration_type": "device",
"iot_class": "assumed_state",
"quality_scale": "silver"
}
@@ -0,0 +1,301 @@
"""Media player platform for NAD Infrared integration."""
from dataclasses import dataclass
from typing import Any, override
from infrared_protocols.codes.nad.amplifier import NADAmplifierCode
from infrared_protocols.codes.nad.cd import NADCDCode
from infrared_protocols.codes.nad.tape import NADTapeCode
from homeassistant.components.media_player import (
MediaPlayerDeviceClass,
MediaPlayerEntity,
MediaPlayerEntityFeature,
MediaPlayerState,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.restore_state import ExtraStoredData, RestoreEntity
from .const import CONF_DEVICE_TYPE, DOMAIN, NADDeviceType
from .entity import NadIrEntity
PARALLEL_UPDATES = 1
SOURCE_TO_CODE: dict[str, NADAmplifierCode] = {
"input_1": NADAmplifierCode.INPUT_1,
"input_2": NADAmplifierCode.INPUT_2,
"input_3": NADAmplifierCode.INPUT_3,
"input_4": NADAmplifierCode.INPUT_4,
"input_5": NADAmplifierCode.INPUT_5,
"input_6": NADAmplifierCode.INPUT_6,
"input_7": NADAmplifierCode.INPUT_7,
"front": NADAmplifierCode.FRONT,
"mp": NADAmplifierCode.MP,
"tuner": NADAmplifierCode.TUNER,
}
SOUND_MODE_TO_CODE: dict[str, NADAmplifierCode] = {
"pliix_movie": NADAmplifierCode.PLIIX_MOVIE,
"pliix_music": NADAmplifierCode.PLIIX_MUSIC,
"dolby_surround_ex": NADAmplifierCode.DOLBY_SURROUND_EX,
"neo6_cinema": NADAmplifierCode.NEO6_CINEMA,
"neo6_music": NADAmplifierCode.NEO6_MUSIC,
"matrix_7_1": NADAmplifierCode.MATRIX_7_1,
"ears": NADAmplifierCode.EARS,
"enhanced_stereo": NADAmplifierCode.ENHANCED_STEREO_1,
"stereo_downmix": NADAmplifierCode.STEREO_DOWNMIX,
"direct": NADAmplifierCode.DIRECT,
"bypass": NADAmplifierCode.BYPASS,
}
@dataclass
class _NadAmplifierExtraData(ExtraStoredData):
"""Persisted assumed-state data for a NAD amplifier or receiver.
Stored separately from the entity state because while the device is
OFF, ``MediaPlayerEntity.state_attributes`` strips ``source`` and
``sound_mode``, so a restart in the OFF state would otherwise lose them.
The power state is stored too, because the entity state is saved as
unavailable when the emitter is unavailable at shutdown.
"""
power_state: MediaPlayerState | None
source: str | None
sound_mode: str | None
@override
def as_dict(self) -> dict[str, Any]:
"""Serialize for the restore-state store."""
return {
"power_state": self.power_state,
"source": self.source,
"sound_mode": self.sound_mode,
}
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up NAD Infrared media player from config entry."""
device_type = entry.data[CONF_DEVICE_TYPE]
if device_type in (NADDeviceType.RECEIVER, NADDeviceType.AMPLIFIER):
async_add_entities([NadIrAmplifierMediaPlayer(entry)])
elif device_type == NADDeviceType.CD_PLAYER:
async_add_entities([NadIrCDPlayerMediaPlayer(entry)])
elif device_type == NADDeviceType.CASSETTE_DECK:
async_add_entities([NadIrCassetteDeckMediaPlayer(entry)])
class NadIrAmplifierMediaPlayer(NadIrEntity, MediaPlayerEntity, RestoreEntity):
"""NAD Infrared amplifier or receiver media player entity."""
_attr_name = None
_attr_assumed_state = True
_attr_device_class = MediaPlayerDeviceClass.RECEIVER
_attr_translation_key = "receiver"
_attr_source_list = list(SOURCE_TO_CODE)
_attr_sound_mode_list = list(SOUND_MODE_TO_CODE)
_attr_supported_features = (
MediaPlayerEntityFeature.TURN_ON
| MediaPlayerEntityFeature.TURN_OFF
| MediaPlayerEntityFeature.VOLUME_STEP
| MediaPlayerEntityFeature.VOLUME_MUTE
| MediaPlayerEntityFeature.SELECT_SOURCE
| MediaPlayerEntityFeature.SELECT_SOUND_MODE
)
def __init__(self, entry: ConfigEntry) -> None:
"""Initialize NAD Infrared amplifier media player."""
super().__init__(entry, unique_id_suffix="media_player")
@property
@override
def extra_restore_state_data(self) -> ExtraStoredData:
"""Persist power state, source and sound mode."""
return _NadAmplifierExtraData(
power_state=self._attr_state,
source=self._attr_source,
sound_mode=self._attr_sound_mode,
)
@override
async def async_added_to_hass(self) -> None:
"""Restore last known assumed state, source and sound mode."""
await super().async_added_to_hass()
if (extra := await self.async_get_last_extra_data()) is not None:
data = extra.as_dict()
if (power_state := data.get("power_state")) in (
MediaPlayerState.ON,
MediaPlayerState.OFF,
):
self._attr_state = MediaPlayerState(power_state)
if (source := data.get("source")) in SOURCE_TO_CODE:
self._attr_source = source
if (sound_mode := data.get("sound_mode")) in SOUND_MODE_TO_CODE:
self._attr_sound_mode = sound_mode
@override
async def async_turn_on(self) -> None:
"""Send discrete power-on command."""
await self._send_nad_command(NADAmplifierCode.ON)
self._attr_state = MediaPlayerState.ON
self.async_write_ha_state()
@override
async def async_turn_off(self) -> None:
"""Send discrete power-off command."""
await self._send_nad_command(NADAmplifierCode.OFF)
self._attr_state = MediaPlayerState.OFF
self.async_write_ha_state()
@override
async def async_volume_up(self) -> None:
"""Send volume up command."""
await self._send_nad_command(NADAmplifierCode.VOLUME_UP)
@override
async def async_volume_down(self) -> None:
"""Send volume down command."""
await self._send_nad_command(NADAmplifierCode.VOLUME_DOWN)
@override
async def async_mute_volume(self, mute: bool) -> None:
"""Send mute toggle command.
NAD amplifiers only have a mute toggle, so the mute state is not tracked.
"""
await self._send_nad_command(NADAmplifierCode.MUTE)
@override
async def async_select_source(self, source: str) -> None:
"""Select an input source."""
if (code := SOURCE_TO_CODE.get(source)) is None:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_source",
translation_placeholders={
"invalid_source": source,
"valid_sources": ", ".join(SOURCE_TO_CODE),
},
)
await self._send_nad_command(code)
self._attr_source = source
self.async_write_ha_state()
@override
async def async_select_sound_mode(self, sound_mode: str) -> None:
"""Select a listening mode."""
if (code := SOUND_MODE_TO_CODE.get(sound_mode)) is None:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_sound_mode",
translation_placeholders={
"invalid_sound_mode": sound_mode,
"valid_sound_modes": ", ".join(SOUND_MODE_TO_CODE),
},
)
await self._send_nad_command(code)
self._attr_sound_mode = sound_mode
self.async_write_ha_state()
class NadIrCDPlayerMediaPlayer(NadIrEntity, MediaPlayerEntity):
"""NAD Infrared CD player media player entity.
NAD CD player remotes have no discrete power codes, so only playback is
controlled here.
"""
_attr_name = None
_attr_assumed_state = True
_attr_supported_features = (
MediaPlayerEntityFeature.PLAY
| MediaPlayerEntityFeature.PAUSE
| MediaPlayerEntityFeature.STOP
| MediaPlayerEntityFeature.NEXT_TRACK
| MediaPlayerEntityFeature.PREVIOUS_TRACK
)
def __init__(self, entry: ConfigEntry) -> None:
"""Initialize NAD Infrared CD player media player."""
super().__init__(entry, unique_id_suffix="media_player")
@override
async def async_media_play(self) -> None:
"""Send play command."""
await self._send_nad_command(NADCDCode.PLAY)
self._attr_state = MediaPlayerState.PLAYING
self.async_write_ha_state()
@override
async def async_media_pause(self) -> None:
"""Send pause command."""
await self._send_nad_command(NADCDCode.PAUSE)
self._attr_state = MediaPlayerState.PAUSED
self.async_write_ha_state()
@override
async def async_media_stop(self) -> None:
"""Send stop command."""
await self._send_nad_command(NADCDCode.STOP)
self._attr_state = MediaPlayerState.IDLE
self.async_write_ha_state()
@override
async def async_media_next_track(self) -> None:
"""Send skip forward command."""
await self._send_nad_command(NADCDCode.SKIP_FORWARD)
@override
async def async_media_previous_track(self) -> None:
"""Send skip back command."""
await self._send_nad_command(NADCDCode.SKIP_BACK)
class NadIrCassetteDeckMediaPlayer(NadIrEntity, MediaPlayerEntity):
"""NAD Infrared cassette deck media player entity.
Controls deck B, which is also the deck single-cassette decks respond to.
Fast forward, rewind, reverse play and recording have no media player
equivalent.
"""
_attr_name = None
_attr_assumed_state = True
_attr_supported_features = (
MediaPlayerEntityFeature.PLAY
| MediaPlayerEntityFeature.PAUSE
| MediaPlayerEntityFeature.STOP
)
def __init__(self, entry: ConfigEntry) -> None:
"""Initialize NAD Infrared cassette deck media player."""
super().__init__(entry, unique_id_suffix="media_player")
@override
async def async_media_play(self) -> None:
"""Send play command."""
await self._send_nad_command(NADTapeCode.DECK_B_PLAY)
self._attr_state = MediaPlayerState.PLAYING
self.async_write_ha_state()
@override
async def async_media_pause(self) -> None:
"""Send pause command."""
await self._send_nad_command(NADTapeCode.DECK_B_PAUSE)
self._attr_state = MediaPlayerState.PAUSED
self.async_write_ha_state()
@override
async def async_media_stop(self) -> None:
"""Send stop command."""
await self._send_nad_command(NADTapeCode.DECK_B_STOP)
self._attr_state = MediaPlayerState.IDLE
self.async_write_ha_state()
@@ -0,0 +1,114 @@
rules:
# Bronze
action-setup:
status: exempt
comment: |
This integration does not provide additional actions.
appropriate-polling:
status: exempt
comment: |
This integration does not poll.
brands: done
common-modules: done
config-flow-test-coverage: done
config-flow: done
dependency-transparency: done
docs-actions:
status: exempt
comment: |
This integration does not provide additional actions.
docs-conditions:
status: exempt
comment: This integration does not have any conditions.
docs-high-level-description: done
docs-installation-instructions: done
docs-removal-instructions: done
docs-triggers:
status: exempt
comment: This integration does not have any triggers.
entity-event-setup: done
entity-unique-id: done
has-entity-name: done
runtime-data:
status: exempt
comment: |
This integration does not keep runtime data.
test-before-configure:
status: exempt
comment: |
This integration only proxies commands through an existing infrared
entity, so there is no connection to test in the config flow.
test-before-setup: done
unique-config-entry: done
# Silver
action-exceptions: done
config-entry-unloading: done
docs-configuration-parameters:
status: exempt
comment: |
This integration does not have an options flow.
docs-installation-parameters: done
entity-unavailable: done
integration-owner: done
log-when-unavailable: done
parallel-updates: done
reauthentication-flow:
status: exempt
comment: |
This integration does not require authentication.
test-coverage: done
# Gold
devices: done
diagnostics: todo
discovery-update-info:
status: exempt
comment: |
This integration does not support discovery.
discovery:
status: exempt
comment: |
This integration is configured manually via config flow.
docs-data-update:
status: exempt
comment: |
This integration does not fetch data from devices.
docs-examples: done
docs-known-limitations: done
docs-supported-devices: done
docs-supported-functions: done
docs-troubleshooting: done
docs-use-cases: done
dynamic-devices:
status: exempt
comment: |
Each config entry creates a single device.
entity-category: done
entity-device-class: done
entity-disabled-by-default:
status: exempt
comment: |
No entities should be disabled by default.
entity-translations: done
exception-translations: done
icon-translations:
status: exempt
comment: |
This integration does not use custom icons.
reconfiguration-flow: todo
repair-issues: todo
stale-devices:
status: exempt
comment: |
Each config entry manages exactly one device.
# Platinum
async-dependency:
status: exempt
comment: |
This integration has no external dependencies.
inject-websession:
status: exempt
comment: |
This integration does not make HTTP requests.
strict-typing: done
@@ -0,0 +1,108 @@
{
"config": {
"abort": {
"already_configured": "This NAD device has already been configured with this infrared emitter.",
"no_infrared_emitters": "[%key:common::config_flow::abort::no_infrared_emitters%]"
},
"step": {
"amplifier": {
"data": {
"infrared_entity_id": "[%key:common::config_flow::data::infrared_entity_id%]"
},
"data_description": {
"infrared_entity_id": "[%key:common::config_flow::data_description::infrared_entity_id%]"
},
"description": "Select the infrared emitter to use for controlling your NAD amplifier. The amplifier must be set to IR channel 0.",
"title": "Set up NAD amplifier"
},
"cassette_deck": {
"data": {
"infrared_entity_id": "[%key:common::config_flow::data::infrared_entity_id%]"
},
"data_description": {
"infrared_entity_id": "[%key:common::config_flow::data_description::infrared_entity_id%]"
},
"description": "Select the infrared emitter to use for controlling your NAD cassette deck.",
"title": "Set up NAD cassette deck"
},
"cd_player": {
"data": {
"infrared_entity_id": "[%key:common::config_flow::data::infrared_entity_id%]"
},
"data_description": {
"infrared_entity_id": "[%key:common::config_flow::data_description::infrared_entity_id%]"
},
"description": "Select the infrared emitter to use for controlling your NAD CD player.",
"title": "Set up NAD CD player"
},
"receiver": {
"data": {
"infrared_entity_id": "[%key:common::config_flow::data::infrared_entity_id%]"
},
"data_description": {
"infrared_entity_id": "[%key:common::config_flow::data_description::infrared_entity_id%]"
},
"description": "Select the infrared emitter to use for controlling your NAD receiver. The receiver must be set to IR channel 0.",
"title": "Set up NAD receiver"
},
"user": {
"description": "Select the type of NAD device to set up.",
"menu_options": {
"amplifier": "Amplifier",
"cassette_deck": "Cassette deck",
"cd_player": "CD player",
"receiver": "Receiver (amplifier with tuner)"
},
"title": "Set up NAD IR Remote"
}
}
},
"entity": {
"media_player": {
"receiver": {
"state_attributes": {
"sound_mode": {
"state": {
"bypass": "Bypass",
"direct": "Direct",
"dolby_surround_ex": "Dolby Surround EX",
"ears": "EARS",
"enhanced_stereo": "Enhanced stereo",
"matrix_7_1": "Matrix 7.1",
"neo6_cinema": "DTS Neo:6 Cinema",
"neo6_music": "DTS Neo:6 Music",
"pliix_movie": "Dolby Pro Logic IIx Movie",
"pliix_music": "Dolby Pro Logic IIx Music",
"stereo_downmix": "Stereo downmix"
}
},
"source": {
"state": {
"front": "Front",
"input_1": "Input 1",
"input_2": "Input 2",
"input_3": "Input 3",
"input_4": "Input 4",
"input_5": "Input 5",
"input_6": "Input 6",
"input_7": "Input 7",
"mp": "MP",
"tuner": "Tuner"
}
}
}
}
}
},
"exceptions": {
"emitter_not_found": {
"message": "The infrared emitter used by this NAD device no longer exists. Remove this device and set it up again with another emitter."
},
"invalid_sound_mode": {
"message": "Cannot select sound mode {invalid_sound_mode}. Valid sound modes: {valid_sound_modes}."
},
"invalid_source": {
"message": "Cannot select input source {invalid_source}. Valid sources: {valid_sources}."
}
}
}
+1
View File
@@ -549,6 +549,7 @@ FLOWS = {
"mysensors",
"mystrom",
"myuplink",
"nad_infrared",
"nam",
"namecheapdns",
"nanoleaf",
+24 -10
View File
@@ -9736,16 +9736,30 @@
},
"nad": {
"name": "NAD",
"integration_type": "hub",
"categories": [
"media_entertainment.speakers_audio"
],
"connectivity": [
"network",
"serial"
],
"config_flow": false,
"iot_class": "local_polling"
"integrations": {
"nad": {
"integration_type": "hub",
"config_flow": false,
"iot_class": "local_polling",
"categories": [
"media_entertainment.speakers_audio"
],
"connectivity": [
"network",
"serial"
],
"name": "NAD"
},
"nad_infrared": {
"integration_type": "device",
"config_flow": true,
"iot_class": "assumed_state",
"categories": [
"media_entertainment.speakers_audio"
],
"name": "NAD Infrared"
}
}
},
"nam": {
"name": "Nettigo Air Monitor",
Generated
+10
View File
@@ -4144,6 +4144,16 @@ disallow_untyped_defs = true
warn_return_any = true
warn_unreachable = true
[mypy-homeassistant.components.nad_infrared.*]
check_untyped_defs = true
disallow_incomplete_defs = true
disallow_subclassing_any = true
disallow_untyped_calls = true
disallow_untyped_decorators = true
disallow_untyped_defs = true
warn_return_any = true
warn_unreachable = true
[mypy-homeassistant.components.nam.*]
check_untyped_defs = true
disallow_incomplete_defs = true
@@ -0,0 +1 @@
"""Tests for the NAD Infrared integration."""
+92
View File
@@ -0,0 +1,92 @@
"""Common fixtures for the NAD Infrared tests."""
from collections.abc import Generator
from unittest.mock import MagicMock, patch
from infrared_protocols.codes.nad.amplifier import NADAmplifierCode
from infrared_protocols.codes.nad.cd import NADCDCode
from infrared_protocols.codes.nad.tape import NADTapeCode
import pytest
from pytest_homeassistant.common import MockConfigEntry
from pytest_homeassistant.components.infrared import (
EMITTER_ENTITY_ID as MOCK_INFRARED_EMITTER_ENTITY_ID,
)
from pytest_homeassistant.components.infrared.common import MockInfraredEmitterEntity
from homeassistant.components.nad_infrared import PLATFORMS
from homeassistant.components.nad_infrared.const import (
CONF_DEVICE_TYPE,
CONF_INFRARED_ENTITY_ID,
DEVICE_NAMES,
DOMAIN,
NADDeviceType,
)
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
@pytest.fixture
def device_type(request: pytest.FixtureRequest) -> NADDeviceType:
"""Return the NAD device type to use for the config entry.
Override with ``@pytest.mark.parametrize("device_type", [...], indirect=True)``.
"""
return getattr(request, "param", NADDeviceType.RECEIVER)
@pytest.fixture
def mock_config_entry(device_type: NADDeviceType) -> MockConfigEntry:
"""Return a mock config entry."""
return MockConfigEntry(
domain=DOMAIN,
entry_id="01JTEST0000000000000000000",
title=DEVICE_NAMES[device_type],
data={
CONF_DEVICE_TYPE: device_type,
CONF_INFRARED_ENTITY_ID: MOCK_INFRARED_EMITTER_ENTITY_ID,
},
)
@pytest.fixture
def platforms() -> list[Platform]:
"""Return platforms to set up."""
return PLATFORMS
@pytest.fixture
def mock_nad_to_command() -> Generator[MagicMock]:
"""Patch ``to_command`` on the NAD code enums to return the code itself.
This lets tests assert on the code enum value rather than on raw timings.
"""
with (
patch.object(
NADAmplifierCode, "to_command", autospec=True, side_effect=lambda self: self
) as mock,
patch.object(
NADCDCode, "to_command", autospec=True, side_effect=lambda self: self
),
patch.object(
NADTapeCode, "to_command", autospec=True, side_effect=lambda self: self
),
):
yield mock
@pytest.fixture
async def init_integration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
mock_nad_to_command: MagicMock,
platforms: list[Platform],
) -> MockConfigEntry:
"""Set up the NAD Infrared integration for testing."""
mock_config_entry.add_to_hass(hass)
with patch("homeassistant.components.nad_infrared.PLATFORMS", platforms):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
return mock_config_entry
@@ -0,0 +1,315 @@
# serializer version: 1
# name: test_entities[amplifier][media_player.nad_amplifier-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
<MediaPlayerEntityCapabilityAttribute.SOUND_MODE_LIST: 'sound_mode_list'>: list([
'pliix_movie',
'pliix_music',
'dolby_surround_ex',
'neo6_cinema',
'neo6_music',
'matrix_7_1',
'ears',
'enhanced_stereo',
'stereo_downmix',
'direct',
'bypass',
]),
<MediaPlayerEntityCapabilityAttribute.INPUT_SOURCE_LIST: 'source_list'>: list([
'input_1',
'input_2',
'input_3',
'input_4',
'input_5',
'input_6',
'input_7',
'front',
'mp',
'tuner',
]),
}),
'config_entry_id': <ANY>,
'config_subentry_id': None,
'device_class': None,
'device_id': <DeviceEntry identifiers=[('nad_infrared', '01JTEST0000000000000000000')]>,
'disabled_by': None,
'domain': 'media_player',
'entity_category': None,
'entity_id': 'media_player.nad_amplifier',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': None,
'options': dict({
}),
'original_device_class': <MediaPlayerDeviceClass.RECEIVER: 'receiver'>,
'original_icon': None,
'original_name': None,
'platform': 'nad_infrared',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': <MediaPlayerEntityFeature: 69000>,
'translation_key': 'receiver',
'unique_id': '01JTEST0000000000000000000_media_player',
'unit_of_measurement': None,
})
# ---
# name: test_entities[amplifier][media_player.nad_amplifier-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.ASSUMED_STATE: 'assumed_state'>: True,
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'receiver',
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'NAD amplifier',
<MediaPlayerEntityCapabilityAttribute.SOUND_MODE_LIST: 'sound_mode_list'>: list([
'pliix_movie',
'pliix_music',
'dolby_surround_ex',
'neo6_cinema',
'neo6_music',
'matrix_7_1',
'ears',
'enhanced_stereo',
'stereo_downmix',
'direct',
'bypass',
]),
<MediaPlayerEntityCapabilityAttribute.INPUT_SOURCE_LIST: 'source_list'>: list([
'input_1',
'input_2',
'input_3',
'input_4',
'input_5',
'input_6',
'input_7',
'front',
'mp',
'tuner',
]),
<EntityStateAttribute.SUPPORTED_FEATURES: 'supported_features'>: <MediaPlayerEntityFeature: 69000>,
}),
'context': <ANY>,
'entity_id': 'media_player.nad_amplifier',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_entities[cassette_deck][media_player.nad_cassette_deck-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
}),
'config_entry_id': <ANY>,
'config_subentry_id': None,
'device_class': None,
'device_id': <DeviceEntry identifiers=[('nad_infrared', '01JTEST0000000000000000000')]>,
'disabled_by': None,
'domain': 'media_player',
'entity_category': None,
'entity_id': 'media_player.nad_cassette_deck',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': None,
'platform': 'nad_infrared',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': <MediaPlayerEntityFeature: 20481>,
'translation_key': None,
'unique_id': '01JTEST0000000000000000000_media_player',
'unit_of_measurement': None,
})
# ---
# name: test_entities[cassette_deck][media_player.nad_cassette_deck-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.ASSUMED_STATE: 'assumed_state'>: True,
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'NAD cassette deck',
<EntityStateAttribute.SUPPORTED_FEATURES: 'supported_features'>: <MediaPlayerEntityFeature: 20481>,
}),
'context': <ANY>,
'entity_id': 'media_player.nad_cassette_deck',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_entities[cd_player][media_player.nad_cd_player-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
}),
'config_entry_id': <ANY>,
'config_subentry_id': None,
'device_class': None,
'device_id': <DeviceEntry identifiers=[('nad_infrared', '01JTEST0000000000000000000')]>,
'disabled_by': None,
'domain': 'media_player',
'entity_category': None,
'entity_id': 'media_player.nad_cd_player',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': None,
'platform': 'nad_infrared',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': <MediaPlayerEntityFeature: 20529>,
'translation_key': None,
'unique_id': '01JTEST0000000000000000000_media_player',
'unit_of_measurement': None,
})
# ---
# name: test_entities[cd_player][media_player.nad_cd_player-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.ASSUMED_STATE: 'assumed_state'>: True,
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'NAD CD player',
<EntityStateAttribute.SUPPORTED_FEATURES: 'supported_features'>: <MediaPlayerEntityFeature: 20529>,
}),
'context': <ANY>,
'entity_id': 'media_player.nad_cd_player',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_entities[receiver][media_player.nad_receiver-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
<MediaPlayerEntityCapabilityAttribute.SOUND_MODE_LIST: 'sound_mode_list'>: list([
'pliix_movie',
'pliix_music',
'dolby_surround_ex',
'neo6_cinema',
'neo6_music',
'matrix_7_1',
'ears',
'enhanced_stereo',
'stereo_downmix',
'direct',
'bypass',
]),
<MediaPlayerEntityCapabilityAttribute.INPUT_SOURCE_LIST: 'source_list'>: list([
'input_1',
'input_2',
'input_3',
'input_4',
'input_5',
'input_6',
'input_7',
'front',
'mp',
'tuner',
]),
}),
'config_entry_id': <ANY>,
'config_subentry_id': None,
'device_class': None,
'device_id': <DeviceEntry identifiers=[('nad_infrared', '01JTEST0000000000000000000')]>,
'disabled_by': None,
'domain': 'media_player',
'entity_category': None,
'entity_id': 'media_player.nad_receiver',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': None,
'options': dict({
}),
'original_device_class': <MediaPlayerDeviceClass.RECEIVER: 'receiver'>,
'original_icon': None,
'original_name': None,
'platform': 'nad_infrared',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': <MediaPlayerEntityFeature: 69000>,
'translation_key': 'receiver',
'unique_id': '01JTEST0000000000000000000_media_player',
'unit_of_measurement': None,
})
# ---
# name: test_entities[receiver][media_player.nad_receiver-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.ASSUMED_STATE: 'assumed_state'>: True,
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'receiver',
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'NAD receiver',
<MediaPlayerEntityCapabilityAttribute.SOUND_MODE_LIST: 'sound_mode_list'>: list([
'pliix_movie',
'pliix_music',
'dolby_surround_ex',
'neo6_cinema',
'neo6_music',
'matrix_7_1',
'ears',
'enhanced_stereo',
'stereo_downmix',
'direct',
'bypass',
]),
<MediaPlayerEntityCapabilityAttribute.INPUT_SOURCE_LIST: 'source_list'>: list([
'input_1',
'input_2',
'input_3',
'input_4',
'input_5',
'input_6',
'input_7',
'front',
'mp',
'tuner',
]),
<EntityStateAttribute.SUPPORTED_FEATURES: 'supported_features'>: <MediaPlayerEntityFeature: 69000>,
}),
'context': <ANY>,
'entity_id': 'media_player.nad_receiver',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
@@ -0,0 +1,121 @@
"""Tests for the NAD Infrared config flow."""
import pytest
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.components.nad_infrared.const import (
CONF_DEVICE_TYPE,
CONF_INFRARED_ENTITY_ID,
DOMAIN,
NADDeviceType,
)
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import MOCK_INFRARED_EMITTER_ENTITY_ID
@pytest.mark.usefixtures("mock_infrared_emitter_entity")
@pytest.mark.parametrize(
("device_type", "expected_title"),
[
(NADDeviceType.RECEIVER, "NAD receiver"),
(NADDeviceType.AMPLIFIER, "NAD amplifier"),
(NADDeviceType.CD_PLAYER, "NAD CD player"),
(NADDeviceType.CASSETTE_DECK, "NAD cassette deck"),
],
)
async def test_user_flow_success(
hass: HomeAssistant,
device_type: NADDeviceType,
expected_title: str,
) -> None:
"""Test successful user config flow for each device type."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "user"
assert result["menu_options"] == [
"receiver",
"amplifier",
"cd_player",
"cassette_deck",
]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": device_type.value}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == device_type.value
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_INFRARED_ENTITY_ID: MOCK_INFRARED_EMITTER_ENTITY_ID},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == expected_title
assert result["data"] == {
CONF_DEVICE_TYPE: device_type,
CONF_INFRARED_ENTITY_ID: MOCK_INFRARED_EMITTER_ENTITY_ID,
}
assert result["result"].unique_id is None
@pytest.mark.usefixtures("mock_infrared_emitter_entity")
async def test_user_flow_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test user flow aborts when the device type already uses the emitter."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": NADDeviceType.RECEIVER.value}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_INFRARED_ENTITY_ID: MOCK_INFRARED_EMITTER_ENTITY_ID},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("mock_infrared_emitter_entity")
async def test_user_flow_other_device_type_same_emitter(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test another device type can share an emitter that is already in use."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": NADDeviceType.AMPLIFIER.value}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_INFRARED_ENTITY_ID: MOCK_INFRARED_EMITTER_ENTITY_ID},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["result"].unique_id is None
@pytest.mark.usefixtures("init_infrared")
async def test_user_flow_no_emitters(hass: HomeAssistant) -> None:
"""Test user flow aborts when no infrared emitters exist."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_infrared_emitters"
@@ -0,0 +1,40 @@
"""Tests for the NAD Infrared integration setup."""
import pytest
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .conftest import MOCK_INFRARED_EMITTER_ENTITY_ID
async def test_setup_and_unload_entry(
hass: HomeAssistant, init_integration: MockConfigEntry
) -> None:
"""Test setting up and unloading a config entry."""
entry = init_integration
assert entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.usefixtures("mock_infrared_emitter_entity")
async def test_emitter_removed(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Setup fails with a clear error when the emitter no longer exists."""
entity_registry.async_remove(MOCK_INFRARED_EMITTER_ENTITY_ID)
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
assert mock_config_entry.error_reason_translation_key == "emitter_not_found"
@@ -0,0 +1,473 @@
"""Tests for the NAD Infrared media player platform."""
from infrared_protocols.codes.nad.amplifier import NADAmplifierCode
from infrared_protocols.codes.nad.cd import NADCDCode
from infrared_protocols.codes.nad.tape import NADTapeCode
from infrared_protocols.commands.nec import NECCommand
import pytest
from pytest_homeassistant.common import (
MockConfigEntry,
mock_restore_cache_with_extra_data,
snapshot_platform,
)
from pytest_homeassistant.components.common import (
assert_availability_follows_source_entity,
)
from pytest_homeassistant.components.infrared.common import MockInfraredEmitterEntity
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.media_player import (
ATTR_INPUT_SOURCE,
ATTR_INPUT_SOURCE_LIST,
ATTR_SOUND_MODE,
ATTR_SOUND_MODE_LIST,
DOMAIN as MEDIA_PLAYER_DOMAIN,
SERVICE_MEDIA_NEXT_TRACK,
SERVICE_MEDIA_PAUSE,
SERVICE_MEDIA_PLAY,
SERVICE_MEDIA_PREVIOUS_TRACK,
SERVICE_MEDIA_STOP,
SERVICE_SELECT_SOUND_MODE,
SERVICE_SELECT_SOURCE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
SERVICE_VOLUME_DOWN,
SERVICE_VOLUME_MUTE,
SERVICE_VOLUME_UP,
MediaPlayerState,
)
from homeassistant.components.nad_infrared.const import NADDeviceType
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant, State
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from .conftest import MOCK_INFRARED_EMITTER_ENTITY_ID
MEDIA_PLAYER_ENTITY_ID = "media_player.nad_receiver"
CD_PLAYER_ENTITY_ID = "media_player.nad_cd_player"
CASSETTE_DECK_ENTITY_ID = "media_player.nad_cassette_deck"
@pytest.fixture
def platforms() -> list[Platform]:
"""Return platforms to set up."""
return [Platform.MEDIA_PLAYER]
@pytest.mark.parametrize(
"device_type",
list(NADDeviceType),
indirect=True,
)
@pytest.mark.usefixtures("init_integration")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the media player entity is created with correct attributes."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("service", "service_data", "expected_code"),
[
(SERVICE_TURN_ON, {}, NADAmplifierCode.ON),
(SERVICE_TURN_OFF, {}, NADAmplifierCode.OFF),
(SERVICE_VOLUME_UP, {}, NADAmplifierCode.VOLUME_UP),
(SERVICE_VOLUME_DOWN, {}, NADAmplifierCode.VOLUME_DOWN),
(SERVICE_VOLUME_MUTE, {"is_volume_muted": True}, NADAmplifierCode.MUTE),
(SERVICE_VOLUME_MUTE, {"is_volume_muted": False}, NADAmplifierCode.MUTE),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_media_player_action_sends_correct_code(
hass: HomeAssistant,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
service: str,
service_data: dict[str, bool],
expected_code: NADAmplifierCode,
) -> None:
"""Test each media player action sends the correct IR code."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
service,
{ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID, **service_data},
blocking=True,
)
assert mock_infrared_emitter_entity.send_command_calls == [expected_code]
@pytest.mark.parametrize(
("source", "expected_code"),
[
("input_1", NADAmplifierCode.INPUT_1),
("input_4", NADAmplifierCode.INPUT_4),
("input_7", NADAmplifierCode.INPUT_7),
("front", NADAmplifierCode.FRONT),
("mp", NADAmplifierCode.MP),
("tuner", NADAmplifierCode.TUNER),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_media_player_select_source(
hass: HomeAssistant,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
source: str,
expected_code: NADAmplifierCode,
) -> None:
"""Test selecting a source sends the correct IR code and updates state."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_SELECT_SOURCE,
{ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID, ATTR_INPUT_SOURCE: source},
blocking=True,
)
assert mock_infrared_emitter_entity.send_command_calls == [expected_code]
state = hass.states.get(MEDIA_PLAYER_ENTITY_ID)
assert state is not None
assert state.attributes[ATTR_INPUT_SOURCE] == source
assert state.attributes[ATTR_INPUT_SOURCE_LIST] == [
"input_1",
"input_2",
"input_3",
"input_4",
"input_5",
"input_6",
"input_7",
"front",
"mp",
"tuner",
]
@pytest.mark.usefixtures("init_integration")
async def test_turn_on_off_update_assumed_state(
hass: HomeAssistant,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
) -> None:
"""Turn-off and turn-on update the assumed state."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID},
blocking=True,
)
state = hass.states.get(MEDIA_PLAYER_ENTITY_ID)
assert state is not None
assert state.state == MediaPlayerState.OFF
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID},
blocking=True,
)
state = hass.states.get(MEDIA_PLAYER_ENTITY_ID)
assert state is not None
assert state.state == MediaPlayerState.ON
assert mock_infrared_emitter_entity.send_command_calls == [
NADAmplifierCode.OFF,
NADAmplifierCode.ON,
]
@pytest.mark.usefixtures("init_integration")
async def test_media_player_availability_follows_ir_entity(
hass: HomeAssistant,
) -> None:
"""Test media player becomes unavailable when IR entity is unavailable."""
await assert_availability_follows_source_entity(
hass, MEDIA_PLAYER_ENTITY_ID, [MOCK_INFRARED_EMITTER_ENTITY_ID]
)
@pytest.mark.parametrize(
"restored_state",
[MediaPlayerState.ON, MediaPlayerState.OFF],
)
@pytest.mark.usefixtures("mock_infrared_emitter_entity", "mock_nad_to_command")
async def test_restores_state_source_and_sound_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
restored_state: MediaPlayerState,
) -> None:
"""State, source and sound mode survive a restart, even when OFF."""
mock_restore_cache_with_extra_data(
hass,
[
(
State(MEDIA_PLAYER_ENTITY_ID, restored_state),
{
"power_state": restored_state,
"source": "input_3",
"sound_mode": "neo6_cinema",
},
)
],
)
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(MEDIA_PLAYER_ENTITY_ID)
assert state is not None
assert state.state == restored_state
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID},
blocking=True,
)
state = hass.states.get(MEDIA_PLAYER_ENTITY_ID)
assert state is not None
assert state.attributes[ATTR_INPUT_SOURCE] == "input_3"
assert state.attributes[ATTR_SOUND_MODE] == "neo6_cinema"
@pytest.mark.usefixtures("init_integration")
async def test_initial_state_unknown_when_no_restore(hass: HomeAssistant) -> None:
"""With no previous state to restore, the entity reports unknown."""
state = hass.states.get(MEDIA_PLAYER_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNKNOWN
assert state.attributes.get(ATTR_INPUT_SOURCE) is None
@pytest.mark.parametrize("device_type", [NADDeviceType.AMPLIFIER], indirect=True)
@pytest.mark.usefixtures("init_integration")
async def test_amplifier_media_player_sends_correct_code(
hass: HomeAssistant,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
) -> None:
"""The amplifier media player sends the same codes as the receiver."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "media_player.nad_amplifier"},
blocking=True,
)
assert mock_infrared_emitter_entity.send_command_calls == [NADAmplifierCode.ON]
@pytest.mark.usefixtures("init_integration")
async def test_select_invalid_source(
hass: HomeAssistant,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
) -> None:
"""Selecting an unknown source raises a validation error and sends nothing."""
with pytest.raises(ServiceValidationError) as exc_info:
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_SELECT_SOURCE,
{ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID, ATTR_INPUT_SOURCE: "input_8"},
blocking=True,
)
assert exc_info.value.translation_key == "invalid_source"
assert exc_info.value.translation_placeholders == {
"invalid_source": "input_8",
"valid_sources": (
"input_1, input_2, input_3, input_4, input_5, input_6, input_7, "
"front, mp, tuner"
),
}
assert mock_infrared_emitter_entity.send_command_calls == []
@pytest.mark.parametrize(
("sound_mode", "expected_code"),
[
("pliix_movie", NADAmplifierCode.PLIIX_MOVIE),
("pliix_music", NADAmplifierCode.PLIIX_MUSIC),
("dolby_surround_ex", NADAmplifierCode.DOLBY_SURROUND_EX),
("neo6_cinema", NADAmplifierCode.NEO6_CINEMA),
("neo6_music", NADAmplifierCode.NEO6_MUSIC),
("ears", NADAmplifierCode.EARS),
("enhanced_stereo", NADAmplifierCode.ENHANCED_STEREO_1),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_select_sound_mode(
hass: HomeAssistant,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
sound_mode: str,
expected_code: NADAmplifierCode,
) -> None:
"""Selecting a sound mode sends its code and updates the assumed state."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_SELECT_SOUND_MODE,
{ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID, ATTR_SOUND_MODE: sound_mode},
blocking=True,
)
assert mock_infrared_emitter_entity.send_command_calls == [expected_code]
state = hass.states.get(MEDIA_PLAYER_ENTITY_ID)
assert state is not None
assert state.attributes[ATTR_SOUND_MODE] == sound_mode
assert state.attributes[ATTR_SOUND_MODE_LIST] == [
"pliix_movie",
"pliix_music",
"dolby_surround_ex",
"neo6_cinema",
"neo6_music",
"matrix_7_1",
"ears",
"enhanced_stereo",
"stereo_downmix",
"direct",
"bypass",
]
@pytest.mark.usefixtures("init_integration")
async def test_select_invalid_sound_mode(
hass: HomeAssistant,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
) -> None:
"""Selecting an unknown sound mode raises a validation error and sends nothing."""
with pytest.raises(ServiceValidationError) as exc_info:
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_SELECT_SOUND_MODE,
{ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID, ATTR_SOUND_MODE: "dolby_atmos"},
blocking=True,
)
assert exc_info.value.translation_key == "invalid_sound_mode"
assert exc_info.value.translation_placeholders["invalid_sound_mode"] == (
"dolby_atmos"
)
assert mock_infrared_emitter_entity.send_command_calls == []
@pytest.mark.usefixtures("mock_infrared_emitter_entity", "mock_nad_to_command")
async def test_restores_power_state_after_emitter_outage(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""The power state survives a restart while the emitter was unavailable."""
mock_restore_cache_with_extra_data(
hass,
[
(
State(MEDIA_PLAYER_ENTITY_ID, STATE_UNAVAILABLE),
{
"power_state": MediaPlayerState.ON,
"source": None,
"sound_mode": None,
},
)
],
)
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(MEDIA_PLAYER_ENTITY_ID)
assert state is not None
assert state.state == MediaPlayerState.ON
async def test_turn_on_sends_nad_nec_frame(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
) -> None:
"""Turning on sends a real NEC frame on NAD's 877C address.
The expected frame is built explicitly, so a wrong address or byte order in
the codes is caught as well.
"""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID},
blocking=True,
)
assert len(mock_infrared_emitter_entity.send_command_calls) == 1
timings = mock_infrared_emitter_entity.send_command_calls[0].get_raw_timings()
assert timings == NECCommand(address=0x7C87, command=0x25).get_raw_timings()
@pytest.mark.parametrize(
("service", "expected_code", "expected_state"),
[
(SERVICE_MEDIA_PLAY, NADCDCode.PLAY, MediaPlayerState.PLAYING),
(SERVICE_MEDIA_PAUSE, NADCDCode.PAUSE, MediaPlayerState.PAUSED),
(SERVICE_MEDIA_STOP, NADCDCode.STOP, MediaPlayerState.IDLE),
(SERVICE_MEDIA_NEXT_TRACK, NADCDCode.SKIP_FORWARD, STATE_UNKNOWN),
(SERVICE_MEDIA_PREVIOUS_TRACK, NADCDCode.SKIP_BACK, STATE_UNKNOWN),
],
)
@pytest.mark.parametrize("device_type", [NADDeviceType.CD_PLAYER], indirect=True)
@pytest.mark.usefixtures("init_integration")
async def test_cd_player_action_sends_correct_code(
hass: HomeAssistant,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
service: str,
expected_code: NADCDCode,
expected_state: str,
) -> None:
"""Test each CD player action sends the correct IR code and sets the state."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
service,
{ATTR_ENTITY_ID: CD_PLAYER_ENTITY_ID},
blocking=True,
)
assert mock_infrared_emitter_entity.send_command_calls == [expected_code]
state = hass.states.get(CD_PLAYER_ENTITY_ID)
assert state is not None
assert state.state == expected_state
@pytest.mark.parametrize(
("service", "expected_code", "expected_state"),
[
(SERVICE_MEDIA_PLAY, NADTapeCode.DECK_B_PLAY, MediaPlayerState.PLAYING),
(SERVICE_MEDIA_PAUSE, NADTapeCode.DECK_B_PAUSE, MediaPlayerState.PAUSED),
(SERVICE_MEDIA_STOP, NADTapeCode.DECK_B_STOP, MediaPlayerState.IDLE),
],
)
@pytest.mark.parametrize("device_type", [NADDeviceType.CASSETTE_DECK], indirect=True)
@pytest.mark.usefixtures("init_integration")
async def test_cassette_deck_action_sends_correct_code(
hass: HomeAssistant,
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
service: str,
expected_code: NADTapeCode,
expected_state: str,
) -> None:
"""Test each cassette deck action sends the correct IR code and sets the state."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
service,
{ATTR_ENTITY_ID: CASSETTE_DECK_ENTITY_ID},
blocking=True,
)
assert mock_infrared_emitter_entity.send_command_calls == [expected_code]
state = hass.states.get(CASSETTE_DECK_ENTITY_ID)
assert state is not None
assert state.state == expected_state