Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dependencies import error after 0.88 #1

Open
advokatb opened this issue Feb 21, 2019 · 19 comments
Open

Dependencies import error after 0.88 #1

advokatb opened this issue Feb 21, 2019 · 19 comments

Comments

@advokatb
Copy link

advokatb commented Feb 21, 2019

Hi.
Can you please update component to make compatiable to the latest HA version.

2019-02-21 10:49:44 ERROR (MainThread) [homeassistant.loader] Error loading custom_components.media_player.xiaomi_miio_gateway. Make sure all dependencies are installed
Traceback (most recent call last):
  File "d:\program\python\python36\lib\site-packages\homeassistant\loader.py", line 147, in _load_file
    module = importlib.import_module(path)
  File "d:\program\python\python36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "d:\User\.homeassistant\custom_components\media_player\xiaomi_miio_gateway.py", line 11, in <module>
    from homeassistant.components.media_player import (
ImportError: cannot import name 'SUPPORT_TURN_ON'

Maybe related to https://developers.home-assistant.io/blog/2019/02/19/the-great-migration.html

And, please, add support for https://github.com/custom-components/custom_updater
Thanks!

@acidquest
Copy link

i have this error too after update HA

@h4v1nfun
Copy link
Owner

thanks for the heads up this weekend i'll look at it and try to update

@mon3y78
Copy link

mon3y78 commented Feb 25, 2019

news?

@LeidenSpain
Copy link

LeidenSpain commented Feb 27, 2019

thanks for the heads up this weekend i'll look at it and try to update

thanks.
I have the same error:

Platform not found: media_player.gateway

Error loading custom_components.gateway.media_player. Make sure all dependencies are installed
Traceback (most recent call last):
  File "/srv/homeassistant/lib/python3.6/site-packages/homeassistant/loader.py", line 147, in _load_file
    module = importlib.import_module(path)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/homeassistant/.homeassistant/custom_components/gateway/media_player.py", line 12, in <module>
    from homeassistant.components.media_player import (
ImportError: cannot import name 'SUPPORT_TURN_ON'

@LeidenSpain
Copy link

LeidenSpain commented Feb 27, 2019

Hi,

I have modified the code to the new dependencies, and it seems that it works

@advokatb
Copy link
Author

advokatb commented Feb 28, 2019

Hi,

I have modified the code to the new dependencies, and it seems that it works

Hi. Please create a gist for it. Can't copy code because all formating breaks down.

@LeidenSpain
Copy link

LeidenSpain commented Feb 28, 2019

Hi,
I have modified the code to the new dependencies, and it seems that it works

Hi. Please create a gist for it. Can't copy code because all formating breaks down.

sorry, I was just trying to help while you were publishing the new code
I edit the post

@advokatb
Copy link
Author

Hi,
I have modified the code to the new dependencies, and it seems that it works

Hi. Please create a gist for it. Can't copy code because all formating breaks down.

sorry, I was just trying to help while you were publishing the new code
I edit the post

I'm not the author, just a user.
I'm trying to say that I can't test your code because I can't copy it with Python formatting...

@LeidenSpain
Copy link

Hi,
I have modified the code to the new dependencies, and it seems that it works

Hi. Please create a gist for it. Can't copy code because all formating breaks down.

sorry, I was just trying to help while you were publishing the new code
I edit the post

I'm not the author, just a user.
I'm trying to say that I can't test your code because I can't copy it with Python formatting...

ups, I misunderstood

""" https://github.com/h4v1nfun/xiaomi_miio_gateway/blob/master/custom_components/media_player/xiaomi_miio_gateway.py """
"""
Add support for the Xiaomi Gateway Radio.
"""

import logging
import voluptuous as vol
import asyncio
from functools import partial

import homeassistant.helpers.config_validation as cv
from homeassistant.components.media_player import (
    MediaPlayerDevice, MEDIA_PLAYER_SCHEMA, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const import (
    SUPPORT_TURN_ON, SUPPORT_TURN_OFF, SUPPORT_VOLUME_MUTE,
    SUPPORT_VOLUME_STEP, SUPPORT_VOLUME_SET, SUPPORT_NEXT_TRACK)
from homeassistant.const import (CONF_HOST, CONF_NAME, CONF_TOKEN, STATE_OFF, STATE_ON)

REQUIREMENTS = ['python-miio>=0.3.7']

ATTR_MODEL = 'model'
ATTR_FIRMWARE_VERSION = 'firmware_version'
ATTR_HARDWARE_VERSION = 'hardware_version'

DEFAULT_NAME = "Xiaomi Gateway Radio"
DATA_KEY = 'media_player.xiaomi_miio_gateway'

ATTR_STATE_PROPERTY = 'state_property'
ATTR_STATE_VALUE = 'state_value'

_LOGGER = logging.getLogger(__name__)

SUPPORT_XIAOMI_GATEWAY_FM = SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | \
                    SUPPORT_TURN_OFF | SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET | SUPPORT_NEXT_TRACK

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_HOST): cv.string,
    vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)),
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})

@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Xiaomi Gateway miio platform."""
    from miio import Device, DeviceException
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    token = config.get(CONF_TOKEN)

    _LOGGER.info("Initializing Xiaomi Gateway with host %s (token %s...)", host, token[:5])

    try:
        miio_device = Device(host, token)
        device_info = miio_device.info()
        model = device_info.model
        _LOGGER.info("%s %s %s detected",
                     model,
                     device_info.firmware_version,
                     device_info.hardware_version)

        device = XiaomiGateway(miio_device, config, device_info)
    except DeviceException:
        raise PlatformNotReady

    hass.data[DATA_KEY][host] = device
    async_add_devices([device], update_before_add=True)

class XiaomiGateway(MediaPlayerDevice):
    """Represent the Xiaomi Gateway for Home Assistant."""

    def __init__(self, device, config, device_info):
        """Initialize the entity."""
        self._device = device

        self._name = config.get(CONF_NAME)
        self._skip_update = False

        self._model = device_info.model
        self._unique_id = "{}-{}-{}".format(device_info.model,
                                            device_info.mac_address,
                                            'pause')
        self._icon = 'mdi:radio'
        self._muted = False
        self._volume = 0
        self._available = None
        self._state = None
        self._state_attrs = {
            ATTR_MODEL: self._model,
            ATTR_FIRMWARE_VERSION: device_info.firmware_version,
            ATTR_HARDWARE_VERSION: device_info.hardware_version,
            ATTR_STATE_PROPERTY: 'pause'
        }

    async def _try_command(self, mask_error, func, *args, **kwargs):
        """Call a device command handling error messages."""
        from miio import DeviceException
        try:
            result = await self.hass.async_add_job(
                partial(func, *args, **kwargs))

            _LOGGER.info("Response received from Gateway: %s", result)

            return result[0] == "ok"
        except DeviceException as exc:
            _LOGGER.error(mask_error, exc)
            return False

    @property
    def name(self):
        """Return the display name of this Gateway."""
        return self._name

    @property
    def state(self):
        """Return _state variable, containing the appropriate constant."""
        return self._state

    @property
    def assumed_state(self):
        """Indicate that state is assumed."""
        return True

    @property
    def is_volume_muted(self):
        """Boolean if volume is currently muted."""
        return self._muted

    @property
    def volume_level(self):
        """Volume level of the media player (0..1)."""
        return self._volume

    @property
    def supported_features(self):
        """Flag media player features that are supported."""
        return SUPPORT_XIAOMI_GATEWAY_FM

    async def turn_off(self):
        result = await self._try_command(
            "Turning the Gateway off failed.", self._device.send,
            'play_fm', ['off'])

    async def turn_on(self):
        """Wake the Gateway back up from sleep."""
        result = await self._try_command(
            "Turning the Gateway on failed.", self._device.send,
            'play_fm', ['on'])

    async def volume_up(self):
        """Increase volume by one."""
        volume = round(self._volume * 100) + 1
        result = await self._try_command(
            "Turning the Gateway volume failed.", self._device.send,
            'set_fm_volume', [volume])

    async def media_next_track(self):
        """Send next track command."""
        result = await self._try_command(
            "Turning the Gateway volume failed.", self._device.send,
            'play_fm', ['next'])

    async def volume_down(self):
        """Decrease volume by one."""
        volume = round(self._volume * 100) - 1
        result = await self._try_command(
            "Turning the Gateway volume failed.", self._device.send,
            'set_fm_volume', [volume])

    async def set_volume_level(self, volume):
        volset = round(volume * 100)
        result = await self._try_command(
            "Setting the Gateway volume failed.", self._device.send,
            'set_fm_volume', [volset])

    async def mute_volume(self, mute):
        """Send mute command."""
        volume = 10
        if self._muted == False:
            volume = 0

        result = await self._try_command(
            "Turning the Gateway volume failed.", self._device.send,
            'set_fm_volume', [volume])
        if result:
            if volume == 0:
                self._muted = True
            else:
                self._muted = False

    async def async_update(self):
        """Fetch state from Gateway."""
        from miio import DeviceException

        try:
            state = await self.hass.async_add_job(
                self._device.send, 'get_prop_fm', '')
            _LOGGER.info("Got new state: %s", state)
            volume = state.pop('current_volume')
            state = state.pop('current_status')

            _LOGGER.debug("Got new state: %s", state)

            self._available = True
            if volume == 0:
                self._muted = True
            else:
                self._muted = False

            if state == 'pause':
                self._state = STATE_OFF
            elif state == 'run':
                self._state = STATE_ON
                self._volume = volume / 100
            else:
                _LOGGER.warning(
                    "New state (%s) doesn't match expected values: %s/%s",
                    state, 'pause', 'run')
                self._state = None

            self._state_attrs.update({
                ATTR_STATE_VALUE: state
            })

        except DeviceException as ex:
            self._available = False
            _LOGGER.error("Got exception while fetching the state: %s", ex)

@h4v1nfun
Copy link
Owner

Hi,
I have modified the code to the new dependencies, and it seems that it works

Hi. Please create a gist for it. Can't copy code because all formating breaks down.

sorry, I was just trying to help while you were publishing the new code
I edit the post

I'm not the author, just a user.
I'm trying to say that I can't test your code because I can't copy it with Python formatting...

ups, I misunderstood

""" https://github.com/h4v1nfun/xiaomi_miio_gateway/blob/master/custom_components/media_player/xiaomi_miio_gateway.py """
"""
Add support for the Xiaomi Gateway Radio.
"""

import logging
import voluptuous as vol
import asyncio
from functools import partial

import homeassistant.helpers.config_validation as cv
from homeassistant.components.media_player import (
    MediaPlayerDevice, MEDIA_PLAYER_SCHEMA, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const import (
    SUPPORT_TURN_ON, SUPPORT_TURN_OFF, SUPPORT_VOLUME_MUTE,
    SUPPORT_VOLUME_STEP, SUPPORT_VOLUME_SET, SUPPORT_NEXT_TRACK)
from homeassistant.const import (CONF_HOST, CONF_NAME, CONF_TOKEN, STATE_OFF, STATE_ON)

REQUIREMENTS = ['python-miio>=0.3.7']

ATTR_MODEL = 'model'
ATTR_FIRMWARE_VERSION = 'firmware_version'
ATTR_HARDWARE_VERSION = 'hardware_version'

DEFAULT_NAME = "Xiaomi Gateway Radio"
DATA_KEY = 'media_player.xiaomi_miio_gateway'

ATTR_STATE_PROPERTY = 'state_property'
ATTR_STATE_VALUE = 'state_value'

_LOGGER = logging.getLogger(__name__)

SUPPORT_XIAOMI_GATEWAY_FM = SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | \
                    SUPPORT_TURN_OFF | SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET | SUPPORT_NEXT_TRACK

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_HOST): cv.string,
    vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)),
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})

@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Xiaomi Gateway miio platform."""
    from miio import Device, DeviceException
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    token = config.get(CONF_TOKEN)

    _LOGGER.info("Initializing Xiaomi Gateway with host %s (token %s...)", host, token[:5])

    try:
        miio_device = Device(host, token)
        device_info = miio_device.info()
        model = device_info.model
        _LOGGER.info("%s %s %s detected",
                     model,
                     device_info.firmware_version,
                     device_info.hardware_version)

        device = XiaomiGateway(miio_device, config, device_info)
    except DeviceException:
        raise PlatformNotReady

    hass.data[DATA_KEY][host] = device
    async_add_devices([device], update_before_add=True)

class XiaomiGateway(MediaPlayerDevice):
    """Represent the Xiaomi Gateway for Home Assistant."""

    def __init__(self, device, config, device_info):
        """Initialize the entity."""
        self._device = device

        self._name = config.get(CONF_NAME)
        self._skip_update = False

        self._model = device_info.model
        self._unique_id = "{}-{}-{}".format(device_info.model,
                                            device_info.mac_address,
                                            'pause')
        self._icon = 'mdi:radio'
        self._muted = False
        self._volume = 0
        self._available = None
        self._state = None
        self._state_attrs = {
            ATTR_MODEL: self._model,
            ATTR_FIRMWARE_VERSION: device_info.firmware_version,
            ATTR_HARDWARE_VERSION: device_info.hardware_version,
            ATTR_STATE_PROPERTY: 'pause'
        }

    async def _try_command(self, mask_error, func, *args, **kwargs):
        """Call a device command handling error messages."""
        from miio import DeviceException
        try:
            result = await self.hass.async_add_job(
                partial(func, *args, **kwargs))

            _LOGGER.info("Response received from Gateway: %s", result)

            return result[0] == "ok"
        except DeviceException as exc:
            _LOGGER.error(mask_error, exc)
            return False

    @property
    def name(self):
        """Return the display name of this Gateway."""
        return self._name

    @property
    def state(self):
        """Return _state variable, containing the appropriate constant."""
        return self._state

    @property
    def assumed_state(self):
        """Indicate that state is assumed."""
        return True

    @property
    def is_volume_muted(self):
        """Boolean if volume is currently muted."""
        return self._muted

    @property
    def volume_level(self):
        """Volume level of the media player (0..1)."""
        return self._volume

    @property
    def supported_features(self):
        """Flag media player features that are supported."""
        return SUPPORT_XIAOMI_GATEWAY_FM

    async def turn_off(self):
        result = await self._try_command(
            "Turning the Gateway off failed.", self._device.send,
            'play_fm', ['off'])

    async def turn_on(self):
        """Wake the Gateway back up from sleep."""
        result = await self._try_command(
            "Turning the Gateway on failed.", self._device.send,
            'play_fm', ['on'])

    async def volume_up(self):
        """Increase volume by one."""
        volume = round(self._volume * 100) + 1
        result = await self._try_command(
            "Turning the Gateway volume failed.", self._device.send,
            'set_fm_volume', [volume])

    async def media_next_track(self):
        """Send next track command."""
        result = await self._try_command(
            "Turning the Gateway volume failed.", self._device.send,
            'play_fm', ['next'])

    async def volume_down(self):
        """Decrease volume by one."""
        volume = round(self._volume * 100) - 1
        result = await self._try_command(
            "Turning the Gateway volume failed.", self._device.send,
            'set_fm_volume', [volume])

    async def set_volume_level(self, volume):
        volset = round(volume * 100)
        result = await self._try_command(
            "Setting the Gateway volume failed.", self._device.send,
            'set_fm_volume', [volset])

    async def mute_volume(self, mute):
        """Send mute command."""
        volume = 10
        if self._muted == False:
            volume = 0

        result = await self._try_command(
            "Turning the Gateway volume failed.", self._device.send,
            'set_fm_volume', [volume])
        if result:
            if volume == 0:
                self._muted = True
            else:
                self._muted = False

    async def async_update(self):
        """Fetch state from Gateway."""
        from miio import DeviceException

        try:
            state = await self.hass.async_add_job(
                self._device.send, 'get_prop_fm', '')
            _LOGGER.info("Got new state: %s", state)
            volume = state.pop('current_volume')
            state = state.pop('current_status')

            _LOGGER.debug("Got new state: %s", state)

            self._available = True
            if volume == 0:
                self._muted = True
            else:
                self._muted = False

            if state == 'pause':
                self._state = STATE_OFF
            elif state == 'run':
                self._state = STATE_ON
                self._volume = volume / 100
            else:
                _LOGGER.warning(
                    "New state (%s) doesn't match expected values: %s/%s",
                    state, 'pause', 'run')
                self._state = None

            self._state_attrs.update({
                ATTR_STATE_VALUE: state
            })

        except DeviceException as ex:
            self._available = False
            _LOGGER.error("Got exception while fetching the state: %s", ex)

hey,

open a pr

my house is remodling and my home assistant is offline

@LeidenSpain
Copy link

Sorry,
I do not understand what you mean
Regards

@koznov
Copy link

koznov commented Oct 17, 2019

It is correct place pytjon script in Home Assistant by path /config/custom_components/xiaomi_gateway_radio/media_player.py and put into it script. After this i've initialized it by adding to /config/configuration.yaml :

media_player:
  - platform: xiaomi_gateway_radio
    host: 10.255.254.150
    token: XXXXXXXXXXXXXXXXXXXXXXXXX

When i'm trying to check config it says:
Platform error media_player.xiaomi_gateway_radio - Integration 'xiaomi_gateway_radio' not found.

@laguten
Copy link

laguten commented Nov 14, 2019

When i'm trying to check config it says:
Platform error media_player.xiaomi_gateway_radio - Integration 'xiaomi_gateway_radio' not found.

For me too (((

@Tri0L
Copy link

Tri0L commented Nov 15, 2019

I have the same error.

Integration 'xiaomi_gateway_radio' not found.

@advokatb
Copy link
Author

advokatb commented Jan 1, 2020

Yes, now is a new error

2020-01-01 14:11:18 ERROR (MainThread) [homeassistant.components.media_player] Error while setting up platform xiaomi_miio_gateway
Traceback (most recent call last):
  File "c:\users\igorb\appdata\local\programs\python\python37\lib\site-packages\homeassistant\helpers\entity_platform.py", line 150, in _async_setup_platform
    await asyncio.wait_for(asyncio.shield(task), SLOW_SETUP_MAX_WAIT)
  File "c:\users\igorb\appdata\local\programs\python\python37\lib\asyncio\tasks.py", line 442, in wait_for
    return fut.result()
  File "c:\users\igorb\appdata\local\programs\python\python37\lib\asyncio\coroutines.py", line 120, in coro
    res = func(*args, **kw)
  File "d:\User\.homeassistant\custom_components\xiaomi_miio_gateway\media_player.py", line 46, in async_setup_platform
    from miio import Device, DeviceException
ModuleNotFoundError: No module named 'miio'

@xrust83
Copy link

xrust83 commented Apr 2, 2020

Its work

""" https://github.com/h4v1nfun/xiaomi_miio_gateway/blob/master/custom_components/media_player/xiaomi_miio_gateway.py """
"""
Add support for the Xiaomi Gateway Radio.
"""

import logging
import voluptuous as vol
import asyncio
from functools import partial

import homeassistant.helpers.config_validation as cv
from homeassistant.components.media_player import (
MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const import (
SUPPORT_TURN_ON, SUPPORT_TURN_OFF, SUPPORT_VOLUME_MUTE,
SUPPORT_VOLUME_STEP, SUPPORT_VOLUME_SET, SUPPORT_NEXT_TRACK)
from homeassistant.const import (CONF_HOST, CONF_NAME, CONF_TOKEN, STATE_OFF, STATE_ON)

REQUIREMENTS = ['python-miio>=0.3.7']

ATTR_MODEL = 'model'
ATTR_FIRMWARE_VERSION = 'firmware_version'
ATTR_HARDWARE_VERSION = 'hardware_version'

DEFAULT_NAME = "Xiaomi Gateway Radio"
DATA_KEY = 'media_player.xiaomi_miio_gateway'

ATTR_STATE_PROPERTY = 'state_property'
ATTR_STATE_VALUE = 'state_value'

_LOGGER = logging.getLogger(name)

SUPPORT_XIAOMI_GATEWAY_FM = SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON |
SUPPORT_TURN_OFF | SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET | SUPPORT_NEXT_TRACK

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})

@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up the Xiaomi Gateway miio platform."""
from miio import Device, DeviceException
if DATA_KEY not in hass.data:
hass.data[DATA_KEY] = {}

host = config.get(CONF_HOST)
token = config.get(CONF_TOKEN)

_LOGGER.info("Initializing Xiaomi Gateway with host %s (token %s...)", host, token[:5])

try:
    miio_device = Device(host, token)
    device_info = miio_device.info()
    model = device_info.model
    _LOGGER.info("%s %s %s detected",
                 model,
                 device_info.firmware_version,
                 device_info.hardware_version)

    device = XiaomiGateway(miio_device, config, device_info)
except DeviceException:
    raise PlatformNotReady

hass.data[DATA_KEY][host] = device
async_add_devices([device], update_before_add=True)

class XiaomiGateway(MediaPlayerDevice):
"""Represent the Xiaomi Gateway for Home Assistant."""

def __init__(self, device, config, device_info):
    """Initialize the entity."""
    self._device = device

    self._name = config.get(CONF_NAME)
    self._skip_update = False

    self._model = device_info.model
    self._unique_id = "{}-{}-{}".format(device_info.model,
                                        device_info.mac_address,
                                        'pause')
    self._icon = 'mdi:radio'
    self._muted = False
    self._volume = 0
    self._available = None
    self._state = None
    self._state_attrs = {
        ATTR_MODEL: self._model,
        ATTR_FIRMWARE_VERSION: device_info.firmware_version,
        ATTR_HARDWARE_VERSION: device_info.hardware_version,
        ATTR_STATE_PROPERTY: 'pause'
    }

async def _try_command(self, mask_error, func, *args, **kwargs):
    """Call a device command handling error messages."""
    from miio import DeviceException
    try:
        result = await self.hass.async_add_job(
            partial(func, *args, **kwargs))

        _LOGGER.info("Response received from Gateway: %s", result)

        return result[0] == "ok"
    except DeviceException as exc:
        _LOGGER.error(mask_error, exc)
        return False

@property
def name(self):
    """Return the display name of this Gateway."""
    return self._name

@property
def state(self):
    """Return _state variable, containing the appropriate constant."""
    return self._state

@property
def assumed_state(self):
    """Indicate that state is assumed."""
    return True

@property
def is_volume_muted(self):
    """Boolean if volume is currently muted."""
    return self._muted

@property
def volume_level(self):
    """Volume level of the media player (0..1)."""
    return self._volume

@property
def supported_features(self):
    """Flag media player features that are supported."""
    return SUPPORT_XIAOMI_GATEWAY_FM

async def turn_off(self):
    result = await self._try_command(
        "Turning the Gateway off failed.", self._device.send,
        'play_fm', ['off'])

async def turn_on(self):
    """Wake the Gateway back up from sleep."""
    result = await self._try_command(
        "Turning the Gateway on failed.", self._device.send,
        'play_fm', ['on'])

async def volume_up(self):
    """Increase volume by one."""
    volume = round(self._volume * 100) + 1
    result = await self._try_command(
        "Turning the Gateway volume failed.", self._device.send,
        'set_fm_volume', [volume])

async def media_next_track(self):
    """Send next track command."""
    result = await self._try_command(
        "Turning the Gateway volume failed.", self._device.send,
        'play_fm', ['next'])

async def volume_down(self):
    """Decrease volume by one."""
    volume = round(self._volume * 100) - 1
    result = await self._try_command(
        "Turning the Gateway volume failed.", self._device.send,
        'set_fm_volume', [volume])

async def set_volume_level(self, volume):
    volset = round(volume * 100)
    result = await self._try_command(
        "Setting the Gateway volume failed.", self._device.send,
        'set_fm_volume', [volset])

async def mute_volume(self, mute):
    """Send mute command."""
    volume = 10
    if self._muted == False:
        volume = 0

    result = await self._try_command(
        "Turning the Gateway volume failed.", self._device.send,
        'set_fm_volume', [volume])
    if result:
        if volume == 0:
            self._muted = True
        else:
            self._muted = False

async def async_update(self):
    """Fetch state from Gateway."""
    from miio import DeviceException

    try:
        state = await self.hass.async_add_job(
            self._device.send, 'get_prop_fm', '')
        _LOGGER.info("Got new state: %s", state)
        volume = state.pop('current_volume')
        state = state.pop('current_status')

        _LOGGER.debug("Got new state: %s", state)

        self._available = True
        if volume == 0:
            self._muted = True
        else:
            self._muted = False

        if state == 'pause':
            self._state = STATE_OFF
        elif state == 'run':
            self._state = STATE_ON
            self._volume = volume / 100
        else:
            _LOGGER.warning(
                "New state (%s) doesn't match expected values: %s/%s",
                state, 'pause', 'run')
            self._state = None

        self._state_attrs.update({
            ATTR_STATE_VALUE: state
        })

    except DeviceException as ex:
        self._available = False
        _LOGGER.error("Got exception while fetching the state: %s", ex)

@vinzeno
Copy link

vinzeno commented Apr 16, 2020

Hello I have the same problem.
I am under 0.108.4. Can you tell me which files to put in the folder of the custom component directory as well as their content. I still get the “no integration found” error. Can you also give me back the code to put in configuration.yaml.
thank you in advance

@webhostsg
Copy link

I'm getting the same error
(MainThread) [homeassistant.config] Platform error: media_player - Integration 'xiaomi_gateway_radio' not found.

On Home Assistant 0.108.9

@Smitkas
Copy link

Smitkas commented May 13, 2020

same error on Home Assistant 0.109.6

h4v1nfun pushed a commit that referenced this issue Oct 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests