Platform error vacuum miio2 integration miio2 not found

nqkdev,home-assistant-vacuum-styj02ym | Install error

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

I followed all steps from readme
Install 5.4.45 mi home and get token
{"did":"292098235","token":"4750684e3531505452616d7173417871","longitude":"0.00000000","latitude":"0.00000000","name":"R2D2","pid":"0","localip":"192.168.0.101","mac":"44:23:7C:A0:37:B1","ssid":"TP-LINK_7CCAAE","bssid":"E8:94:F6:7C:CA:AE","parent_id":"","parent_model":"","show_mode":1,"model":"dreame.vacuum.mc1808","adminFlag":1,"shareFlag":0,"permitLevel":16,"isOnline":true,"desc":"Устройство в сети ","extra":{"isSetPincode":0,"fw_version":"3.5.8_1059","needVerifyCode":0,"isPasswordEncrypt":0},"uid":4172124617,"pd_id":66181,"password":"","p2p_id":"","rssi":-52,"family_id":0,"reset_flag":0}

But not connect, i have error

2020-09-22 23:12:19 WARNING (MainThread) [homeassistant.components.vacuum] Setup of vacuum platform miio2 is taking over 10 seconds.
2020-09-22 23:12:30 ERROR (SyncWorker_0) [miio.miioprotocol] Got error when receiving: timed out
2020-09-22 23:12:30 WARNING (SyncWorker_0) [custom_components.miio2.vacuum] Got exception while fetching the state: No response from the device
2020-09-22 23:13:00 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.mi_hihi is taking over 10 seconds
2020-09-22 23:13:10 WARNING (MainThread) [homeassistant.components.vacuum] Updating miio2 vacuum took longer than the scheduled update interval 0:00:20
2020-09-22 23:13:10 ERROR (SyncWorker_9) [miio.miioprotocol] Got error when receiving: timed out

And
2020-09-22 23:11:07 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.mi_hihi is taking over 10 seconds
2020-09-22 23:11:07 DEBUG (SyncWorker_9) [miio.miioprotocol] Retrying with incremented id, retries left: 2
2020-09-22 23:11:08 DEBUG (SyncWorker_9) [miio.protocol] Unable to decrypt, returning raw bytes: b»
2020-09-22 23:11:08 DEBUG (SyncWorker_9) [miio.miioprotocol] Got a response: Container:
data = Container:
data = b» (total 0)
value = b» (total 0)
offset1 = 32
offset2 = 32
length = 0
header = Container:
data = b’!1×00 x00x00x00x00x11ix10xbb_jZ[‘ (total 16)
value = Container:
length = 32
unknown = 0
device_id = b’x11ix10xbb’ (total 4)
ts = 2020-09-22 20:11:07
offset1 = 0
offset2 = 16
length = 16
checksum = b’xffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxff’ (total 16)
2020-09-22 23:11:08 DEBUG (SyncWorker_9) [miio.miioprotocol] Discovered 116910bb with ts: 2020-09-22 20:11:07, token: b’ffffffffffffffffffffffffffffffff’
2020-09-22 23:11:08 DEBUG (SyncWorker_9) [miio.miioprotocol] 192.168.0.101:54321 >>: {‘id’: 1115, ‘method’: ‘get_prop’, ‘params’: [‘run_state’, ‘mode’, ‘err_state’, ‘battary_life’, ‘box_type’, ‘mop_type’, ‘s_time’, ‘s_area’, ‘suction_grade’, ‘water_grade’, ‘remember_map’, ‘has_map’, ‘is_mop’, ‘has_newmap’]}

In console send
$ miiocli viomivacuum —ip 192.168.0.101 —token 4750684e3531505452616d7173417871 info
Model: dreame.vacuum.mc1808
Hardware version: Linux
Firmware version: 3.5.8_1059
Network: {‘localIp’: ‘192.168.0.101’, ‘mask’: ‘255.255.255.0’, ‘gw’: ‘192.168.0.1’}
AP: {‘ssid’: ‘TP-LINK_7CCAAE’, ‘bssid’: ‘E8:94:F6:7C:CA:AE’, ‘rssi’: -51}

How do I get it to work?

nergal / homeassistant-vacuum-viomi
Goto Github
PK

View Code? Open in Web Editor
NEW

30.0
8.0
9.0
158 KB

Integration of a Xiaomi Viomi vacuum to a Home Assistant

License: MIT License

Makefile 1.83%
Python 98.17%
python
hassio
hass
hacs
vacuum
vacuum-robot
home-automation
homeassistant-integration
xiaomi
viomi

homeassistant-vacuum-viomi’s Introduction

Contributors

nergal avatar

homeassistant-vacuum-viomi’s Issues

cannot import name ‘ROCKROBO_S7_MAXV’ from ‘miio.vacuum’ (/usr/local/lib/python3.10/site-packages/miio/vacuum.py

I dont have ROCKROBO_S7_MAXV, i usually need to do double reboot to get rid of this warning and get integration working.

2022-11-26 07:32:51.480 ERROR (MainThread) [homeassistant.setup] Setup failed for xiaomi_miio: Unable to import component: cannot import name 'ROCKROBO_S7_MAXV' from 'miio.vacuum' (/usr/local/lib/python3.10/site-packages/miio/vacuum.py) 2022-11-26 07:32:51.573 ERROR (MainThread) [homeassistant.setup] Unable to set up dependencies of xiaomi_viomi. Setup failed for dependencies: xiaomi_miio 2022-11-26 07:32:51.579 ERROR (MainThread) [homeassistant.setup] Setup failed for custom integration xiaomi_viomi: (DependencyError(...), 'Could not setup dependencies: xiaomi_miio')

viomi s9 support

I would love to see viomi s9 support :)

Doesn’t show up in integrations

Hi, after hacs install it’s not visible under add integration.

Looks like non existent state

FAILED error_code: 2108, state: ViomiVacuumState.VacuumingAndMopping, state_code: 6
FAILED error_code: 2100, state: ViomiVacuumState.VacuumingAndMopping, state_code: 6
FAILED error_code: 2101, state: ViomiVacuumState.VacuumingAndMopping, state_code: 6
FAILED error_code: 514, state: ViomiVacuumState.Idle2, state_code: 2
FAILED error_code: 2102, state: ViomiVacuumState.Returning, state_code: 4

Logger: custom_components.xiaomi_viomi.vacuum
Source: custom_components/xiaomi_viomi/vacuum.py:116

Cover vacuum with unit tests

«zone clean up» and «Pin & go»

Hi

First of all, thanks very much for your hard work. Finally got it to work with my vacuum cleaner!!
However, the «zone clean up» and «Pin & go» is not working.
Is just me, or is a known issue?

Thanks a lot.

Cannot ad repo to HACS

STYTJ02YM not supported?

Hello,

looks like that this type is not supported under your integration ?
Model: viomi.vacuum.v8 STYTJ02YM
I’ve tried latest version, beta as well but its not working.

Traceback (most recent call last):
File «/usr/src/homeassistant/homeassistant/helpers/entity_platform.py», line 246, in _async_setup_platform
task = async_create_setup_task()
File «/usr/src/homeassistant/homeassistant/helpers/entity_platform.py», line 175, in async_create_setup_task
return platform.async_setup_platform( # type: ignore
TypeError: async_setup_platform() takes 3 positional arguments but 4 were given

When I am trying to set up via Integration:
Incomplete information to setup device, no host or token supplied
image

Fatal error after update to 0.0.4 Integation don’t start at all

Hi
After update to 0.0.4 version integration don’t work at all after the reboot
My HA version is 2022.2.0
bellow screenshot with error
image

Zone clean-up?

Hello there,
I have used viomi integration for several months, either from you, nergal, or from someone upstream or downstream, can’t remember. However it stopped working so I moved to this viomi integration, because of how easy it is to download/update via HACS.

However this flavor of integration is missing zone clean-up, which I miss very much. Any ideas if you plan to add support? Or is it HASS issue? Or maybe I am doing something wrong?
I have used such definitions:

          service: xiaomi_viomi.clean_zone
          target:
            entity_id: vacuum.robot
          data:
            zone:
              - - -1.1 #left
                - 1.3 #up
                - 0.2 #right
                - 0.4 #down
            repeats: 1

Now the service is non-existent in this integration. ANY ideas? Thank you.

Locate service not working for viomi_vacuum_v8

When i try to use service locate

service: vacuum.locate
target:
entity_id: vacuum.viomi_vacuum_v8

I get error

2022-01-18 15:26:59 ERROR (MainThread) [homeassistant.helpers.script.websocket_api_script] websocket_api script: Error executing script. Unexpected error for call_service at pos 1:
Traceback (most recent call last):
File «/usr/src/homeassistant/homeassistant/helpers/script.py», line 381, in _async_step
await getattr(self, handler)()
File «/usr/src/homeassistant/homeassistant/helpers/script.py», line 584, in _async_call_service_step
await service_task
File «/usr/src/homeassistant/homeassistant/core.py», line 1495, in async_call
task.result()
File «/usr/src/homeassistant/homeassistant/core.py», line 1530, in _execute_service
await handler.job.target(service_call)
File «/usr/src/homeassistant/homeassistant/helpers/entity_component.py», line 209, in handle_service
await self.hass.helpers.service.entity_service_call(
File «/usr/src/homeassistant/homeassistant/helpers/service.py», line 663, in entity_service_call
future.result() # pop exception if have
File «/usr/src/homeassistant/homeassistant/helpers/entity.py», line 896, in async_request_call
await coro
File «/usr/src/homeassistant/homeassistant/helpers/service.py», line 700, in _handle_entity_call
await result
File «/usr/src/homeassistant/homeassistant/components/vacuum/init.py», line 239, in async_locate
await self.hass.async_add_executor_job(partial(self.locate, **kwargs))
File «/usr/local/lib/python3.9/concurrent/futures/thread.py», line 52, in run
result = self.fn(*self.args, **self.kwargs)
File «/usr/src/homeassistant/homeassistant/components/vacuum/init.py», line 232, in locate
raise NotImplementedError()
NotImplementedError
2022-01-18 15:26:59 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection] [139729599148624] Error handling message: Unknown error
Traceback (most recent call last):
File «/usr/src/homeassistant/homeassistant/components/websocket_api/decorators.py», line 27, in _handle_async_response
await func(hass, connection, msg)
File «/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py», line 527, in handle_execute_script
await script_obj.async_run(msg.get(«variables»), context=context)
File «/usr/src/homeassistant/homeassistant/helpers/script.py», line 1260, in async_run
await asyncio.shield(run.async_run())
File «/usr/src/homeassistant/homeassistant/helpers/script.py», line 363, in async_run
await self._async_step(log_exceptions=False)
File «/usr/src/homeassistant/homeassistant/helpers/script.py», line 381, in _async_step
await getattr(self, handler)()
File «/usr/src/homeassistant/homeassistant/helpers/script.py», line 584, in _async_call_service_step
await service_task
File «/usr/src/homeassistant/homeassistant/core.py», line 1495, in async_call
task.result()
File «/usr/src/homeassistant/homeassistant/core.py», line 1530, in _execute_service
await handler.job.target(service_call)
File «/usr/src/homeassistant/homeassistant/helpers/entity_component.py», line 209, in handle_service
await self.hass.helpers.service.entity_service_call(
File «/usr/src/homeassistant/homeassistant/helpers/service.py», line 663, in entity_service_call
future.result() # pop exception if have
File «/usr/src/homeassistant/homeassistant/helpers/entity.py», line 896, in async_request_call
await coro
File «/usr/src/homeassistant/homeassistant/helpers/service.py», line 700, in _handle_entity_call
await result
File «/usr/src/homeassistant/homeassistant/components/vacuum/init.py», line 239, in async_locate
await self.hass.async_add_executor_job(partial(self.locate, **kwargs))
File «/usr/local/lib/python3.9/concurrent/futures/thread.py», line 52, in run
result = self.fn(*self.args, **self.kwargs)
File «/usr/src/homeassistant/homeassistant/components/vacuum/init.py», line 232, in locate
raise NotImplementedError()
NotImplementedError

Update documentation

Documentation should contain:

  • stability description
  • general description of the package
  • ways of how to install the package
  • common issues during installation and usage
  • optional stuff like credits, license, etc

Component suddenly stoped working after home assistant update to 2022.11.0

log:
Logger: homeassistant.config_entries
Source: config_entries.py:809
First occurred: 13:27:21 (1 occurrences)
Last logged: 13:27:21

Error occurred loading configuration flow for integration xiaomi_miio: cannot import name ‘ROCKROBO_S7_MAXV’ from ‘miio.vacuum’ (/usr/local/lib/python3.10/site-packages/miio/vacuum.py)

I have tried v3 v4 and v4-1 same results.

no other changes

component has worked stable for over a year.

Vacuum cleaner not available version operating system 7.5

Hello,
after upgrading the operating system to version 7.5, the vacuum cleaner has become unavailable.
The HA log is as follows:

Error while setting up xiaomi_viomi platform for vacuum
Traceback (most recent call last):
File «/usr/src/homeassistant/homeassistant/helpers/entity_platform.py», line 249, in _async_setup_platform
await asyncio.shield(task)
File «/config/custom_components/xiaomi_viomi/vacuum.py», line 54, in async_setup_platform
config = await validate_input(hass, raw_config)
File «/config/custom_components/xiaomi_viomi/config_flow.py», line 86, in validate_input
raise InvalidAuth
custom_components.xiaomi_viomi.config_flow.InvalidAuth

Thank you

Viomi V3 (viomi.vacuum.v13) vacuum cleaner status unknown

Hi,
I try to add my Viomi V3 vacuum cleaner using your integration. After uploading «custom_components» folder with the contents I restarted home assistant. «Starting xiaomi.viomi_cleaner» take a while to start.
After adding my cleaner to integrations it shows 1 device and 1 entity.
However when checking info on entity, it shows status unavailable.

No setup or config entry setup function defined

After successful setup, logs shows the error:
Setup failed for xiaomi_viomi: No setup or config entry setup function defined.

Sometimes it is unable to fetch device state

Error in logs:
Got exception while fetching the state: Unable to discover the device 192.168.xx.xx

Logger: custom_components.xiaomi_viomi.vacuum
Source: custom_components/xiaomi_viomi/vacuum.py:252

Add assets

Assets requirements:

  • package name and description in HACS is visible
  • HACS has a proper description page
  • icons are in place
  • package has proper strings in a HASS integration dashboard

DeviceException during setup

DeviceException during setup of Viomi device with host [ip address]

STYJ02YM viomi.vacuum.v8 Mi Robot Vacuum-Mop P

HA 2022.12.6

Can’t config my vacuum
What can I try now?

Add correct state representation

Steps to reproduce:

  1. Open a vacuum card
  2. See its state

Expected behavior:
Status is represented as a machine-readable string, eg. ViomiVacuumState.Docked

Actual behavior:
The state is human-readable and suitable for translation

After update HA to 2021.12 xiaomi_viomi: Error on device update!

Hi! Thank you for your integration
There is an issue after HA 2021.12 update
Can you help?
Vacuum is V-RVCLM21B viomi.vacuum.v6

xiaomi_viomi: Error on device update!
Traceback (most recent call last):
File «/usr/src/homeassistant/homeassistant/helpers/entity_platform.py», line 431, in _async_add_entity
await entity.async_device_update(warning=False)
File «/usr/src/homeassistant/homeassistant/helpers/entity.py», line 684, in async_device_update
await task
File «/usr/local/lib/python3.9/concurrent/futures/thread.py», line 52, in run
result = self.fn(*self.args, **self.kwargs)
File «/config/custom_components/xiaomi_viomi/vacuum.py», line 242, in update
self._fan_speeds = state.fan_speed_presets()
File «/usr/local/lib/python3.9/site-packages/miio/click_common.py», line 179, in _wrap
if gco is not None and gco.output is not None:
AttributeError: ‘ViomiVacuumStatus’ object has no attribute ‘_model’

Change fan state throws ‘int’ object has no attribute ‘value’

On change fan mode through UI

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 185, in handle_call_service
    await hass.services.async_call(
  File "/usr/src/homeassistant/homeassistant/core.py", line 1491, in async_call
    task.result()
  File "/usr/src/homeassistant/homeassistant/core.py", line 1526, in _execute_service
    await handler.job.target(service_call)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 213, in handle_service
    await self.hass.helpers.service.entity_service_call(
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 658, in entity_service_call
    future.result()  # pop exception if have
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 760, in async_request_call
    await coro
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 695, in _handle_entity_call
    await result
  File "/config/custom_components/xiaomi_viomi/vacuum.py", line 306, in async_set_fan_speed
    await self._try_command(
  File "/config/custom_components/xiaomi_viomi/vacuum.py", line 267, in _try_command
    await self.hass.async_add_executor_job(
  File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.8/site-packages/miio/viomivacuum.py", line 667, in set_fan_speed
    self.send("set_suction", [speed.value])
AttributeError: 'int' object has no attribute 'value'

Integration doesn’t return proper cleaning time and area

Returned values displayed as nulls in the UI card

Add additional attributes for STY02YM

I have the global (china) version of the Mi Robot Vacuum-Mop P. On the back it says the model is STYTJ02YM and in the Xiaomi Home app it displays as viomi.vacuum.v7. Firmware is 3.5.3_0047.

With another forked repo which doesn’t work (anymore) I had a lot more attributes. Could these be added? Especially the consumables (for support in the lovelace vacuum card) and box_type (for automations notifying of emptying container) are of interest.
https://github.com/l-j/home-assistant-vacuum-styj02ym

The full list of attributes I got with the other repo:

fan_speed_list:
  - Silent
  - Standard
  - Medium
  - Turbo
battery_level: 100
battery_icon: mdi:battery-charging-100
fan_speed: Turbo
run_state: 5
mode: 0
err_state: 2105
battary_life: 100
box_type: 1
mop_type: 0
s_time: 0
s_area: 0
suction_grade: 3
water_grade: 12
remember_map: 1
has_map: 1
is_mop: 0
has_newmap: 0
side_brush_life: 98
side_brush_hours: 178
main_brush_life: 88
main_brush_hours: 317
hypa_life: 76
hypa_hours: 137
mop_life: 100
mop_hours: 180
water_percent: 0
hw_info: 1.0.3
sw_info: 3.5.3_0047
start_time: 0
order_time: '0'
v_state: 0
zone_data: '0'
repeat_state: 0
light_state: 1
is_charge: 0
is_work: 1
cur_mapid: 1630292632
mop_route: 0
map_num: 1
main_brush_left: 317
side_brush_left: 178
filter_left: 137
sensor_dirty_left: 180
cleaned_area: 0
cleaning_time: 0
status: docked
friendly_name: Stofzuiger
supported_features: 13180

Testing viomi.vacuum.v7

I’m testing the integration with my v7 (the v8’s Chinese version), and those are the commands I tried that work great:

  • start
  • pause
  • stop
  • set_fan_speed
  • return_to_base

Fun fact: the same pause command on miio2 causes the vacuum to say something after pausing, while in your case it just pauses silently.

Commands that don’t work:

  • locate: lol, raises NotImplementedError… but works fine on miio2
  • start_pause: AttributeError: 'MiroboVacuum2' object has no attribute 'async_start_pause' (same for miio2)
  • turn_off: doesn’t seem to do anything? Didn’t try further since I would probably be unable to test other services. Also doesn’t do anything (nor any error logs) on miio2

I didn’t try:

  • turn_on: made no sense since it is on all the time and I couldn’t turn it off
  • send_command: no clue what it does
  • clean_spot: no clue how to use it

Also, since I’m comparing working commands with miio2, an addendum: miio2 seems to update the vacuum’s state (as seen via https://github.com/denysdovhan/vacuum-card) faster than this integration 🤔

Everything here was tried against the entity. Some commands were also tried against the device, which seems to work fine as well. Anything else I should check to say «this integration works fine with v7»? :)

[Enabler] Sometimes update takes much longer then it should be

Need to discover the cause of such kind of log strings:

2021-07-07 20:26:13 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds
2021-07-07 20:26:13 WARNING (SyncWorker_4) [custom_components.xiaomi_viomi.vacuum] Got exception while fetching the state: Unable to discover the device 192.168.x.x
2021-07-07 20:28:13 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds
2021-07-07 20:28:13 WARNING (SyncWorker_4) [custom_components.xiaomi_viomi.vacuum] Got exception while fetching the state: Unable to discover the device 192.168.x.x
2021-07-07 20:32:13 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds
2021-07-07 20:34:13 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds
2021-07-07 20:34:13 WARNING (SyncWorker_4) [custom_components.xiaomi_viomi.vacuum] Got exception while fetching the state: Unable to discover the device 192.168.x.x
2021-07-07 20:41:53 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds
2021-07-07 21:08:53 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds
2021-07-07 21:26:53 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds
2021-07-07 21:32:33 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds
2021-07-07 21:32:34 WARNING (SyncWorker_1) [custom_components.xiaomi_viomi.vacuum] Got exception while fetching the state: Unable to discover the device 192.168.x.x
2021-07-07 21:37:13 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds
2021-07-07 21:44:33 WARNING (MainThread) [homeassistant.helpers.entity] Update of vacuum.viomi_vacuum_v8 is taking over 10 seconds

No strings in the config user popup

There is a call of a not implemented method

[547669146352]
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 185, in handle_call_service
    await hass.services.async_call(
  File "/usr/src/homeassistant/homeassistant/core.py", line 1491, in async_call
    task.result()
  File "/usr/src/homeassistant/homeassistant/core.py", line 1526, in _execute_service
    await handler.job.target(service_call)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 213, in handle_service
    await self.hass.helpers.service.entity_service_call(
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 658, in entity_service_call
    future.result()  # pop exception if have
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 760, in async_request_call
    await coro
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 695, in _handle_entity_call
    await result
  File "/usr/src/homeassistant/homeassistant/components/vacuum/__init__.py", line 228, in async_locate
    await self.hass.async_add_executor_job(partial(self.locate, **kwargs))
  File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/homeassistant/homeassistant/components/vacuum/__init__.py", line 221, in locate
    raise NotImplementedError()
NotImplementedError

Logger: homeassistant.components.websocket_api.http.connection
Source: components/vacuum/__init__.py:221

Viomi V2 (viomi.vacuum.v6) verified working!

I own a chinese Viomi V2 (viomi app) which has been re-flashed with German/European Xiaomi software (Mi Home App) by Viomi itself.
Thus, it registers as a viomi.vacuum.v6 and it seems to work great with your integration! If you need any logs/proof please send me a message, otherwise you can close this issue and mark it as verified :)

Cover config_flow with unit tests

Issue with HA 2022.3 version

Hello,

after installing today’s update of HA i receive this error in the logs:

Platform error: vacuum - Requirements for miio2 not found: ['python-miio==0.5.5'].
also the configuration check error:

Platform error vacuum.miio2 - Requirements for miio2 not found: ['python-miio==0.5.5'].
can you update your component?

У меня также есть Viomi V2 Pro (аналогичная модели Xiaomi styj02ym), подключенная к Mi Home. Я получил сообщение об ошибке «Ошибка: нет ответа от устройства».

Я извлекаю токены из журналов приложения Mi Home 5.4.49, запущенного на BlueStacks.

SmartHome 269:[DEBUG]-12-13 23:50:44.942 processResult in result
{"code":0,"message":"ok","result": 
{"list: [{"did":"309012659", "token":"XXXXX", "longitude":"0.00000000", "latitude":"0.00000000", "name":"Viomi Cleaning  Robot", "pid":"0", "localip":"192.168.1.225", "mac":"XXXX", "ssid":"XXXX", "bssid":"XXXX", "parent_id":"", "parent_model":"", "show_mode":1, "model":"viomi.vacuum.v6", "adminFlag":1, "shareFlag":0, "permitLevel":16, "isOnline":true, "desc":"Urządzenie w trybie online ", "extra":{"isSetPincode":0, "fw_version":"3.5.3_0030", "needVerifyCode":0, "isPasswordEncrypt":0}, "uid":1773537580,"pd_id":66708, "password":"", "p2p_id":"", "rssi":0,"family_id":0,"reset_flag":0}], "virtualModels":[{"model":"zhimi.airpurifier.m1", "state":0, "url":""},{"model":"yunmi.waterpurifier.v2","state":0,"url":""},{"model":"zimi.powerstrip.v2","state":0,"url":""}]}}

mirobo -d discover --handshake 1

INFO:miio.vacuum_cli:Debug mode active
INFO:miio.device:Sending discovery to <broadcast> with timeout of 5s..
DEBUG:miio.protocol:Unable to decrypt, returning raw bytes: b''
DEBUG:miio.device:Got a response: Container:
    data = Container:
        data = b'' (total 0)
        value = b'' (total 0)
        offset1 = 32
        offset2 = 32
        length = 0
    header = Container:
        data = b'!1x00 x00x00x00x00x12k(xb3]xf4x18xb1' (total 16)
        value = Container:
            length = 32
            unknown = 0
            device_id = b'x12k(xb3' (total 4)
            ts = 2019-12-13 23:03:13
        offset1 = 0
        offset2 = 16
        length = 16
    checksum = b'xffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxff' (total 16)
INFO:miio.device:  IP 192.168.1.225 (ID: 126b28b3) - token: b'ffffffffffffffffffffffffffffffff'
INFO:miio.device:Discovery done

Выполнение любой команды с ранее извлеченным токеном заканчивается ошибкой Error: No response from the device
: https://gist.github.com/0sk4r/5e9b25a13bc93c86a603f482e0394d40

Я также пытаюсь использовать mirobo после сброса вакуума WiFi и прямого подключения к Wi-Fi робота. mirobo discovery токен возврата. Никакие другие команды не работали.

Я думаю, что изменения, внесенные в этот PR # 576, также должны работать для Viomi V2 Pro, потому что это один и тот же продукт от разных брендов.

Хорошая мысль @ 0sk4r! К сожалению, у меня это не сработало, НО это привело к более значимой ошибке!

РЕДАКТИРОВАТЬ: Нет, это тот же результат без изменений :(

Репродукция:

virtualenv /tmp/blaa --system-site-packages
cd /tmp/blaa
bin/pip install git+https://github.com/rytilahti/python-miio

Актуальная охота:

$ bin/mirobo discover
INFO:miio.discovery:Discovering devices with mDNS, press any key to quit...
WARNING:miio.discovery:Found unsupported device viomi-vacuum-v6_miio277939356._miio._udp.local. at 192.168.0.9, please report to developers
$ bin/mirobo discover --handshake 1
INFO:miio.device:Sending discovery to <broadcast> with timeout of 5s..
INFO:miio.device:  IP 192.168.0.9 (ID: 1091049c) - token: b'ffffffffffffffffffffffffffffffff'
INFO:miio.device:Discovery done

Не уверен, стоит ли нам изменить какую-то конфигурацию, чтобы объяснить miio, что делать с этим вакуумом.

Повторная попытка без системных пакетов и явной основной версии не помогла:

virtualenv /tmp/bli
cd /tmp/bli
bin/pip install git+https://github.com/rytilahti/python-miio<strong i="6">@master</strong>
...

Привет ребята

Удалось ли вам заставить его работать?

Это устройство использует протокол, отличный от протокола rockrobo, поэтому инструмент mirobo настоящее время не может использоваться с ним. Если кто-то хочет расширить его, чтобы поддержать viomi, пожалуйста, сделайте для этого пиар. На данный момент miiocli viomivacuum можно использовать для основных элементов управления.

Чтобы использовать это в homeassistant, необходимо обновить интеграцию homeassistant, чтобы можно было определить, какой протокол использовать (rockrobo или viomi). Не стесняйтесь делать пиар в репозитории домашнего помощника и для этого!

@rytilahti
miiocli viomivacuum похоже, тоже не работает

miiocli viomivacuum --ip 192.168.0.9 --token xxx info
ERROR:miio.device:Got error when receiving: timed out
Error: No response from the device

Однако он отвечает на пинг (43 мс).

прошивка 3.5.3_0045

Значит, токен, скорее всего, неправильный, извлекли ли вы его со своего мобильного устройства после первоначальной подготовки?

Я лично не могу подтвердить, правильно это или неправильно. Однако я извлек его из мобильного эмулятора после входа в свою учетную запись.

Значит, токен, скорее всего, неправильный, извлекли ли вы его со своего мобильного устройства после первоначальной подготовки?

Жетон правильный.
То же самое для:

  1. Модифицированное приложение Mi Home на android.
  2. Резервная копия iPhone из расшифрованного ZTOKEN в 4169293468_mihome.sqlite base.
  3. Резервное копирование iPhone с базой miio-extract-tokens от 4169293468_mihome.sqlite .

Что еще я мог сделать?

Значит, токен, скорее всего, неправильный, извлекли ли вы его со своего мобильного устройства после первоначальной подготовки?

Жетон правильный.
То же самое для:

  1. Модифицированное приложение Mi Home на android.
  2. Резервная копия iPhone из расшифрованного ZTOKEN в 4169293468_mihome.sqlite base.
  3. Резервное копирование iPhone с базой miio-extract-tokens от 4169293468_mihome.sqlite .

Что еще я мог сделать?

Это может быть та же проблема, что и эта: https://github.com/rytilahti/python-miio/issues/550#issuecomment -574286407

Если вы выключите устройство и снова включите его, сможете ли вы запустить miiocli viomivacuum —ip 192.168.0.9 —token xxx info?
Или: если вы увеличите retry_count в device.py с 3 до 20, сможете ли вы запустить miiocli viomivacuum —ip 192.168.0.9 —token xxx info?

«Вы пробовали выключить и снова включить?» метод работал у меня с комбинацией retry_count=20 в device.py и self._timeout=0.5 , timeout=0.5 . Также помогло снять устройство с док-станции и снова подключиться к нему с помощью MiHome App.
Он такой нестабильный и глючный, но время от времени работает.
@ silentkiller88 большое спасибо!

«Вы пробовали выключить и снова включить?» метод работал у меня с комбинацией retry_count=20 в device.py и self._timeout=0.5 , timeout=0.5 . Также помогло снять устройство с док-станции и снова подключиться к нему с помощью MiHome App.
Он такой нестабильный и глючный, но время от времени работает.
@ silentkiller88 большое спасибо!

@rytilahti Я думаю, что для viomi v2, а также для styj02ym есть одна и та же проблема (такое же оборудование). Проблема в том, что программе требуется много повторных попыток, прежде чем она получит действительный ответ от робота.
Вы хотите, чтобы я создал для этого новый выпуск? Я думаю, что эта проблема говорит сама за себя (обнаруживается, но не отвечает)

@ silentkiller88 Насколько я понимаю, проблема заключается в том, что устройство не отвечает на запрос, используя уже использованный (или более низкий, чем «текущий») msgid; это нужно исправить в miiocli, не стесняйтесь открывать PR для этого.

Для пользователей API это не должно быть проблемой, поскольку идентификатор автоматически увеличивается в фоновом режиме, просто miiocli не сохраняет последний использованный идентификатор для следующего вызова.

Мне все еще не повезло, но я не уверен, что мой токен был законным, потому что я получил его из эмулятора, работающего под управлением mihome 5.4.54.
Постараюсь с реальным телефоном.

Тем не менее, я воодушевлен вашим успехом, потому что это означает, что Виоми по своей сути не отказывается от miio :)

Я запустил tcpdump на своем маршрутизаторе и перенаправил на wirehark, чтобы увидеть, как приложение обменивается данными, надеюсь, подтвердив мой токен.
Однако я обнаружил, что приложение обменивается данными извне (пакеты приходили с IP-адреса в Сингапуре) и с другим портом (35764).
Я прикрепляю несколько файлов pcap, чтобы вы могли увидеть, имеют ли они смысл:
Из приложения: vimoi-fromapp.zip
Из библиотеки Python:
viomi-frompython.zip

Я попытался расшифровать сообщения, выполнив это:

from miio.miioprotocol import Message
import codecs
str="21310020000000001091049c5e221c923938f4a7e559812246d0108b856b134f"
# str="213100f0000000001091049c5e221ca2e3e0ceb2f4c9f8babe94999157efddb6ae99e0b14b6b76216d6ceb900bd943cd57c00f9bc67addb710ca3082696baa11b21d92ae6987bd8de058ac0328add82d4f7f96e08957bf67e4d0a14f8d256c6f6141682826a471c1aa46468b80530e7712c9d012b7d33da09fc596153373acdb2aa8fdcc058140ca9daed1f8b462d00da6b26063450a84f720c3c02f39a871907d2427585eb8e79909c9529fc6ad6602661866037d032695778fbe528378d6af12c2585f1064f13483dd5c794139fb4dc3f64695f7d80509507db93f29b5fd3fe613e4d250348a1dd36523023c8d678d"
codecs.decode(str, "hex")
token=b"5736417473416662386c63683136716c"
Message.parse(codecs.decode(str, "hex"), token=token)

Короткое сообщение анализируется успешно, но длинное настаивает, что у меня неправильная контрольная сумма:

wrong checksum, read b'e3e0ceb2f4c9f8babe94999157efddb6', computed b'8bda6dc83a8231eb8245c80bc6ac9b31'

Я знаю, что мой токен там, и если кто-то захочет удаленно управлять моим пылесосом, idgaf. Я немного перепарю его.

Что вы думаете об этом, профессионалы?

Сгенерировал новый токен методом bluestacks ( здесь ) и с такими же неутешительными результатами.

Провел еще несколько тестов. Токен bluestacks кажется нормальным, но никуда не годится.

info иногда работает:

$ venv/bin/mirobo --ip 192.168.0.9 --token REDACTED info
viomi.vacuum.v6 v3.5.3_0030 (50:EC:50:EE:A6:F3) @ 192.168.0.9 - token: REDACTED

запуск inspect в версии NPM работает:

~/projects/python-miio$ /tmp/blu/node_modules/.bin/miio inspect 192.168.0.9
 INFO  Attempting to inspect 192.168.0.9

Device ID: 277939356
Model info: viomi.vacuum.v6
Address: 192.168.0.9
Token: REDACTED via stored token
Support: At least generic

Type info: miio
Capabilities: 

Firmware version: 3.5.3_0030
Hardware version: Linux

WiFi: REDACTED RSSI: 

Remote access (Mi Home App): Maybe

Однако запуск home на sound --test никогда не работает:

~/projects/python-miio$ venv/bin/mirobo --ip 192.168.0.9 --token REDACTED home
ERROR:miio.miioprotocol:Unable to discover a device at address 192.168.0.9
Error: Unable to discover the device 192.168.0.9
~/projects/python-miio$ venv/bin/mirobo --ip 192.168.0.9 --token REDACTED home
ERROR:miio.miioprotocol:Got error when receiving: timed out
Error: No response from the device

Будем рады предоставить любые дампы, которые могут вам помочь — tcpdumps, отладочные распечатки и т. Д.

Хорошо, я последовал этому руководству

Я успешно добавил Viomi V2 Pro в Home Assistant.

Для получения токена я использовал взломанное русское приложение MI Home для android. Дайте мне знать, если вам понадобится ссылка.

@polysa , это было бы здорово.
Не могли бы вы также предоставить:

  1. Соответствующий бит из вашего config.yaml
  2. Версия прошивки вашего пылесоса (достала из npm lib miio)
  3. В каком порядке вы что-то делали (например, вы удалили пылесос из дома mii и добавили его с помощью русского приложения, использовали ли вы эмулятор и т. Д.)

Спасибо!

@BackSlasher Вот и все:

Прямая ссылка на apk
Исходный сайт
custom_components для Home Assistant

Мой conficuration.yaml:

# Xiaomi Vacuume
vacuum:
  - platform: miio2
    host: 192.168.*.*
    token: Your-token
    name: Viomi

Версия прошивки: 3.5.3_0030

Шаги:
Удалите MI Home
Установить модифицированную версию RU
Войти в нормальный режим
Ваша Виоми должна быть указана
Зайдите в свой пылесос -> Три точки вверху справа -> Дополнительные настройки -> Информация о сети -> Токен

Вы уверены в этой платформе? Я получил эту ошибку при попытке использовать miio2:

Jan 19 09:52:16 venus hass[20259]: 2020-01-19 09:52:16 ERROR (MainThread) [homeassistant.config] Platform error: vacuum - Integration 'miio2' not found.
Jan 19 09:52:16 venus hass[20259]: 2020-01-19 09:52:16 INFO (MainThread) [homeassistant.setup] Setting up vacuum

Выглядит многообещающе! Проверю, когда я дома, спасибо: D

@polysa работает! Он не поддерживает все (например, я не могу получить карту комнаты), но «запуск» и «возврат на базу» работают.
@rytilahti Я полностью признателен, если это выходит за рамки вашей компетенции, но было бы интересно понять разницу, которую nqkdev / home-assistant-vacuum-styj02ym применяет при общении и «слиянии» ее с вашей библиотекой.
Думаю, мы можем это закрыть.

@BackSlasher

Вы можете отправлять команды, чтобы изменить режим или убрать определенную комнату.
Мы можем работать вместе, чтобы создать пользовательскую карту в HA, чтобы мы могли управлять вакуумом и передавать правильные настройки. Если вы доступны, дайте мне знать.

@BackSlasher , это не выходит за рамки, так что не беспокойтесь. Большинство (большинство?) Коммуникационных частей уже содержатся в этой библиотеке, просто необходимо соответствующим образом обновить интеграцию homeassistant, чтобы выбрать модель, которая будет использоваться для коммуникации. Или это мое текущее понимание на данный момент, я действительно не копался в коде, чтобы увидеть, нужно ли что-то еще реализовать в этой библиотеке. Если есть необходимость в расширении поддержки, мы будем рады сделать это с помощью PR :-)

@polysa то, что я сейчас пытаюсь сделать, — это get_room_mapping .

@rytilahti отлично. Я не уверен, в чем именно разница, но провайдер python-miio, похоже, вообще не работает, и miio2 работал с первой секунды. Покопаюсь, когда узнаю, как получить список комнат :)

Хорошая вещь! Удалось ли вам запускать произвольные команды через домашний помощник, например

curl -X POST -H "Authorization: Bearer REDACTED" -H "Content-Type: application/json" https://HASS:8123/api/services/vacuum/send_command -d '{"entity_id": "NAME", "command": "get_prop", "params": ["cur_mapid"]}'

?

Ваши ссылки кажутся очень информативными, пройдемся по ним позже :)

@BackSlasher на самом деле нет, я просто запускаю некоторые команды из инструментов / служб разработчика и настраиваю базовые автоматы на пылесос / моб мою квартиру.

Выбрать программу несложно:
команда: set_mode
параметры: 1 -> моб / вакуум 0 -> просто вакуум

@BackSlasher

для карты, может быть, это поможет.

Привет,
Я столкнулся с проблемой, позвольте мне описать. Токен был извлечен с помощью приложения MiHome 5.6.50 с модификацией Android (RU). Дальнейшее тестирование на свежем Raspbian.

Полученные результаты:
Использование «mirobo» Viomi V2 Pro классифицируется как версия «v6», где я где-то видел, что его клон Xiaomi STYJ02YM классифицируется как viomi.vacuum.v7.

pi<strong i="9">@raspberrypi</strong>:~ $ mirobo discover
INFO:miio.discovery:Discovering devices with mDNS, press any key to quit...
WARNING:miio.discovery:Found unsupported device viomi-vacuum-v6_miio309159813._miio._udp.local. at 192.168.0.42, please report to developers
pi<strong i="12">@raspberrypi</strong>:~ $ mirobo --ip 192.168.0.42 --token xxxx status
ERROR:miio.miioprotocol:Got error when receiving: timed out
Error: No response from the device

Используя «miiocli», я смог получить данные.

pi<strong i="16">@raspberrypi</strong>:~ $ miiocli viomivacuum --ip 192.168.0.42 --token xxxx status
State: ViomiVacuumState.Idle
Mode: 0
Error: None
Battery: 42
Fan speed: ViomiVacuumSpeed.Silent
Box type: 1
Mop type: 0
Clean time: 0:00:00
Clean area: 0
Water level: 11
Remember map: True
Has map: True
Has new map: False
Mop mode: ViomiMopMode.Off

Я также мог запускать / останавливать, однако через 10-15 минут что-то ломается, и я больше не могу получать данные, пока не включу вручную Viomi.

pi<strong i="20">@raspberrypi</strong>:~ $ miiocli viomivacuum --ip 192.168.0.42 --token xxxx info
ERROR:miio.miioprotocol:Got error when receiving: timed out
Error: No response from the device

Есть идеи, что это может быть? Благодарю, если кто-то может помочь мне с этой темой / интеграцией, я могу предоставить необходимые результаты. Моя цель — запустить его на Domoticz :).

Спасибо,
Ваше здоровье

Полагаю, это другой пароль.
Знает ли кто-нибудь, где можно найти документацию?

@polysa Возвращаясь к этому, вы нашли способ убрать определенную комнату?
Пробовал копировать с https://github.com/rytilahti/python-miio/issues/550 , но лучшее, что я мог придумать, — это miio protocol call IPISHERE set_mode_withroom '[0, 1, 1, 4]' в чистую комнату 4, которая печатает

 INFO  Got result:
[
  "ok"
]

и заставляет пылесос покидать док-станцию ​​и немедленно возвращаться

@BackSlasher

Вот сценарий, который я использую для уборки в столовой:

`Vacuum_dinningroom:
псевдоним: Чистая столовая
последовательность:

  • данные:
    команда: set_mode_withroom
    параметры:

    • 0
    • 1
    • 1
    • 11

      entity_id: Vacuum.viomi

      сервис: Vacuum.send_command`

Пришлось вручную тестировать код для каждой комнаты. Мои комнаты начинаются с номера 10 и выше.

Последнее обновление прошивки, поддерживающее многоуровневые карты этажей, делает Viomi непригодным для использования, и я не могу найти способ откатиться :(

Не устанавливайте последнюю версию прошивки, попался :)
Будет перебирать номера комнат. Пока что Вакуум еще уходит и сразу возвращается :)

Не устанавливайте последнюю версию прошивки, попался :)
Будет перебирать номера комнат. Пока что Вакуум еще уходит и сразу возвращается :)

Процесс идентификации комнат был следующим:

  1. не переименовывайте комнаты в приложении.
  2. Моя столовая была отмечена в приложении цифрой 1. так что мне в HA 11

комната 2 будет 12 и так далее. Я не уверен в этом шаблоне, но он работает для меня.

Держитесь подальше от прошивки 3.5.8_0033 Я дам вам знать, как только получу новую прошивку без ошибок.

Я подумал, что это будет мой процесс. Я не переименовал комнаты, просто объединил их, но я вижу некоторые странные несоответствия (я думаю, что комната 11 в API — это «room4» в пользовательском интерфейсе.
Однако кажется, что комната 15 — это комната 5, так что остается еще много загадок :)

РЕДАКТИРОВАТЬ: комната 15 в API на самом деле является комнатой 8 в пользовательском интерфейсе. Удивительный

image

Хорошо, только что вспомнил, что вам нужно отправлять пылесос в док перед каждым тестом. Поэтому, если вы отправляете с помощью команды из док-станции в комнату 1 (11), вам нужно состыковать, прежде чем отправлять ее в комнату 2 (12).

Да, я об этом. Я думаю, что пользовательский интерфейс повторно использует самый низкий roomid, а API — нет. Итак, из-за массового повторного редактирования комнат, которые я сделал, числа не совпадают.

11 = room4
15 = room8
18 = room3
19 = X
20 = X
21 = X
22 = room0

Это мое отображение на данный момент. Знаю, захватывающе.

РЕДАКТИРОВАТЬ: Готово с отображением! Хорошая вещь :)

Идеально. Они думают, что мне не хватает моей настройки в HA, это живая карта. Наверное, я начну работать над этим, теперь я застрял дома.

Нет ничего лучше, чем заняться домашней автоматизацией :)

Кстати, я думаю, что карта будет действительно сложной, если вы не рутированы. Я боюсь рутировать свое устройство, так как я не могу заставить свой порт adb работать.

См. Мой предыдущий ответ выше: # 597 (комментарий) . Если вы используете miiocli из domoticz, проблема заключается в повторном использовании msgid в этом инструменте.

@BackSlasher @polysa : вроде у тебя почти все работает !? Я застрял с ошибкой идентификатора сообщения — как вы решили эту проблему?

@ crazykiwi2003 Я проверил свой токен, используя версию miio для npm, и использовал ее для отправки команд устройству.
Тот Python, который я использую только вместе с homeassistant, используя решение miio2, упомянутое в https://github.com/rytilahti/python-miio/issues/597#issuecomment -575983172
После правильной работы интеграции с HASS вы можете использовать там службу ( vacuum.send_command для отправки материалов в вакуум с меньшей вероятностью конфликта msgid.
Обратной стороной использования сервиса является то, что вы не видите ответа — только наблюдайте за вакуумом и посмотрите, делает ли он что-нибудь интересное.
Вот команда, которую вы можете использовать, чтобы увидеть, работает ли базовая связь с вакуумом.

miio protocol call IPIPIPIPIP get_prop '["mode"]'

Для меня это возвращается

 INFO  Attempting to call get_prop on IPIPIPIPIP

 INFO  Device found, making call

 INFO  Got result:
[
  0
]

Привет
У меня viomi v2 pro и вчера я установил обновление 3.5.8_0034, все прошло хорошо, за исключением того, что в Y больше нет стирки, она моет только в S.
Как смыть обратно в Y, пожалуйста?

Прошивка 3.5.8_0034
E60FC0FD-EB82-4FD9-8545-30737F59DE51

Прошивка 3.5.3_0030
CB898838-3A12-4362-9AF3-43042FB88E33

С наилучшими пожеланиями

Вы не можете. это ошибка. Пожалуйста, эта тема предназначена для интеграции Home Assistant с python-miio. Свяжитесь с Виоми из Facebook.

Вы не можете. это ошибка. Пожалуйста, эта тема предназначена для интеграции Home Assistant с python-miio. Свяжитесь с Виоми из Facebook.

хорошо, извини, спасибо. их фейсбук — это «viomi tech», пожалуйста?

Вы не можете. это ошибка. Пожалуйста, эта тема предназначена для интеграции Home Assistant с python-miio. Свяжитесь с Виоми из Facebook.

хорошо, извини, спасибо. их фейсбук — это «viomi tech», пожалуйста?

да исправить

Закрытие, потому что я получил свои ответы. @polysa, пожалуйста, отправьте мне CC, когда у вас будет интересный прогресс :)

Была ли эта страница полезной?

0 / 5 — 0 рейтинги

Hello, this will be a Home Assistant Xiaomi Vacuum Cleaner integration tutorial. The same method can be applied for several other Xiaomi products like:

  • Xiaomi Gateways,
  • Xiaomi Air Purifiers,
  • Xiaomi IR Remotes,
  • Xiaomi WiFi repeaters,
  • Xiaomi Smart plugs and more.

For dessert we will create some Home Assistant automations and scripts to control our Xiaomi Robot Vacuum Cleaner locally.

Let’s start…

Home Assistant Xiaomi Vacuum Cleaner Integration (HOW-TO)

What this article is about?

This article will not be a Xiaomi Robot Vacuum cleaner review. Instead we will focus on Home Assistant Xiaomi integration by extracting the Xiaomi Access Token that is is needed by Home Assistant to control the Xiaomi Robot Vacuum Cleaner and other devices stated above.

We will also make some Home Assistant automations just as a hint of what is possible when we finish that integration.

What I’m going to use?

As example I’m going to use Xiaomi Mi Robot Vacuum-Mop Pro, which looks like this.

The robot that we are going to test 😂
I’m wondering can I integrate that to Home Assistant?

I’m kidding it is this one.

Home Assistant Xiaomi Robot Vacuum Mop Pro Integration will start in few seconds
Home Assistant Xiaomi Robot Vacuum Mop Pro Integration will start in few seconds

Here are few affiliate links where you can check the best price and shipping for your region if you want to buy the same:

  • Xiaomi Robot Vacuum Mop Pro (AliExpress Affiliate 1) 👉 LINK
  • Xiaomi Robot Vacuum Mop Pro (AliExpress Affiliate 2) 👉 LINK
  • Xiaomi Robot Vacuum Mop Pro (AliExpress Affiliate 3) 👉 LINK
  • Xiaomi Robot Vacuum Mop Pro (AliExpress Affiliate 4) 👉 LINK
  • Xiaomi Robot Vacuum Mop Pro (Amazon UK Affiliate) 👉 LINK

As I said in the beginning of the article there are a lot of Xiaomi Products that can be integrated almost the same way. Here is the full list:

  • Supported Xiaomi Gateway Models – LINK
  • Supported Xiaomi Air Purifiers and Humidifiers – LINK
  • Supported Xiaomi Philips Light – LINK
  • Supported Xiaomi Smart WiFi Socket and Smart Power Strip – LINK

Mi Home mobile App

To complete this tutorial you will need an Access Token and Mi Home mobile app. Now is the best time to add your Xiaomi device to the Mi Home mobile app.

This is easy and straightforward task:

  1. Download the Mi Home app on your mobile device:
    1. Mi Home App for iOS 👉 LINK
    2. Mi Home App for Android 👉 LINK
  2. Start it!
  3. Follow the instructions there for the initial device setup.

Xiaomi Access Token

There are several ways to get your Xiaomi Access Token. I will show you some of these methods and the whole idea here is to choose a method that suits you best.

When you get your token by either of the ways you can go directly to the Home Assistant Integration part 👉 LINK

Quick Hint

Some people are saying that if you smash my Newsletter Subscribe button so hard that you receive a confirmation mail, and you actually click on the confirmation link after that – you will get your Xiaomi access token in no time.

Just kidding here, but please consider seriously about subscribing for my newsletter – I won’t spam.

Let’s see the first method of Xiaomi access token extraction.

Extract Xiaomi Access Token – 1st method

You will need pip3 (python package manager) for this method. To check if you already have pip3 – open a Terminal if you are running Linux/macOS or command prompt in Windows and type:

pip3
  • If you see an error – Google how to install pip3 on your Operating System.
  • If you see the pip3 help screen you can continue forward.

Next step is to get all dependencies by executing:

pip3 install pycryptodome pybase64 requests

You will also need a git client or you can download the Project as ZIP from the GitHub repo and extract the archive on your computer. The result is the same.

This is how you can get the needed files using git client and git clone command:

git clone https://github.com/PiotrMachowski/Xiaomi-cloud-tokens-extractor.git

Enter inside the downloaded/cloned folder:

cd Xiaomi-cloud-tokens-extractor

Start the tool with python:

python3 token_extractor.py

Alternatively you can start the tool using Docker, but you have to have up & running Docker client for that:

docker run --rm -it $(docker build -q .)

After you start the tool either by using Python or Docker you have to enter your Mi Home App credentials.

When the script ask you to choose a server – just Hit Enter and the tool will auto check all Xiaomi servers. At the end you should see all of your Xiaomi devices, their IP’s, models, and most importantly their Tokens. Which is exactly what we need.

Extract Access Token that is needed for Home Assistant Xiaomi Vacuum integration

Extract Access Token that is needed for Home Assistant Xiaomi Vacuum integration

Extract Xiaomi Access Token – 2nd method

The second method for Xiaomi Access Token extraction is even easier than the first one, but it’s only working on Windows and macOS.

  • Go to https://github.com/Maxmudjon/Get_MiHome_devices_token/releases
  • Download and start the Get Mi Home Devices Token App (it is the zip archive)
  • Start the App
  • Log in with your Mi Home e-mail and password and click Sign in button
Even easier method for extracting the Xiaomi Access Token for the Home Assistant Xiaomi Vacuum integration
Even easier method for extracting the Xiaomi Access Token for the Home Assistant Xiaomi Vacuum integration

You will see a compete list of your Xiaomi Devices and their tokens 🤩

We have the Xiaomi Access Token! Now let’s finish this Home Assistant Xiaomi Vacuum Mop Pro integration.

Again we have two methods for the Home Assistant Xiaomi Vacuum integration:

  1. Using the xiaomi_miio platform which is embedded in Home Assistant – LINK
  2. Using a custom component 👉 LINK

The first method is preferred, as there is better chance if it worked once to work for a long time without issues. It all depends of your Xiaomi Device and model here.

Unfortunately, the first method didn’t worked for me (Xiaomi Robot Vacuum Mop P/Pro) and I have to use the second method, which turns out to work flawlessly at least for now.

MY RECOMMENDATION: Start with the first method and only if it is not working for you – go for the second method.

After we finish (regardless of the method) we will be able to give commands to our device like: start, stop, pause, return to base, locate, clean spot, set fan speed and more.

Home Assistant Xiaomi Vacuum integration – 1st method

Open your configuration.yaml file in your Home Assistant config folder and paste the following YAML code inside:

# configuration.yaml entry
vacuum:
  - platform: xiaomi_miio
    host: 192.168.1.2
    token: YOUR_TOKEN

Replace the 192.168.1.2 with your Xiaomi device IP, and YOUR_TOKEN with your real token that you get from the above steps. Save the file and restart the Home Assistant.

After Home Assistant Starts, go to Developer Tools > Services and try to invoke vacuum.start service with your new Xiaomi Entity as shown in the picture below:

Testing the Home Assistant Xiaomi vacuum integration - method 1
Testing the Home Assistant Xiaomi vacuum integration – method 1

If your Xiaomi Robot Vacuum start cleaning, then everything is fine and you can skip method 2 and you can go directly to the Home Assistant Xiaomi vacuum automation part.

Home Assistant Xiaomi Vacuum integration – 2nd method

Do this part only if the Home Assistant Xiaomi Vacuum integration – 1st method didn’t worked for you.

Go to https://github.com/nqkdev/home-assistant-vacuum-styj02ym and download the project as ZIP

Home Assistant Xiaomi Vacuum Cleaner Integration (HOW-TO) 1

Extract the files and copy them under /custom_components/miio2 folder inside your Home Assistant configuration folder. If you don’t have such folders – create them

Then open your configuration.yaml file, remove the vacuum section from the first method if it is still there and and paste the following:

# configuration.yaml entry
vacuum:
  - platform: miio2
    host: 192.168.1.2
    token: YOUR_TOKEN
    name: Mi hihi

Replace the 192.168.1.2 with your Xiaomi device IP, and YOUR_TOKEN with your real token that you have from the above steps. Save the file and restart the Home Assistant.

Go to Developer Tools > Services and try to invoke vacuum.start service with your new Xiaomi Entity. If everything is fine, then Xiaomi Robot Vacuum will start cleaning.

Good job 👍

Create a Home Assistant Xiaomi Automation

Let’s create a Home Assistant automation that will start the Xiaomi Robot Vacuum Cleaner when Elvis has left the building.

Start Xiaomi Robot Vacuum Cleaner when Elvis leave the building.
Start Xiaomi Robot Vacuum Cleaner when Elvis leave the building automation.

I’m kidding when a person leave the house.

And as always you can use the Home Assistant Graphical Automations Editor as I’m showing in my video or you can edit the automations.yaml file as I will show here.

Open the automations.yaml file and paste the following YAML lines:

- id: '1613942351983'
  alias: Start vacuum when I leave home
  description: ''
  trigger:
  - platform: state
    entity_id: person.kiril
    from: home
    to: not_home
  condition: []
  action:
  - service: vacuum.start
    data: {}
    entity_id: vacuum.mi_hihi
  mode: single

Replace person.kiril with your entity_id that you want to track and vacuum.mi_hihi with your vacuum cleaner entity.

Save the file and reload the automations. Now when person.kiril goes from home to not_home the Xiaomi Robot Vacuum Cleaner will start cleaning automatically.

You can of course add conditions and complications to this automation to make it really useful for your needs.

Reset Xiaomi maintenance hours with Home Assistant

You can reset maintenance hours of the Xiaomi Robot Vacuum Mop Pro using Home Assistant scripts.

This is the link to Home Assistant documentation about how you can do that 👉 LINK

Home Assistant Xiaomi vacuum card

You also can create a card to your Home Assistant Lovelace for your robot vacuum. The author of the card claims that it supports the following brands/models: Xiaomi, Roomba, Neato, Robovac, Valetudo, Ecovacs, Deebot.

And here is the GitHub page and instructions about how you can do that 👉 LINK

Question for You!

My question for you is very simple. Do you have any Xiaomi devices at your home and if yes what exactly?

Let me know in the comments below.

Except the Xiaomi Robot Vacuum Mop Pro I also have 3 Xiaomi Xiaofanng cameras which I mounted at my parents work place and they work just fine.

Support My Work!

If you want to secure this blog existence you can become one of my supporters. You can see exactly how in this section of my site.

I can’t thank enough to all wonderful guys that are supporting my work already – you are amazing!

Any other sort of engagement on this site and my YouTube channel does really help out a lot with the Google & YouTube algorithms, so make sure you:

  • Hit the subscribe for my weekly newsletter 🗞 
  • As well as the Like and Bell buttons 👍🔔

If you are just entering the Smart Home world you could also buy my digital product called: Smart Home – Getting Started Actionable Guide 👉 LINK

Also feel free to add me on Twitter by searching for @KPeyanski.  You can find me on my Discord server as well.

Stay safe and don’t forget – Home Smart, But Not Hard!

Hello-

I recently bought a Roborock E25, successfully got the token and added it to Home Assistant using the xiaomi_miio.vacuum integration. It was working well. Then, I noticed a few days ago that it had disappeared from the front end. Checking the log at HA restart, I see:

«`

2020-07-23 07:26:16 INFO (MainThread) [homeassistant.components.xiaomi_miio.vacuum] Initializing with host 192.168.86.21 (token a6640...)

2020-07-23 07:26:17 DEBUG (MainThread) [homeassistant.components.xiaomi_miio.vacuum] Unable to find reverse for 102

2020-07-23 07:26:17 ERROR (MainThread) [homeassistant.components.vacuum] Error while setting up xiaomi_miio platform for vacuum

Traceback (most recent call last):

File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 186, in _async_setup_platform

await asyncio.gather(*pending)

File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 292, in async_add_entities

await asyncio.gather(*tasks)

File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 451, in _async_add_entity

entity.async_write_ha_state()

File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 290, in async_write_ha_state

self._async_write_ha_state()

File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 317, in _async_write_ha_state

attr.update(self.device_state_attributes or {})

File "/usr/src/homeassistant/homeassistant/components/xiaomi_miio/vacuum.py", line 333, in device_state_attributes

if self.timers:

File "/usr/src/homeassistant/homeassistant/components/xiaomi_miio/vacuum.py", line 284, in timers

for timer in self._timers

File "/usr/src/homeassistant/homeassistant/components/xiaomi_miio/vacuum.py", line 284, in <listcomp>

for timer in self._timers

File "/usr/local/lib/python3.7/site-packages/miio/vacuumcontainers.py", line 444, in next_schedule

local_tz = timezone(self.timezone)

File "/usr/local/lib/python3.7/site-packages/pytz/__init__.py", line 163, in timezone

if zone.upper() == 'UTC':

AttributeError: 'dict' object has no attribute 'upper'

The configuration.yaml entry is. (Indentations is correct in the actual config file. I can’t figure out how to make them appear properly here…)

vacuum

- platform: xiaomi_miio

host: 192.168.86.21

token: a6640aaa1cf74d2dxxxxxxxa7e7763f2

`name: ‘Vacuum Dexter’«

I’m not sure exactly when it disappeared, so I can’t link it to any possible change with HA.

I have tried the obvious like checking that the IP hasn’t changed (set as static but just in case), that it works with the Xiaomi app, power cycling, etc.

Any suggestions? Thanks


The xiaomi miio vacuum platform allows you to control the state of your Xiaomi Mi Robot Vacuum.

Currently supported features are:

  • turn_on
  • pause
  • stop
  • return_to_home
  • turn_off (stop all activity and return to dock)
  • locate
  • clean_spot
  • set_fan_speed
  • remote control of your robot.

Please follow Retrieving the Access Token to retrieve the API token used in
configuration.yaml.

Configuring the Platform

To add a vacuum to your installation, add the following to configuration.yaml:

vacuum:
  - platform: xiaomi_miio
    host: 192.168.1.2
    token: YOUR_TOKEN

Configuration variables:

  • host (Required): The IP of your robot.
  • token (Required): The API token of your robot.
  • name (Optional): The name of your robot.

Platform Services

In addition to all of the services provided by the vacuum component (turn_on, turn_off, start_pause, stop, return_to_home, locate, set_fan_speed and send_command), the xiaomi platform introduces specific services to access the remote control mode of the robot. These are:

  • xiaomi_remote_control_start
  • xiaomi_remote_control_stop
  • xiaomi_remote_control_move
  • xiaomi_remote_control_move_step

Service vacuum.xiaomi_remote_control_start

Start the remote control mode of the robot. You can then move it with remote_control_move; when done, call remote_control_stop.

Service data attribute Optional Description
entity_id yes Only act on specific robot; default targets all

Service vacuum.xiaomi_remote_control_stop

Exit the remote control mode of the robot.

Service data attribute Optional Description
entity_id yes Only act on specific robot; default targets all

Service vacuum.xiaomi_remote_control_move

Remote control the robot. Please ensure you first set it in remote control mode with remote_control_start.

Service data attribute Optional Description
entity_id yes Only act on specific robot; default targets all
velocity no Speed: between -0.29 and 0.29
rotation no Rotation: between -179 degrees and 179 degrees
duration no The number of seconds that the robot should move for

Service vacuum.xiaomi_remote_control_move_step

Enter remote control mode, make one move, stop, and exit remote control mode.

Service data attribute Optional Description
entity_id yes Only act on specific robot; default targets all
velocity no Speed: between -0.29 and 0.29.
rotation no Rotation: between -179 degrees and 179 degrees.
duration no The number of seconds that the robot should move for

Attributes

In addition to all of the attributes provided by the vacuum component,
(battery_icon, cleaned_area, fan_speed, fan_speed_list, status, and params), the xiaomi platform introduces specific attributes. These are:

  • cleaning_time
  • do_not_disturb
  • main_brush_left
  • side_brush_left
  • filter_left
  • cleaning_count
  • total_cleaned_area
  • total_cleaning_time

The following table shows the units of measurement for each attribute:

Attribute Unit of measurement Description
do_not_disturb   DND mode on / off
cleaning_time minutes Last / actual cleaning time in minutes
cleaned_area square meter Last / actual cleaned area in square meters
main_brush_left hours Hours left until a change of the main brush is needed
side_brush_left hours Hours left until a change of the side brush is needed
filter_left hours Hours left until a change of the filter is needed
cleaning_count   Number of total cleaning cycles
total_cleaned_area square meter Total cleaned area in square meters
total_cleaning_time minutes Total cleaning time in minutes

Retrieving the Access Token

As per python-miio issue 185 the Mi-Home app no longer stores the token within the database (it’s retrieved from Xiaomi servers from version 5.0.31+). Currently the only known fix is to uninstall, then install a downgraded version of the apk. Apkmirror is a trusted source for older versions of the app. Mi-Home version 5.0.0 is confirmed as working for the following Android methods.
This token (32 hexadecimal characters) is required for the Xiaomi Mi Robot Vacuum, Xiaomi Philips Lights and Xiaomi IR Remote. The Xiaomi Gateway uses another security method and requires a key (16 alphanumeric chars), which can be obtained
easily via a hidden menu item at the Mi-Home app or using the miio command line tool.

Miio command line tool

You can install the command line tool with:

Discovering devices on current network

This will list devices that are connected to the same network as your computer. Let it run for a while so it has a chance to reach all devices, as it might take a minute or two for all devices to answer.

The commands outputs each device on this format:

Device ID: 48765421
Model info: zhimi.airpurifier.m1
Address: 192.168.100.9
Token: token-as-hex-here via auto-token
Support: At least basic

The information output is:

  • Device ID — the unique identifier of the device, does not change if the device is reset.
  • Model ID — the model id if it could be determined, this indicates what type of device it is
  • Address — the IP that the device has on the network
  • Token — the token of the device or ??? if it could not be automatically determined

Windows and Android

To fetch the token follow these instructions depending on your mobile phone platform.

  1. Configure the robot with the Mi-Home app.
  2. Download and extract the MiToolKit.zip.
  3. Enable developer mode and USB debugging on the Android phone and plug it into the computer.
  4. Change the MiToolKit language to English if you need to.
  5. Click “Extract Token”
  6. On the phone, you must confirm the backup. DO NOT enter any password and press the button to make the backup.
  7. Once you have confirmed the backup the token extraction will begin, it should appear in the MiToolKit shortly.

Linux and Android (not rooted)

Follow the pairing process using your phone and Mi-Home app. You will be able to retrieve the token from a SQLite file inside your phone.

Before you begin you need to install libffi-dev and libssl-dev by running the command below. This is needed for python-miio to be installed correctly.

$ sudo apt-get install libffi-dev libssl-dev

If your Home Assistant installation is running in a Virtualenv, make sure you activate it by running the commands below.

$ sudo su -s /bin/bash homeassistant
$ source /srv/homeassistant/bin/activate

To fetch the token follow these instructions depending on your mobile phone platform.

  1. Configure the robot with the Mi-Home app.
  2. Enable developer mode, USB debugging and plug the Android phone into the computer.
  3. Get ADB e.g. apt-get install android-tools-adb or apt-get install adb
  4. adb devices should list your device. Consult ADB manual if necessary.
  5. Issue a backup command via adb: adb backup -noapk com.xiaomi.smarthome -f backup.ab (set a password if prompted on your phone). Some devices may required single quotes in the command adb backup '-noapk com.xiaomi.smarthome -f backup.ab'
  6. Download the ‘ADB Backup Extractor’ from here
  7. Extract the data from the backup: java -jar Android Backup Utilities/Android Backup Extractor/android-backup-extractor-20171005-bin/abe.jar unpack backup.ab unpacked.tar (enter the password, if prompted)
  8. Untar the unpacked data: tar -xvf unpacked.tar
  9. sqlite3 apps/com.xiaomi.smarthome/db/miio2.db 'select token from devicerecord where name = "Mi Robot Vacuum";' returns the token for your Xiaomi vacuum bot.

Linux and Android (rooted!)

Follow the pairing process using your phone and Mi-Home app. You will be able to retrieve the token from a SQLite file inside your phone.

Before you begin you need to install libffi-dev and libssl-dev by running the command below. This is needed for python-miio to be installed correctly.

$ sudo apt-get install libffi-dev libssl-dev

If your Home Assistant installation is running in a Virtualenv, make sure you activate it by running the commands below.

$ sudo su -s /bin/bash homeassistant
$ source /srv/homeassistant/bin/activate

To fetch the token follow these instructions depending on your mobile phone platform.

  1. Configure the robot with the Mi-Home app.
  2. Enable developer mode, USB debugging and root permission only for ADB on the Android phone and plug it into the computer.
  3. Get ADB f.e. apt-get install android-tools-adb
  4. adb devices should list your device
  5. adb root (does work for development builds only: ones with ro.debuggable=1)
  6. adb shell (for those using Magisk based root the previous command won’t work. After entering a shell, type su to enter the root shell)
  7. echo "select name,localIP,token from devicerecord;" | sqlite3 /data/data/com.xiaomi.smarthome/databases/miio2.db returns a list of all registered devices including IP address and token.

iOS

  1. Configure the robot with the Mi-Home app.
  2. Using iTunes, create an unencrypted backup of your iPhone.
  3. Install iBackup Viewer, open it, and open your backup.
  4. Open the “Raw Data” module.
  5. Navigate to com.xiaomi.mihome.
  6. Search for a file that looks like this: 123456789_mihome.sqlite – note that _mihome.sqlite is not the correct file.
  7. Save this file to your filesystem.
  8. Install DB Browser for SQLite.
  9. Open DB Browser and load the .sqlite file you saved from your backup.
  10. Click on the Execute SQL tab.
  11. Input and run this query: SELECT ZTOKEN FROM ZDEVICE WHERE ZNAME = "Mi Robot Vacuum"
  12. Copy the returned 32-digit hexadecimal string to your clipboard.
  13. Open Terminal and execute this command: echo '0: <YOUR HEXADECIMAL STRING>' | xxd -r -p | openssl enc -d -aes-128-ecb -nopad -nosalt -K 00000000000000000000000000000000
  14. Use the resulting string as your token.

Понравилась статья? Поделить с друзьями:
  • Playstation app произошла ошибка
  • Platform error bad module serverbrowser dll not loading что делать
  • Playstation 5 ошибка ce 108255 1
  • Plants vs zombies ошибка fatal error
  • Playstation 4 ошибка su 41333 4