Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 414ae81041 | |||
| 05818b8c23 | |||
| d74ec5dc6a | |||
| 3caa4c1127 | |||
| d92acfc027 | |||
| d2976d1cf1 | |||
| dedf805e6e | |||
| 5ff93266a2 | |||
| 4add2020d9 | |||
| aac3d0f31e | |||
| 27b9bc4afe | |||
| 5a3cc283be | |||
| 0170a9e177 | |||
| bc6e174d3f | |||
| 3e9410fbb6 | |||
| f02ba3310a | |||
| 07ed6100a9 | |||
| ec5f598330 | |||
| bdc9ee4c0a | |||
| 6d703780e6 | |||
| a1356f2652 | |||
| fde7ee9d5f | |||
| 9d8ee5eb49 | |||
| 5eb86f5960 | |||
| 1ed7eeaea2 | |||
| 5f0a21fd93 | |||
| 906007a290 | |||
| c371f1ffd0 | |||
| 70bf423c5c | |||
| 1f0a83ec7d | |||
| 09fa332fb0 | |||
| dc11383d3e | |||
| da3b2b0ec2 | |||
| 859c0c02f4 | |||
| 16a6e3379c | |||
| ea8e7f37a7 | |||
| 32e93de62f | |||
| 6d28fd4ec1 | |||
| 596981325d | |||
| 0725046971 | |||
| fbec024ebb | |||
| 8c032651a2 | |||
| 99c11a5b04 | |||
| e4273d7ea4 | |||
| 7ce31c4b2c | |||
| f3b6bc0ff8 | |||
| 3fc0204c2c | |||
| 5ad3a0b928 | |||
| 5727372268 | |||
| c749bca96c | |||
| c681fb4c75 | |||
| bd83dae3a2 | |||
| d18a93cc55 | |||
| 6471f86163 | |||
| 0f2d5f38f5 | |||
| 5bc6802aae | |||
| 9daaaf9040 | |||
| c3841c63ba | |||
| c8cc6f20bc | |||
| 1311546ed4 |
-16
@@ -1,19 +1,3 @@
|
||||
__pycache__
|
||||
Pipfile
|
||||
Pipfile.lock
|
||||
scratch*
|
||||
.idea
|
||||
build
|
||||
dist
|
||||
|
||||
# Nosetests files
|
||||
cover/
|
||||
.coverage
|
||||
|
||||
# Ignore Vscode files
|
||||
.vscode/
|
||||
|
||||
# Ignore sucks.egg-info
|
||||
sucks.egg-info/
|
||||
.noseids
|
||||
nosetests.xml
|
||||
|
||||
@@ -1,81 +1,52 @@
|
||||
# Home Assistant Ecovacs Custom Component with Bumper Support
|
||||
Based off the regular home assistant ecovacs components and bmartin's fork of sucks, https://github.com/bmartin5692/sucks. Replaces built in ecovacs component, with some upgrades and fixes. Allows SSL verification to be set to false to work with a self-hosted bumper server, https://github.com/bmartin5692/bumper, a replacement for Ecovacs servers to truly get local control.
|
||||
Replaces built in ecovacs component.
|
||||
|
||||
Works with bumper with my N79 and should work with other XMPP based ecovacs. Catches some XMPP messages now that the default HASS one misses (at least with my Ecovacs), including some initial queries and also life span for filters and brushes. Includes MQTT robot support from bmartin's fork that's basically unchanged in this since I don't have one of those robots.
|
||||
Works with bumper with my N79 and should work with at least other XMPP based ecovacs. Don't know if changes will work with MQTT based ones.
|
||||
|
||||
Should work as regular without bumper if verify_ssl is true or omitted in config but haven't tested yet, goal was to get it all local. Maybe mess around and test it in future.
|
||||
Added additional catches to sucks because my N79 sends some weird payloads, but attributes all pull in now for brush life spans. Couple initial queries it also sends weird that I'm in process of catching atm. As of version 1.3.0 (in the manifest.json) these initial queries and all attributes are working. Was using an implementation completely mine but saw in the MQTT class there were already catches for child payloads without the main payload having the expected td in its payload. Kept comments in giving credit and adapted them to work with xmpp.
|
||||
|
||||
## Bumper Setup
|
||||
Check out bmartin's docs to setup a bumper server, https://bumper.readthedocs.io/.
|
||||
With bumper and my N79 commands would work but some queries had responses that included errno='', which bumper would flag as an error even though the full response was there. If your debug logs are throwing errors and the errno is '' then my small fork of bumper may help https://github.com/bittles/bumper-fork
|
||||
|
||||
Should work as regular if bumper isn't used in config but haven't tested yet, goal was to get it all local. Maybe mess around and test it in future.
|
||||
|
||||
I'm using the docker-compose example for bumper by bmartin5692, https://github.com/bmartin5692/bumper on an odroid-n2+.
|
||||
|
||||
For DNS routing I have an Asus AX88u with asus-merlin installed running Adguard. DNS rewrites in AdGuard for domains:
|
||||
```
|
||||
*.ecouser.net
|
||||
*.ecovacs.com
|
||||
*.ecovacs.net
|
||||
```
|
||||
pointing to my bumper server.
|
||||
|
||||
Big credits to bmartin5692 for his fork of sucks to base this off of as well.
|
||||
|
||||
## Home Assistant Install & Config
|
||||
### HACS Install
|
||||
You can add this repository to your HACS: https://github.com/bittles/ha_ecovacs_bumper
|
||||
|
||||
Then download with HACS, HACS -> Integrations -> Explore & Download Repositories -> EcovacsBumper
|
||||
|
||||
Drop the ecovacs folder into your custom_components folder. If I polish this up I'll add hacs support.
|
||||
Restart HASS.
|
||||
|
||||
### Manually Install
|
||||
Drop the ecovacs folder into your custom_components folder.
|
||||
In your configuration.yaml:
|
||||
```
|
||||
ecovacs:
|
||||
username:
|
||||
password:
|
||||
country:
|
||||
continent:
|
||||
bumper: true/false (optional, defaults false)
|
||||
bumper_server: (optional, defaults null)
|
||||
verify_ssl: true/false, false if using bumper (optional, defaults true)
|
||||
```
|
||||
Any username, password, country, and continent should work if bumper is true. Set bumper_server to the ip_address where you're running bumper and set verify_ssl to false for bumper. If you're not using bumper this SHOULD technically work no different than the Home Assistant ecovacs integration but I haven't looked at it enough to be sure and I haven't tested it.
|
||||
|
||||
Restart HASS.
|
||||
|
||||
### Config
|
||||
Example in configuration.yaml:
|
||||
### Example Config
|
||||
```
|
||||
ecovacs:
|
||||
username: bumper
|
||||
password: bumper
|
||||
country: us
|
||||
continent: na
|
||||
bumper: true
|
||||
bumper_server: "192.168.1.55"
|
||||
verify_ssl: false
|
||||
```
|
||||
If you're not using bumper this SHOULD technically work no different than the Home Assistant ecovacs integration but I haven't tested it.
|
||||
|
||||
| Paremeter | Description | Required/Optional |
|
||||
| --- | --- | --- |
|
||||
| username | Ecovacs username, can be anything if using bumper | required |
|
||||
| password | Ecovacs password, can be anything if using bumper | required |
|
||||
| country | Ecovacs country, can be anything if using bumper | required |
|
||||
| continent | Ecovacs continent, can be anything if using bumper | required |
|
||||
| verify_ssl | true/false, defaults to true. Use false if using bumper | optional |
|
||||
|
||||
#### Country/Continent Values and Pairs
|
||||
From the HASS ecovacs integration page:
|
||||
|
||||
```
|
||||
Note: For some countries, you will need to set continent to ww (meaning worldwide.)
|
||||
There is unfortunately no way to know the correct settings other than guessing and checking.
|
||||
See the py-sucks library protocol documentation for more information about what has been figured out about the Ecovacs servers.
|
||||
|
||||
Additional note: There are some issues during the password encoding.
|
||||
Using some special characters (e.g., -) in your password does not work.
|
||||
```
|
||||
|
||||
From the sucks documentation:
|
||||
|
||||
| country code | matching continent code |
|
||||
| --- | --- |
|
||||
| CH | ww or as |
|
||||
| TW, MY, JP, SG, TH, HK, IN, KR | as |
|
||||
| US | na |
|
||||
| FR, ES, UK, NO, MX, DE, PT, CH, AU, IT, NL, SE, BE, DK | eu |
|
||||
| Any other country code | ww |
|
||||
|
||||
### Logging
|
||||
If your debug logs are throwing errors and the errno is '' then my small fork of bumper may help https://github.com/bittles/bumper-fork, which also includes ability to disable the XMPP or MQTT servers seperately if you don't own a robot that uses that protocol.
|
||||
```
|
||||
logger:
|
||||
logs:
|
||||
sleekxmpss: debug
|
||||
custom_components.ecovacs.sucksbumper: debug # or whatever level you want
|
||||
```
|
||||
|
||||
### To-Do:
|
||||
Make component async, use config_flow, create device and clean up some of the hass integration stuff. Not in that order.
|
||||
|
||||
### Misc Info From Making This
|
||||
Commit history is a bit of a mess. master branch shows changes from bmartins fork of sucks to v1.3.0 of this custom component. dev branch shows commits from my attempts at testing and getting this to work.
|
||||
|
||||
Added additional catches to sucks because my N79 sends some weird payloads, but attributes all pull in now for brush life spans. Couple initial queries it also sends weird that I'm in process of catching atm. As of version 1.3.0 (in the manifest.json) these initial queries and all attributes are working. Was using an implementation completely mine but saw in the MQTT class there were already catches for child payloads without the main payload having the expected td in its payload. Kept comments in giving credit and adapted them to work with xmpp.
|
||||
Just finished getting this working late 12/13/22 so not sure if everything works yet but will commit changes here if I update it or at least document issues.
|
||||
@@ -1,31 +1,38 @@
|
||||
"""Support for Ecovacs Deebot vacuums."""
|
||||
import logging
|
||||
import random
|
||||
import string
|
||||
#import asyncio ## to do will need to convert to slixmpp to do this i believe
|
||||
|
||||
##import asyncio ## to do
|
||||
|
||||
|
||||
#just included the modified sucks in component
|
||||
from .sucksbumper import EcoVacsAPI, VacBot
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import (
|
||||
CONF_USERNAME,
|
||||
CONF_PASSWORD,
|
||||
CONF_COUNTRY,
|
||||
CONF_VERIFY_SSL,
|
||||
CONF_USERNAME,
|
||||
CONF_VERIFY_SSL, # added
|
||||
EVENT_HOMEASSISTANT_STOP,
|
||||
Platform,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import discovery
|
||||
#from homeassistant.helpers.typing import ConfigType
|
||||
#import homeassistant.helpers.config_validation as cv
|
||||
#import voluptuous as vol
|
||||
#use local sucks
|
||||
from .sucks import EcoVacsAPI, VacBot
|
||||
from .const import (
|
||||
# ECOVACS_DEVICES,
|
||||
# DOMAIN,
|
||||
CONF_CONTINENT,
|
||||
LOGGER
|
||||
)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DOMAIN = "ecovacs"
|
||||
|
||||
CONF_COUNTRY = "country"
|
||||
CONF_CONTINENT = "continent"
|
||||
#bumper config vars
|
||||
CONF_BUMPER = "bumper"
|
||||
CONF_BUMPER_SERVER = "bumper_server"
|
||||
server_address = None
|
||||
|
||||
"""
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{
|
||||
DOMAIN: vol.Schema(
|
||||
@@ -34,13 +41,16 @@ CONFIG_SCHEMA = vol.Schema(
|
||||
vol.Required(CONF_PASSWORD): cv.string,
|
||||
vol.Required(CONF_COUNTRY): vol.All(vol.Lower, cv.string),
|
||||
vol.Required(CONF_CONTINENT): vol.All(vol.Lower, cv.string),
|
||||
vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean, # can probably get rid of this and set verify ssl false if
|
||||
vol.Optional(CONF_BUMPER, default=False): cv.boolean,
|
||||
vol.Optional(CONF_BUMPER_SERVER): cv.string,
|
||||
vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean, # can probably get rid of this and set verify ssl false if bumper true
|
||||
}
|
||||
)
|
||||
},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
"""
|
||||
|
||||
ECOVACS_DEVICES = "ecovacs_devices"
|
||||
|
||||
# Generate a random device ID on each bootup
|
||||
ECOVACS_API_DEVICEID = "".join(
|
||||
@@ -49,24 +59,30 @@ ECOVACS_API_DEVICEID = "".join(
|
||||
|
||||
def setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
"""Set up the Ecovacs component."""
|
||||
LOGGER.debug("Creating new Ecovacs component")
|
||||
# hass.data[ECOVACS_DEVICES] = []
|
||||
SERVER_ADDRESS = None
|
||||
_LOGGER.debug("Creating new Ecovacs component")
|
||||
|
||||
hass.data[ECOVACS_DEVICES] = []
|
||||
# if we're using bumper then define the server address
|
||||
if CONF_BUMPER == True:
|
||||
server_address = (config[DOMAIN].get(CONF_BUMPER_SERVER), 5223)
|
||||
# if not make sure it's null
|
||||
else:
|
||||
server_address = None
|
||||
|
||||
ecovacs_api = EcoVacsAPI(
|
||||
ECOVACS_API_DEVICEID,
|
||||
config_entry.data(CONF_USERNAME),
|
||||
EcoVacsAPI.md5(config_entry.data(CONF_PASSWORD)),
|
||||
config_entry.data(CONF_COUNTRY),
|
||||
config_entry.data(CONF_CONTINENT),
|
||||
config_entry.data(CONF_VERIFY_SSL), # add to class call
|
||||
config[DOMAIN].get(CONF_USERNAME),
|
||||
EcoVacsAPI.md5(config[DOMAIN].get(CONF_PASSWORD)),
|
||||
config[DOMAIN].get(CONF_COUNTRY),
|
||||
config[DOMAIN].get(CONF_CONTINENT),
|
||||
config[DOMAIN].get(CONF_VERIFY_SSL), # add to class call
|
||||
)
|
||||
|
||||
devices = ecovacs_api.devices()
|
||||
LOGGER.debug("Ecobot devices: %s", devices)
|
||||
_LOGGER.debug("Ecobot devices: %s", devices)
|
||||
|
||||
for device in devices:
|
||||
LOGGER.info(
|
||||
_LOGGER.info(
|
||||
"Discovered Ecovacs device on account: %s with nickname %s",
|
||||
device.get("did"),
|
||||
device.get("nick"),
|
||||
@@ -77,17 +93,17 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
ecovacs_api.resource,
|
||||
ecovacs_api.user_access_token,
|
||||
device,
|
||||
config_entry.data(CONF_CONTINENT).lower(),
|
||||
SERVER_ADDRESS, # include server address in class, if it's null should be no effect
|
||||
config_entry.data(CONF_VERIFY_SSL), # add to class call
|
||||
monitor=True
|
||||
config[DOMAIN].get(CONF_CONTINENT).lower(),
|
||||
server_address, # include server address in class, if it's null shoul be no effect
|
||||
config[DOMAIN].get(CONF_VERIFY_SSL), # verify ssl or not
|
||||
monitor=True,
|
||||
)
|
||||
hass.data[ECOVACS_DEVICES].append(vacbot)
|
||||
|
||||
def stop(event: object) -> None:
|
||||
"""Shut down open connections to Ecovacs XMPP server."""
|
||||
for device in hass.data[ECOVACS_DEVICES]:
|
||||
LOGGER.info(
|
||||
_LOGGER.info(
|
||||
"Shutting down connection to Ecovacs device %s",
|
||||
device.vacuum.get("did"),
|
||||
)
|
||||
@@ -95,7 +111,9 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
|
||||
# Listen for HA stop to disconnect.
|
||||
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop)
|
||||
|
||||
if hass.data[ECOVACS_DEVICES]:
|
||||
LOGGER.debug("Starting vacuum components")
|
||||
_LOGGER.debug("Starting vacuum components")
|
||||
discovery.load_platform(hass, Platform.VACUUM, DOMAIN, {}, config)
|
||||
|
||||
return True
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import logging
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
#ecovacs constants
|
||||
#init constants
|
||||
#ECOVACS_DEVICES = "ecovacs_devices"
|
||||
#DOMAIN = "ecovacs"
|
||||
CONF_CONTINENT = "continent"
|
||||
@@ -1,84 +0,0 @@
|
||||
"""Data update coordinator for Ecovacs vacuums."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from async_timeout import timeout
|
||||
from sharkiq import (
|
||||
AylaApi,
|
||||
SharkIqAuthError,
|
||||
SharkIqAuthExpiringError,
|
||||
SharkIqNotAuthedError,
|
||||
SharkIqVacuum,
|
||||
)
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
|
||||
from .const import API_TIMEOUT, DOMAIN, LOGGER, UPDATE_INTERVAL
|
||||
|
||||
|
||||
class SharkIqUpdateCoordinator(DataUpdateCoordinator[bool]):
|
||||
"""Define a wrapper class to update Shark IQ data."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
config_entry: ConfigEntry,
|
||||
ayla_api: AylaApi,
|
||||
shark_vacs: list[SharkIqVacuum],
|
||||
) -> None:
|
||||
"""Set up the SharkIqUpdateCoordinator class."""
|
||||
self.ayla_api = ayla_api
|
||||
self.shark_vacs: dict[str, SharkIqVacuum] = {
|
||||
sharkiq.serial_number: sharkiq for sharkiq in shark_vacs
|
||||
}
|
||||
self._config_entry = config_entry
|
||||
self._online_dsns: set[str] = set()
|
||||
|
||||
super().__init__(hass, LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL)
|
||||
|
||||
@property
|
||||
def online_dsns(self) -> set[str]:
|
||||
"""Get the set of all online DSNs."""
|
||||
return self._online_dsns
|
||||
|
||||
def device_is_online(self, dsn: str) -> bool:
|
||||
"""Return the online state of a given vacuum dsn."""
|
||||
return dsn in self._online_dsns
|
||||
|
||||
@staticmethod
|
||||
async def _async_update_vacuum(sharkiq: SharkIqVacuum) -> None:
|
||||
"""Asynchronously update the data for a single vacuum."""
|
||||
dsn = sharkiq.serial_number
|
||||
LOGGER.debug("Updating sharkiq data for device DSN %s", dsn)
|
||||
async with timeout(API_TIMEOUT):
|
||||
await sharkiq.async_update()
|
||||
|
||||
async def _async_update_data(self) -> bool:
|
||||
"""Update data device by device."""
|
||||
try:
|
||||
all_vacuums = await self.ayla_api.async_list_devices()
|
||||
self._online_dsns = {
|
||||
v["dsn"]
|
||||
for v in all_vacuums
|
||||
if v["connection_status"] == "Online" and v["dsn"] in self.shark_vacs
|
||||
}
|
||||
|
||||
LOGGER.debug("Updating sharkiq data")
|
||||
online_vacs = (self.shark_vacs[dsn] for dsn in self.online_dsns)
|
||||
await asyncio.gather(*(self._async_update_vacuum(v) for v in online_vacs))
|
||||
except (
|
||||
SharkIqAuthError,
|
||||
SharkIqNotAuthedError,
|
||||
SharkIqAuthExpiringError,
|
||||
) as err:
|
||||
LOGGER.debug("Bad auth state. Attempting re-auth", exc_info=err)
|
||||
raise ConfigEntryAuthFailed from err
|
||||
except Exception as err:
|
||||
LOGGER.exception("Unexpected error updating SharkIQ")
|
||||
raise UpdateFailed(err) from err
|
||||
|
||||
return True
|
||||
@@ -1,11 +1,10 @@
|
||||
{
|
||||
"domain": "ecovacs",
|
||||
"name": "Ecovacs Bumper",
|
||||
"version": "1.4.2",
|
||||
"documentation": "https://github.com/bittles/ha_ecovacs_bumper",
|
||||
"issue_tracker": "https://github.com/bittles/ha_ecovacs_bumper/issues",
|
||||
"requirements": ["sleekxmppfs==1.4.1", "requests>=2.18", "pycryptodome>=3.4", "pycountry-convert>=0.5", "paho-mqtt>=1.4", "stringcase>=1.2"],
|
||||
"codeowners": ["bittles"],
|
||||
"version": "1.3.0",
|
||||
"documentation": "https://www.home-assistant.io/integrations/ecovacs",
|
||||
"requirements": ["sleekxmppfs==1.4.1", "click>=6", "requests>=2.18", "pycryptodome>=3.4", "pycountry-convert>=0.5", "paho-mqtt>=1.4", "stringcase>=1.2"],
|
||||
"codeowners": ["@OverloadUT", "@mib1185"],
|
||||
"iot_class": "local_polling",
|
||||
"loggers": ["sleekxmppfs", "ecovacs"]
|
||||
"loggers": ["sleekxmppfs", "sucksbumper"]
|
||||
}
|
||||
|
||||
@@ -1,596 +0,0 @@
|
||||
import hashlib
|
||||
import time
|
||||
import requests
|
||||
import os
|
||||
from base64 import b64decode, b64encode
|
||||
from collections import OrderedDict
|
||||
from sleekxmppfs.xmlstream import ET
|
||||
from sleekxmppfs.exceptions import XMPPError
|
||||
|
||||
from .sucks_mqtt import EcoVacsIOTMQ
|
||||
from .sucks_xmpp import EcoVacsXMPP
|
||||
|
||||
from .const import LOGGER
|
||||
from .sucks_const import *
|
||||
|
||||
def str_to_bool_or_cert(s):
|
||||
if s == 'True' or s == True:
|
||||
return True
|
||||
elif s == 'False' or s == False:
|
||||
return False
|
||||
else:
|
||||
if not s == None:
|
||||
if os.path.exists(s): # User could provide a path to a CA Cert as well, which is useful for Bumper
|
||||
if os.path.isfile(s):
|
||||
return s
|
||||
else:
|
||||
raise ValueError("Certificate path provided is not a file - {}".format(s))
|
||||
raise ValueError("Cannot covert {} to a bool or certificate path".format(s))
|
||||
|
||||
class EcoVacsAPI:
|
||||
CLIENT_KEY = "eJUWrzRv34qFSaYk"
|
||||
SECRET = "Cyu5jcR4zyK6QEPn1hdIGXB5QIDAQABMA0GC"
|
||||
PUBLIC_KEY = 'MIIB/TCCAWYCCQDJ7TMYJFzqYDANBgkqhkiG9w0BAQUFADBCMQswCQYDVQQGEwJjbjEVMBMGA1UEBwwMRGVmYXVsdCBDaXR5MRwwGgYDVQQKDBNEZWZhdWx0IENvbXBhbnkgTHRkMCAXDTE3MDUwOTA1MTkxMFoYDzIxMTcwNDE1MDUxOTEwWjBCMQswCQYDVQQGEwJjbjEVMBMGA1UEBwwMRGVmYXVsdCBDaXR5MRwwGgYDVQQKDBNEZWZhdWx0IENvbXBhbnkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDb8V0OYUGP3Fs63E1gJzJh+7iqeymjFUKJUqSD60nhWReZ+Fg3tZvKKqgNcgl7EGXp1yNifJKUNC/SedFG1IJRh5hBeDMGq0m0RQYDpf9l0umqYURpJ5fmfvH/gjfHe3Eg/NTLm7QEa0a0Il2t3Cyu5jcR4zyK6QEPn1hdIGXB5QIDAQABMA0GCSqGSIb3DQEBBQUAA4GBANhIMT0+IyJa9SU8AEyaWZZmT2KEYrjakuadOvlkn3vFdhpvNpnnXiL+cyWy2oU1Q9MAdCTiOPfXmAQt8zIvP2JC8j6yRTcxJCvBwORDyv/uBtXFxBPEC6MDfzU2gKAaHeeJUWrzRv34qFSaYkYta8canK+PSInylQTjJK9VqmjQ'
|
||||
MAIN_URL_FORMAT = 'https://eco-{country}-api.ecovacs.com/v1/private/{country}/{lang}/{deviceId}/{appCode}/{appVersion}/{channel}/{deviceType}'
|
||||
USER_URL_FORMAT = 'https://users-{continent}.ecouser.net:8000/user.do'
|
||||
PORTAL_URL_FORMAT = 'https://portal-{continent}.ecouser.net/api'
|
||||
USERSAPI = 'users/user.do'
|
||||
IOTDEVMANAGERAPI = 'iot/devmanager.do' # IOT Device Manager - This provides control of "IOT" products via RestAPI, some bots use this instead of XMPP
|
||||
PRODUCTAPI = 'pim/product' # Leaving this open, the only endpoint known currently is "Product IOT Map" - pim/product/getProductIotMap - This provides a list of "IOT" products. Not sure what this provides the app.
|
||||
REALM = 'ecouser.net'
|
||||
|
||||
def __init__(self, device_id, account_id, password_hash, country, continent, verify_ssl=True):
|
||||
self.meta = {
|
||||
'country': country,
|
||||
'lang': 'en',
|
||||
'deviceId': device_id,
|
||||
'appCode': 'i_eco_e',
|
||||
#'appCode': 'i_eco_a' - iphone
|
||||
'appVersion': '1.3.5',
|
||||
#'appVersion': '1.4.6' - iphone
|
||||
'channel': 'c_googleplay',
|
||||
#'channel': 'c_iphone', - iphone
|
||||
'deviceType': '1'
|
||||
#'deviceType': '2' - iphone
|
||||
}
|
||||
self.verify_ssl = str_to_bool_or_cert(verify_ssl)
|
||||
LOGGER.debug("Setting up EcoVacsAPI")
|
||||
self.resource = device_id[0:8]
|
||||
self.country = country
|
||||
self.continent = continent
|
||||
login_info = self.__call_main_api('user/login',
|
||||
('account', self.encrypt(account_id)),
|
||||
('password', self.encrypt(password_hash)))
|
||||
self.uid = login_info['uid']
|
||||
self.login_access_token = login_info['accessToken']
|
||||
self.auth_code = self.__call_main_api('user/getAuthCode',
|
||||
('uid', self.uid),
|
||||
('accessToken', self.login_access_token))['authCode']
|
||||
login_response = self.__call_login_by_it_token()
|
||||
self.user_access_token = login_response['token']
|
||||
if login_response['userId'] != self.uid:
|
||||
LOGGER.debug("Switching to shorter UID " + login_response['userId'])
|
||||
self.uid = login_response['userId']
|
||||
LOGGER.debug("EcoVacsAPI connection complete")
|
||||
|
||||
def __sign(self, params):
|
||||
result = params.copy()
|
||||
result['authTimespan'] = int(time.time() * 1000)
|
||||
result['authTimeZone'] = 'GMT-8'
|
||||
sign_on = self.meta.copy()
|
||||
sign_on.update(result)
|
||||
sign_on_text = EcoVacsAPI.CLIENT_KEY + ''.join(
|
||||
[k + '=' + str(sign_on[k]) for k in sorted(sign_on.keys())]) + EcoVacsAPI.SECRET
|
||||
result['authAppkey'] = EcoVacsAPI.CLIENT_KEY
|
||||
result['authSign'] = self.md5(sign_on_text)
|
||||
return result
|
||||
|
||||
def __call_main_api(self, function, *args):
|
||||
LOGGER.debug("calling main api {} with {}".format(function, args))
|
||||
params = OrderedDict(args)
|
||||
params['requestId'] = self.md5(time.time())
|
||||
url = (EcoVacsAPI.MAIN_URL_FORMAT + "/" + function).format(**self.meta)
|
||||
api_response = requests.get(url, self.__sign(params), verify=self.verify_ssl)
|
||||
json = api_response.json()
|
||||
LOGGER.debug("got {}".format(json))
|
||||
if json['code'] == '0000':
|
||||
return json['data']
|
||||
elif json['code'] == '1005':
|
||||
LOGGER.error("incorrect email or password")
|
||||
raise ValueError("incorrect email or password")
|
||||
else:
|
||||
LOGGER.error("call to {} failed with {}".format(function, json))
|
||||
raise RuntimeError("failure code {} ({}) for call {} and parameters {}".format(
|
||||
json['code'], json['msg'], function, args))
|
||||
|
||||
def __call_user_api(self, function, args):
|
||||
LOGGER.debug("calling user api {} with {}".format(function, args))
|
||||
params = {'todo': function}
|
||||
params.update(args)
|
||||
response = requests.post(EcoVacsAPI.USER_URL_FORMAT.format(continent=self.continent), json=params, verify=self.verify_ssl)
|
||||
json = response.json()
|
||||
LOGGER.debug("got {}".format(json))
|
||||
if json['result'] == 'ok':
|
||||
return json
|
||||
else:
|
||||
LOGGER.error("call to {} failed with {}".format(function, json))
|
||||
raise RuntimeError(
|
||||
"failure {} ({}) for call {} and parameters {}".format(json['error'], json['errno'], function, params))
|
||||
|
||||
def __call_portal_api(self, api, function, args, verify_ssl=True, **kwargs):
|
||||
if api == self.USERSAPI:
|
||||
params = {'todo': function}
|
||||
params.update(args)
|
||||
else:
|
||||
params = {}
|
||||
params.update(args)
|
||||
LOGGER.debug("calling portal api {} function {} with {}".format(api, function, params))
|
||||
continent = self.continent
|
||||
if 'continent' in kwargs:
|
||||
continent = kwargs.get('continent')
|
||||
url = (EcoVacsAPI.PORTAL_URL_FORMAT + "/" + api).format(continent=continent, **self.meta)
|
||||
response = requests.post(url, json=params, verify=verify_ssl)
|
||||
json = response.json()
|
||||
LOGGER.debug("got {}".format(json))
|
||||
if api == self.USERSAPI:
|
||||
if json['result'] == 'ok':
|
||||
return json
|
||||
elif json['result'] == 'fail':
|
||||
if json['error'] == 'set token error.': # If it is a set token error try again
|
||||
if not 'set_token' in kwargs:
|
||||
LOGGER.debug("loginByItToken set token error, trying again (2/3)")
|
||||
return self.__call_portal_api(self.USERSAPI, function, args, verify_ssl=verify_ssl, set_token=1)
|
||||
elif kwargs.get('set_token') == 1:
|
||||
LOGGER.debug("loginByItToken set token error, trying again with ww (3/3)")
|
||||
return self.__call_portal_api(self.USERSAPI, function, args, verify_ssl=verify_ssl, set_token=2, continent="ww")
|
||||
else:
|
||||
LOGGER.debug("loginByItToken set token error, failed after 3 attempts")
|
||||
if api.startswith(self.PRODUCTAPI):
|
||||
if json['code'] == 0:
|
||||
return json
|
||||
|
||||
else:
|
||||
LOGGER.error("call to {} failed with {}".format(function, json))
|
||||
raise RuntimeError(
|
||||
"failure {} ({}) for call {} and parameters {}".format(json['error'], json['errno'], function, params))
|
||||
|
||||
def __call_login_by_it_token(self):
|
||||
return self.__call_portal_api(self.USERSAPI,'loginByItToken',
|
||||
{'country': self.meta['country'].upper(),
|
||||
'resource': self.resource,
|
||||
'realm': EcoVacsAPI.REALM,
|
||||
'userId': self.uid,
|
||||
'token': self.auth_code}
|
||||
, verify_ssl=self.verify_ssl)
|
||||
|
||||
def getdevices(self):
|
||||
return self.__call_portal_api(self.USERSAPI,'GetDeviceList', {
|
||||
'userid': self.uid,
|
||||
'auth': {
|
||||
'with': 'users',
|
||||
'userid': self.uid,
|
||||
'realm': EcoVacsAPI.REALM,
|
||||
'token': self.user_access_token,
|
||||
'resource': self.resource
|
||||
}
|
||||
}, verify_ssl=self.verify_ssl)['devices']
|
||||
|
||||
def getiotProducts(self):
|
||||
return self.__call_portal_api(self.PRODUCTAPI + '/getProductIotMap','', {
|
||||
'channel': '',
|
||||
'auth': {
|
||||
'with': 'users',
|
||||
'userid': self.uid,
|
||||
'realm': EcoVacsAPI.REALM,
|
||||
'token': self.user_access_token,
|
||||
'resource': self.resource
|
||||
}
|
||||
}, verify_ssl=self.verify_ssl)['data']
|
||||
|
||||
def SetIOTDevices(self, devices, iotproducts):
|
||||
#Originally added for D900, and not actively used in code now - Not sure what the app checks the items in this list for
|
||||
for device in devices: #Check if the device is part of iotProducts
|
||||
device['iot_product'] = False
|
||||
for iotProduct in iotproducts:
|
||||
if device['class'] in iotProduct['classid']:
|
||||
device['iot_product'] = True
|
||||
|
||||
return devices
|
||||
|
||||
def SetIOTMQDevices(self, devices):
|
||||
#Added for devices that utilize MQTT instead of XMPP for communication
|
||||
for device in devices:
|
||||
device['iotmq'] = False
|
||||
if device['company'] == 'eco-ng': #Check if the device is part of the list
|
||||
device['iotmq'] = True
|
||||
|
||||
return devices
|
||||
|
||||
def devices(self):
|
||||
return self.SetIOTMQDevices(self.getdevices())
|
||||
|
||||
@staticmethod
|
||||
def md5(text):
|
||||
return hashlib.md5(bytes(str(text), 'utf8')).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def encrypt(text):
|
||||
from Crypto.PublicKey import RSA
|
||||
from Crypto.Cipher import PKCS1_v1_5
|
||||
key = RSA.import_key(b64decode(EcoVacsAPI.PUBLIC_KEY))
|
||||
cipher = PKCS1_v1_5.new(key)
|
||||
result = cipher.encrypt(bytes(text, 'utf8'))
|
||||
return str(b64encode(result), 'utf8')
|
||||
|
||||
class EventEmitter(object):
|
||||
"""A very simple event emitting system."""
|
||||
def __init__(self):
|
||||
self._subscribers = []
|
||||
|
||||
def subscribe(self, callback):
|
||||
listener = EventListener(self, callback)
|
||||
self._subscribers.append(listener)
|
||||
return listener
|
||||
|
||||
def unsubscribe(self, listener):
|
||||
self._subscribers.remove(listener)
|
||||
|
||||
def notify(self, event):
|
||||
for subscriber in self._subscribers:
|
||||
subscriber.callback(event)
|
||||
|
||||
class EventListener(object):
|
||||
"""Object that allows event consumers to easily unsubscribe from events."""
|
||||
def __init__(self, emitter, callback):
|
||||
self._emitter = emitter
|
||||
self.callback = callback
|
||||
|
||||
def unsubscribe(self):
|
||||
self._emitter.unsubscribe(self)
|
||||
|
||||
class VacBot():
|
||||
# switched verify and monitor just to be consistent
|
||||
def __init__(self, user, domain, resource, secret, vacuum, continent, server_address=None, verify_ssl=True, monitor=False):
|
||||
self.vacuum = vacuum
|
||||
self.server_address = server_address
|
||||
# If True, the VacBot object will handle keeping track of all statuses,
|
||||
# including the initial request for statuses, and new requests after the
|
||||
# VacBot returns from being offline. It will also cause it to regularly
|
||||
# request component lifespans
|
||||
self._monitor = monitor
|
||||
self._failed_pings = 0
|
||||
# These three are representations of the vacuum state as reported by the API
|
||||
self.clean_status = None
|
||||
self.charge_status = None
|
||||
self.battery_status = None
|
||||
# This is an aggregate state managed by the sucks library, combining the clean and charge events to a single state
|
||||
self.vacuum_status = None
|
||||
self.fan_speed = None
|
||||
# Populated by component Lifespan reports
|
||||
self.components = {}
|
||||
self.statusEvents = EventEmitter()
|
||||
self.batteryEvents = EventEmitter()
|
||||
self.lifespanEvents = EventEmitter()
|
||||
self.errorEvents = EventEmitter()
|
||||
#Set none for clients to start
|
||||
self.xmpp = None
|
||||
self.iotmq = None
|
||||
if not vacuum['iotmq']:
|
||||
self.xmpp = EcoVacsXMPP(user, domain, resource, secret, continent, vacuum, server_address)
|
||||
#Uncomment line to allow unencrypted plain auth
|
||||
#self.xmpp['feature_mechanisms'].unencrypted_plain = True
|
||||
self.xmpp.subscribe_to_ctls(self._handle_ctl)
|
||||
else:
|
||||
self.iotmq = EcoVacsIOTMQ(user, domain, resource, secret, continent, vacuum, server_address, verify_ssl=verify_ssl)
|
||||
self.iotmq.subscribe_to_ctls(self._handle_ctl)
|
||||
#The app still connects to XMPP as well, but only issues ping commands.
|
||||
#Everything works without XMPP, so leaving the below commented out.
|
||||
#self.xmpp = EcoVacsXMPP(user, domain, resource, secret, continent, vacuum, server_address)
|
||||
#Uncomment line to allow unencrypted plain auth
|
||||
#self.xmpp['feature_mechanisms'].unencrypted_plain = True
|
||||
#self.xmpp.subscribe_to_ctls(self._handle_ctl)
|
||||
|
||||
def connect_and_wait_until_ready(self):
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.connect_and_wait_until_ready()
|
||||
self.xmpp.schedule('Ping', 300, lambda: self.send_ping(), repeat=True)
|
||||
else:
|
||||
self.iotmq.connect_and_wait_until_ready()
|
||||
self.iotmq.schedule(30, self.send_ping)
|
||||
#self.xmpp.connect_and_wait_until_ready() #Leaving in case xmpp is given to iotmq in the future
|
||||
if self._monitor:
|
||||
# Do a first ping, which will also fetch initial statuses if the ping succeeds
|
||||
self.send_ping()
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.schedule('Components', 3600, lambda: self.refresh_components(), repeat=True)
|
||||
else:
|
||||
self.iotmq.schedule(3600,self.refresh_components)
|
||||
|
||||
def _handle_ctl(self, ctl):
|
||||
method = '_handle_' + ctl['event']
|
||||
if hasattr(self, method):
|
||||
getattr(self, method)(ctl)
|
||||
|
||||
def _handle_error(self, event):
|
||||
if 'error' in event:
|
||||
error = event['error']
|
||||
elif 'errs' in event:
|
||||
error = event['errs']
|
||||
if not error == '':
|
||||
self.errorEvents.notify(error)
|
||||
LOGGER.error("*** error = " + error)
|
||||
|
||||
def _handle_life_span(self, event):
|
||||
type = event['type']
|
||||
try:
|
||||
type = COMPONENT_FROM_ECOVACS[type]
|
||||
except KeyError:
|
||||
LOGGER.warning("Unknown component type: '" + type + "'")
|
||||
if 'val' in event:
|
||||
lifespan = int(event['val']) / 100
|
||||
LOGGER.info("**********Component " + type + " has lifespan of " + str(lifespan) + ".")
|
||||
else:
|
||||
lifespan = int(event['left']) / 60 #This works for a D901
|
||||
self.components[type] = lifespan
|
||||
lifespan_event = {'type': type, 'lifespan': lifespan}
|
||||
self.lifespanEvents.notify(lifespan_event)
|
||||
LOGGER.info("*** life_span " + type + " = " + str(lifespan))
|
||||
|
||||
def _handle_clean_report(self, event):
|
||||
type = event['type']
|
||||
try:
|
||||
type = CLEAN_MODE_FROM_ECOVACS[type]
|
||||
if self.vacuum['iotmq']: #Was able to parse additional status from the IOTMQ, may apply to XMPP too
|
||||
statustype = event['st']
|
||||
statustype = CLEAN_ACTION_FROM_ECOVACS[statustype]
|
||||
if statustype == CLEAN_ACTION_STOP or statustype == CLEAN_ACTION_PAUSE:
|
||||
type = statustype
|
||||
except KeyError:
|
||||
LOGGER.warning("Unknown cleaning status '" + type + "'")
|
||||
self.clean_status = type
|
||||
self.vacuum_status = type
|
||||
fan = event.get('speed', None)
|
||||
if fan is not None:
|
||||
try:
|
||||
fan = FAN_SPEED_FROM_ECOVACS[fan]
|
||||
except KeyError:
|
||||
LOGGER.warning("Unknown fan speed: '" + fan + "'")
|
||||
self.fan_speed = fan
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
if self.fan_speed:
|
||||
LOGGER.info("*** clean_status = " + self.clean_status + " fan_speed = " + self.fan_speed)
|
||||
else:
|
||||
LOGGER.info("*** clean_status = " + self.clean_status + " fan_speed = None")
|
||||
|
||||
def _handle_battery_info(self, iq):
|
||||
try:
|
||||
self.battery_status = float(iq['power']) / 100
|
||||
except ValueError:
|
||||
LOGGER.warning("couldn't parse battery status " + ET.tostring(iq))
|
||||
else:
|
||||
self.batteryEvents.notify(self.battery_status)
|
||||
LOGGER.info("*** battery_status = {:.0%}".format(self.battery_status))
|
||||
|
||||
def _handle_charge_state(self, event):
|
||||
if 'type' in event:
|
||||
status = event['type']
|
||||
elif 'errno' in event: #Handle error
|
||||
if event['ret'] == 'fail' and event['errno'] == '8': #Already charging
|
||||
status = 'slot_charging'
|
||||
elif event['ret'] == 'fail' and event['errno'] == '5': #Busy with another command
|
||||
status = 'idle'
|
||||
elif event['ret'] == 'fail' and event['errno'] == '3': #Bot in stuck state, example dust bin out
|
||||
status = 'idle'
|
||||
else:
|
||||
status = 'idle' #Fall back to Idle status
|
||||
LOGGER.error("Unknown charging status '" + event['errno'] + "'") #Log this so we can identify more errors
|
||||
try:
|
||||
status = CHARGE_MODE_FROM_ECOVACS[status]
|
||||
except KeyError:
|
||||
LOGGER.warning("Unknown charging status '" + status + "'")
|
||||
self.charge_status = status
|
||||
if status != 'idle' or self.vacuum_status == 'charging':
|
||||
# We have to ignore the idle messages, because all it means is that it's not
|
||||
# currently charging, in which case the clean_status is a better indicator
|
||||
# of what the vacuum is currently up to.
|
||||
self.vacuum_status = status
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
LOGGER.info("*** charge_status = " + self.charge_status)
|
||||
|
||||
def _vacuum_address(self):
|
||||
if not self.vacuum['iotmq']:
|
||||
return self.vacuum['did'] + '@' + self.vacuum['class'] + '.ecorobot.net/atom'
|
||||
else:
|
||||
return self.vacuum['did'] #IOTMQ only uses the did
|
||||
|
||||
@property
|
||||
def is_charging(self) -> bool:
|
||||
return self.vacuum_status in CHARGING_STATES
|
||||
|
||||
@property
|
||||
def is_cleaning(self) -> bool:
|
||||
return self.vacuum_status in CLEANING_STATES
|
||||
|
||||
def send_ping(self):
|
||||
try:
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.send_ping(self._vacuum_address())
|
||||
elif self.vacuum['iotmq']:
|
||||
if not self.iotmq.send_ping():
|
||||
raise RuntimeError()
|
||||
except XMPPError as err:
|
||||
LOGGER.warning("Ping did not reach VacBot. Will retry.")
|
||||
LOGGER.error("*** Error type: " + err.etype)
|
||||
LOGGER.error("*** Error condition: " + err.condition)
|
||||
self._failed_pings += 1
|
||||
if self._failed_pings >= 4:
|
||||
self.vacuum_status = 'offline'
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
except RuntimeError as err:
|
||||
LOGGER.warning("Ping did not reach VacBot. Will retry.")
|
||||
self._failed_pings += 1
|
||||
if self._failed_pings >= 4:
|
||||
self.vacuum_status = 'offline'
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
else:
|
||||
self._failed_pings = 0
|
||||
if self._monitor:
|
||||
# If we don't yet have a vacuum status, request initial statuses again now that the ping succeeded
|
||||
if self.vacuum_status == 'offline' or self.vacuum_status is None:
|
||||
self.request_all_statuses()
|
||||
else:
|
||||
# If we're not auto-monitoring the status, then just reset the status to None, which indicates unknown
|
||||
if self.vacuum_status == 'offline':
|
||||
self.vacuum_status = None
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
|
||||
def refresh_components(self):
|
||||
try:
|
||||
self.run(GetLifeSpan('main_brush'))
|
||||
self.run(GetLifeSpan('side_brush'))
|
||||
self.run(GetLifeSpan('filter'))
|
||||
except XMPPError as err:
|
||||
LOGGER.warning("Component refresh requests failed to reach VacBot. Will try again later.")
|
||||
LOGGER.error("*** Error type: " + err.etype)
|
||||
LOGGER.error("*** Error condition: " + err.condition)
|
||||
|
||||
def refresh_statuses(self):
|
||||
try:
|
||||
self.run(GetCleanState())
|
||||
self.run(GetChargeState())
|
||||
self.run(GetBatteryState())
|
||||
except XMPPError as err:
|
||||
LOGGER.warning("Initial status requests failed to reach VacBot. Will try again on next ping.")
|
||||
LOGGER.error("*** Error type: " + err.etype)
|
||||
LOGGER.error("*** Error condition: " + err.condition)
|
||||
|
||||
def request_all_statuses(self):
|
||||
self.refresh_statuses()
|
||||
self.refresh_components()
|
||||
|
||||
def send_command(self, action):
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.send_command(action.to_xml(), self._vacuum_address())
|
||||
else:
|
||||
#IOTMQ issues commands via RestAPI, and listens on MQTT for status updates
|
||||
self.iotmq.send_command(action, self._vacuum_address()) #IOTMQ devices need the full action for additional parsing
|
||||
|
||||
def run(self, action):
|
||||
self.send_command(action)
|
||||
|
||||
def disconnect(self, wait=False):
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.disconnect(wait=wait)
|
||||
else:
|
||||
self.iotmq._disconnect()
|
||||
#self.xmpp.disconnect(wait=wait) #Leaving in case xmpp is added to iotmq in the future
|
||||
|
||||
class VacBotCommand:
|
||||
ACTION = {
|
||||
'forward': 'forward',
|
||||
'backward': 'backward',
|
||||
'left': 'SpinLeft',
|
||||
'right': 'SpinRight',
|
||||
'turn_around': 'TurnAround',
|
||||
'stop': 'stop'
|
||||
}
|
||||
|
||||
def __init__(self, name, args=None, **kwargs):
|
||||
if args is None:
|
||||
args = {}
|
||||
self.name = name
|
||||
self.args = args
|
||||
|
||||
def to_xml(self):
|
||||
ctl = ET.Element('ctl', {'td': self.name})
|
||||
for key, value in self.args.items():
|
||||
if type(value) is dict:
|
||||
inner = ET.Element(key, value)
|
||||
ctl.append(inner)
|
||||
elif type(value) is list:
|
||||
for item in value:
|
||||
ixml = self.listobject_to_xml(key, item)
|
||||
ctl.append(ixml)
|
||||
else:
|
||||
ctl.set(key, value)
|
||||
return ctl
|
||||
|
||||
def __str__(self, *args, **kwargs):
|
||||
return self.command_name() + " command"
|
||||
|
||||
def command_name(self):
|
||||
return self.__class__.__name__.lower()
|
||||
|
||||
def listobject_to_xml(self, tag, conv_object):
|
||||
rtnobject = ET.Element(tag)
|
||||
if type(conv_object) is dict:
|
||||
for key, value in conv_object.items():
|
||||
rtnobject.set(key, value)
|
||||
else:
|
||||
rtnobject.set(tag, conv_object)
|
||||
return rtnobject
|
||||
|
||||
class Clean(VacBotCommand):
|
||||
def __init__(self, mode='auto', speed='normal', iotmq=False, action='start',terminal=False, **kwargs):
|
||||
if kwargs == {}:
|
||||
#Looks like action is needed for some bots, shouldn't affect older models
|
||||
super().__init__('Clean', {'clean': {'type': CLEAN_MODE_TO_ECOVACS[mode], 'speed': FAN_SPEED_TO_ECOVACS[speed],'act': CLEAN_ACTION_TO_ECOVACS[action]}})
|
||||
else:
|
||||
initcmd = {'type': CLEAN_MODE_TO_ECOVACS[mode], 'speed': FAN_SPEED_TO_ECOVACS[speed]}
|
||||
for kkey, kvalue in kwargs.items():
|
||||
initcmd[kkey] = kvalue
|
||||
super().__init__('Clean', {'clean': initcmd})
|
||||
|
||||
class Edge(Clean):
|
||||
def __init__(self):
|
||||
super().__init__('edge', 'high')
|
||||
|
||||
class Spot(Clean):
|
||||
def __init__(self):
|
||||
super().__init__('spot', 'high')
|
||||
|
||||
class Stop(Clean):
|
||||
def __init__(self):
|
||||
super().__init__('stop', 'normal')
|
||||
|
||||
class SpotArea(Clean):
|
||||
def __init__(self, action='start', area='', map_position='', cleanings='1'):
|
||||
if area != '': #For cleaning specified area
|
||||
super().__init__('spot_area', 'normal', act=CLEAN_ACTION_TO_ECOVACS[action], mid=area)
|
||||
elif map_position != '': #For cleaning custom map area, and specify deep amount 1x/2x
|
||||
super().__init__('spot_area' ,'normal',act=CLEAN_ACTION_TO_ECOVACS[action], p=map_position, deep=cleanings)
|
||||
else:
|
||||
#no valid entries
|
||||
raise ValueError("must provide area or map_position for spotarea clean")
|
||||
|
||||
class Charge(VacBotCommand):
|
||||
def __init__(self):
|
||||
super().__init__('Charge', {'charge': {'type': CHARGE_MODE_TO_ECOVACS['return']}})
|
||||
|
||||
class Move(VacBotCommand):
|
||||
def __init__(self, action):
|
||||
super().__init__('Move', {'move': {'action': self.ACTION[action]}})
|
||||
|
||||
class PlaySound(VacBotCommand):
|
||||
def __init__(self, sid="0"):
|
||||
super().__init__('PlaySound', {'sid': sid})
|
||||
|
||||
class GetCleanState(VacBotCommand):
|
||||
def __init__(self):
|
||||
super().__init__('GetCleanState')
|
||||
|
||||
class GetChargeState(VacBotCommand):
|
||||
def __init__(self):
|
||||
super().__init__('GetChargeState')
|
||||
|
||||
class GetBatteryState(VacBotCommand):
|
||||
def __init__(self):
|
||||
super().__init__('GetBatteryInfo')
|
||||
|
||||
class GetLifeSpan(VacBotCommand):
|
||||
def __init__(self, component):
|
||||
super().__init__('GetLifeSpan', {'type': COMPONENT_TO_ECOVACS[component]})
|
||||
|
||||
class SetTime(VacBotCommand):
|
||||
def __init__(self, timestamp, timezone):
|
||||
super().__init__('SetTime', {'time': {'t': timestamp, 'tz': timezone}})
|
||||
@@ -1,109 +0,0 @@
|
||||
#sucks constants
|
||||
# These consts define all of the vocabulary used by this library when presenting various states and components.
|
||||
# Applications implementing this library should import these rather than hard-code the strings, for future-proofing.
|
||||
|
||||
CLEAN_MODE_AUTO = 'auto'
|
||||
CLEAN_MODE_EDGE = 'edge'
|
||||
CLEAN_MODE_SPOT = 'spot'
|
||||
CLEAN_MODE_SPOT_AREA = 'spot_area'
|
||||
CLEAN_MODE_SINGLE_ROOM = 'single_room'
|
||||
CLEAN_MODE_STOP = 'stop'
|
||||
|
||||
CLEAN_ACTION_START = 'start'
|
||||
CLEAN_ACTION_PAUSE = 'pause'
|
||||
CLEAN_ACTION_RESUME = 'resume'
|
||||
CLEAN_ACTION_STOP = 'stop'
|
||||
|
||||
FAN_SPEED_NORMAL = 'normal'
|
||||
FAN_SPEED_HIGH = 'high'
|
||||
|
||||
CHARGE_MODE_RETURN = 'return'
|
||||
CHARGE_MODE_RETURNING = 'returning'
|
||||
CHARGE_MODE_CHARGING = 'charging'
|
||||
CHARGE_MODE_IDLE = 'idle'
|
||||
|
||||
COMPONENT_SIDE_BRUSH = 'side_brush'
|
||||
COMPONENT_MAIN_BRUSH = 'main_brush'
|
||||
COMPONENT_FILTER = 'filter'
|
||||
|
||||
VACUUM_STATUS_OFFLINE = 'offline'
|
||||
|
||||
CLEANING_STATES = {CLEAN_MODE_AUTO, CLEAN_MODE_EDGE, CLEAN_MODE_SPOT, CLEAN_MODE_SPOT_AREA, CLEAN_MODE_SINGLE_ROOM}
|
||||
CHARGING_STATES = {CHARGE_MODE_CHARGING}
|
||||
|
||||
# These dictionaries convert to and from Sucks's consts (which closely match what the UI and manuals use)
|
||||
# to and from what the Ecovacs API uses (which are sometimes very oddly named and have random capitalization.)
|
||||
CLEAN_MODE_TO_ECOVACS = {
|
||||
CLEAN_MODE_AUTO: 'auto',
|
||||
CLEAN_MODE_EDGE: 'border',
|
||||
CLEAN_MODE_SPOT: 'spot',
|
||||
CLEAN_MODE_SPOT_AREA: 'SpotArea',
|
||||
CLEAN_MODE_SINGLE_ROOM: 'singleroom',
|
||||
CLEAN_MODE_STOP: 'stop'
|
||||
}
|
||||
|
||||
CLEAN_ACTION_TO_ECOVACS = {
|
||||
CLEAN_ACTION_START: 's',
|
||||
CLEAN_ACTION_PAUSE: 'p',
|
||||
CLEAN_ACTION_RESUME: 'r',
|
||||
CLEAN_ACTION_STOP: 'h',
|
||||
}
|
||||
|
||||
CLEAN_ACTION_FROM_ECOVACS = {
|
||||
's': CLEAN_ACTION_START,
|
||||
'p': CLEAN_ACTION_PAUSE,
|
||||
'r': CLEAN_ACTION_RESUME,
|
||||
'h': CLEAN_ACTION_STOP,
|
||||
}
|
||||
|
||||
CLEAN_MODE_FROM_ECOVACS = {
|
||||
'auto': CLEAN_MODE_AUTO,
|
||||
'border': CLEAN_MODE_EDGE,
|
||||
'spot': CLEAN_MODE_SPOT,
|
||||
'spot_area': CLEAN_MODE_SPOT_AREA,
|
||||
'SpotArea': CLEAN_MODE_SPOT_AREA,
|
||||
'singleroom': CLEAN_MODE_SINGLE_ROOM,
|
||||
'stop': CLEAN_MODE_STOP,
|
||||
'going': CHARGE_MODE_RETURNING,
|
||||
}
|
||||
|
||||
FAN_SPEED_TO_ECOVACS = {
|
||||
FAN_SPEED_NORMAL: 'standard',
|
||||
FAN_SPEED_HIGH: 'strong'
|
||||
}
|
||||
|
||||
FAN_SPEED_FROM_ECOVACS = {
|
||||
'standard': FAN_SPEED_NORMAL,
|
||||
'strong': FAN_SPEED_HIGH,
|
||||
}
|
||||
|
||||
CHARGE_MODE_TO_ECOVACS = {
|
||||
CHARGE_MODE_RETURN: 'go',
|
||||
CHARGE_MODE_RETURNING: 'Going',
|
||||
CHARGE_MODE_CHARGING: 'SlotCharging',
|
||||
CHARGE_MODE_IDLE: 'Idle',
|
||||
}
|
||||
|
||||
CHARGE_MODE_FROM_ECOVACS = {
|
||||
'going': CHARGE_MODE_RETURNING,
|
||||
# 'Going': CHARGE_MODE_RETURNING,
|
||||
'slot_charging': CHARGE_MODE_CHARGING,
|
||||
# 'SlotCharging': CHARGE_MODE_CHARGING,
|
||||
'idle': CHARGE_MODE_IDLE,
|
||||
# 'Idle': CHARGE_MODE_IDLE,
|
||||
}
|
||||
|
||||
COMPONENT_TO_ECOVACS = {
|
||||
COMPONENT_MAIN_BRUSH: 'Brush',
|
||||
COMPONENT_SIDE_BRUSH: 'SideBrush',
|
||||
COMPONENT_FILTER: 'DustCaseHeap',
|
||||
}
|
||||
|
||||
COMPONENT_FROM_ECOVACS = {
|
||||
'brush': COMPONENT_MAIN_BRUSH,
|
||||
# 'Brush': COMPONENT_MAIN_BRUSH,
|
||||
'side_brush': COMPONENT_SIDE_BRUSH,
|
||||
# 'SideBrush': COMPONENT_SIDE_BRUSH,
|
||||
'dust_case_heap': COMPONENT_FILTER,
|
||||
# 'DustCaseHeap': COMPONENT_FILTER,
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
import time
|
||||
import sched
|
||||
import threading
|
||||
import ssl
|
||||
import requests
|
||||
import stringcase
|
||||
from threading import Event
|
||||
from paho.mqtt.client import Client as ClientMQTT
|
||||
from paho.mqtt import publish as MQTTPublish
|
||||
from paho.mqtt import subscribe as MQTTSubscribe
|
||||
from sleekxmppfs.xmlstream import ET
|
||||
|
||||
from .const import LOGGER
|
||||
|
||||
#This is used by EcoVacsIOTMQ and EcoVacsXMPP for _ctl_to_dict
|
||||
def RepresentsInt(stringvar):
|
||||
try:
|
||||
int(stringvar)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
class EcoVacsIOTMQ(ClientMQTT):
|
||||
def __init__(self, user, domain, resource, secret, continent, vacuum, server_address=None, verify_ssl=True):
|
||||
ClientMQTT.__init__(self)
|
||||
self.ctl_subscribers = []
|
||||
self.user = user
|
||||
self.domain = str(domain).split(".")[0] #MQTT is using domain without tld extension
|
||||
self.resource = resource
|
||||
self.secret = secret
|
||||
self.continent = continent
|
||||
self.vacuum = vacuum
|
||||
self.scheduler = sched.scheduler(time.time, time.sleep)
|
||||
self.scheduler_thread = threading.Thread(target=self.scheduler.run, daemon=True, name="mqtt_schedule_thread")
|
||||
self.verify_ssl = str_to_bool_or_cert(verify_ssl)
|
||||
if server_address is None:
|
||||
self.hostname = ('mq-{}.ecouser.net'.format(self.continent))
|
||||
self.port = 8883
|
||||
else:
|
||||
saddress = server_address.split(":")
|
||||
if len(saddress) > 1:
|
||||
self.hostname = saddress[0]
|
||||
if RepresentsInt(saddress[1]):
|
||||
self.port = int(saddress[1])
|
||||
else:
|
||||
self.port = 8883
|
||||
self._client_id = self.user + '@' + self.domain.split(".")[0] + '/' + self.resource
|
||||
self.username_pw_set(self.user + '@' + self.domain, secret)
|
||||
self.ready_flag = Event()
|
||||
|
||||
def connect_and_wait_until_ready(self):
|
||||
#self._on_log = self.on_log #This provides more logging than needed, even for debug
|
||||
self._on_message = self._handle_ctl_mqtt
|
||||
self._on_connect = self.on_connect
|
||||
#TODO: This is pretty insecure and accepts any cert, maybe actually check?
|
||||
ssl_ctx = ssl.create_default_context()
|
||||
ssl_ctx.check_hostname = False
|
||||
ssl_ctx.verify_mode = ssl.CERT_NONE
|
||||
self.tls_set_context(ssl_ctx)
|
||||
self.tls_insecure_set(True)
|
||||
self.connect(self.hostname, self.port)
|
||||
self.loop_start()
|
||||
self.wait_until_ready()
|
||||
|
||||
def subscribe_to_ctls(self, function):
|
||||
self.ctl_subscribers.append(function)
|
||||
|
||||
def _disconnect(self):
|
||||
self.disconnect() #disconnect mqtt connection
|
||||
self.scheduler.empty() #Clear schedule queue
|
||||
|
||||
def _run_scheduled_func(self, timer_seconds, timer_function):
|
||||
timer_function()
|
||||
self.schedule(timer_seconds, timer_function)
|
||||
|
||||
def schedule(self, timer_seconds, timer_function):
|
||||
self.scheduler.enter(timer_seconds, 1, self._run_scheduled_func,(timer_seconds, timer_function))
|
||||
if not self.scheduler_thread.isAlive():
|
||||
self.scheduler_thread.start()
|
||||
|
||||
def wait_until_ready(self):
|
||||
self.ready_flag.wait()
|
||||
|
||||
def on_connect(self, client, userdata, flags, rc):
|
||||
if rc != 0:
|
||||
LOGGER.error("EcoVacsMQTT - error connecting with MQTT Return {}".format(rc))
|
||||
raise RuntimeError("EcoVacsMQTT - error connecting with MQTT Return {}".format(rc))
|
||||
else:
|
||||
LOGGER.debug("EcoVacsMQTT - Connected with result code "+str(rc))
|
||||
LOGGER.debug("EcoVacsMQTT - Subscribing to all")
|
||||
self.subscribe('iot/atr/+/' + self.vacuum['did'] + '/' + self.vacuum['class'] + '/' + self.vacuum['resource'] + '/+', qos=0)
|
||||
self.ready_flag.set()
|
||||
|
||||
#def on_log(self, client, userdata, level, buf): #This is very noisy and verbose
|
||||
# LOGGER.debug("EcoVacsMQTT Log: {} ".format(buf))
|
||||
|
||||
def send_ping(self):
|
||||
LOGGER.debug("*** MQTT sending ping ***")
|
||||
rc = self._send_simple_command(MQTTPublish.paho.PINGREQ)
|
||||
if rc == MQTTPublish.paho.MQTT_ERR_SUCCESS:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def send_command(self, action, recipient):
|
||||
if action.name == "Clean": #For handling Clean when action not specified (i.e. CLI)
|
||||
action.args['clean']['act'] = CLEAN_ACTION_TO_ECOVACS['start'] #Inject a start action
|
||||
c = self._wrap_command(action, recipient)
|
||||
LOGGER.debug('Sending command {0}'.format(c))
|
||||
self._handle_ctl_api(action,
|
||||
self.__call_iotdevmanager_api(c ,verify_ssl=self.verify_ssl )
|
||||
)
|
||||
|
||||
def _wrap_command(self, cmd, recipient):
|
||||
#Remove the td from ctl xml for RestAPI
|
||||
payloadxml = cmd.to_xml()
|
||||
payloadxml.attrib.pop("td")
|
||||
return {
|
||||
'auth': {
|
||||
'realm': EcoVacsAPI.REALM,
|
||||
'resource': self.resource,
|
||||
'token': self.secret,
|
||||
'userid': self.user,
|
||||
'with': 'users',
|
||||
},
|
||||
"cmdName": cmd.name,
|
||||
"payload": ET.tostring(payloadxml).decode(),
|
||||
|
||||
"payloadType": "x",
|
||||
"td": "q",
|
||||
"toId": recipient,
|
||||
"toRes": self.vacuum['resource'],
|
||||
"toType": self.vacuum['class']
|
||||
}
|
||||
|
||||
def __call_iotdevmanager_api(self, args, verify_ssl=True):
|
||||
LOGGER.debug("calling iotdevmanager api with {}".format(args))
|
||||
params = {}
|
||||
params.update(args)
|
||||
url = (EcoVacsAPI.PORTAL_URL_FORMAT + "/iot/devmanager.do").format(continent=self.continent)
|
||||
response = None
|
||||
try: #The RestAPI sometimes doesnt provide a response depending on command, reduce timeout to 3 to accomodate and make requests faster
|
||||
response = requests.post(url, json=params, timeout=3, verify=verify_ssl) #May think about having timeout as an arg that could be provided in the future
|
||||
except requests.exceptions.ReadTimeout:
|
||||
LOGGER.debug("call to iotdevmanager failed with ReadTimeout")
|
||||
return {}
|
||||
json = response.json()
|
||||
if json['ret'] == 'ok':
|
||||
return json
|
||||
elif json['ret'] == 'fail':
|
||||
if 'debug' in json:
|
||||
if json['debug'] == 'wait for response timed out':
|
||||
#TODO - Maybe handle timeout for IOT better in the future
|
||||
LOGGER.error("call to iotdevmanager failed with {}".format(json))
|
||||
return {}
|
||||
else:
|
||||
#TODO - Not sure if we want to raise an error yet, just return empty for now
|
||||
LOGGER.error("call to iotdevmanager failed with {}".format(json))
|
||||
return {}
|
||||
#raise RuntimeError(
|
||||
#"failure {} ({}) for call {} and parameters {}".format(json['error'], json['errno'], function, params))
|
||||
|
||||
def _handle_ctl_api(self, action, message):
|
||||
if not message == {}:
|
||||
resp = self._ctl_to_dict_api(action, message['resp'])
|
||||
if resp is not None:
|
||||
for s in self.ctl_subscribers:
|
||||
s(resp)
|
||||
|
||||
def _ctl_to_dict_api(self, action, xmlstring):
|
||||
xml = ET.fromstring(xmlstring)
|
||||
xmlchild = xml.getchildren()
|
||||
if len(xmlchild) > 0:
|
||||
result = xmlchild[0].attrib.copy()
|
||||
#Fix for difference in XMPP vs API response
|
||||
#Depending on the report will use the tag and add "report" to fit the mold of sucks library
|
||||
if xmlchild[0].tag == "clean":
|
||||
result['event'] = "CleanReport"
|
||||
elif xmlchild[0].tag == "charge":
|
||||
result['event'] = "ChargeState"
|
||||
elif xmlchild[0].tag == "battery":
|
||||
result['event'] = "BatteryInfo"
|
||||
else: #Default back to replacing Get from the api cmdName
|
||||
result['event'] = action.name.replace("Get","",1)
|
||||
else:
|
||||
result = xml.attrib.copy()
|
||||
result['event'] = action.name.replace("Get","",1)
|
||||
if 'ret' in result: #Handle errors as needed
|
||||
if result['ret'] == 'fail':
|
||||
if action.name == "Charge": #So far only seen this with Charge, when already docked
|
||||
result['event'] = "ChargeState"
|
||||
for key in result:
|
||||
if not RepresentsInt(result[key]): #Fix to handle negative int values
|
||||
result[key] = stringcase.snakecase(result[key])
|
||||
return result
|
||||
|
||||
def _handle_ctl_mqtt(self, client, userdata, message):
|
||||
#LOGGER.debug("EcoVacs MQTT Received Message on Topic: {} - Message: {}".format(message.topic, str(message.payload.decode("utf-8"))))
|
||||
as_dict = self._ctl_to_dict_mqtt(message.topic, str(message.payload.decode("utf-8")))
|
||||
if as_dict is not None:
|
||||
for s in self.ctl_subscribers:
|
||||
s(as_dict)
|
||||
|
||||
def _ctl_to_dict_mqtt(self, topic, xmlstring):
|
||||
#I haven't seen the need to fall back to data within the topic (like we do with IOT rest call actions), but it is here in case of future need
|
||||
xml = ET.fromstring(xmlstring) #Convert from string to xml (like IOT rest calls), other than this it is similar to XMPP
|
||||
#Including changes from jasonarends @ 28da7c2 below
|
||||
result = xml.attrib.copy()
|
||||
if 'td' not in result:
|
||||
# This happens for commands with no response data, such as PlaySound
|
||||
# Handle response data with no 'td'
|
||||
if 'type' in result: # single element with type and val
|
||||
result['event'] = "LifeSpan" # seems to always be LifeSpan type
|
||||
else:
|
||||
if len(xml) > 0: # case where there is child element
|
||||
if 'clean' in xml[0].tag:
|
||||
result['event'] = "CleanReport"
|
||||
elif 'charge' in xml[0].tag:
|
||||
result['event'] = "ChargeState"
|
||||
elif 'battery' in xml[0].tag:
|
||||
result['event'] = "BatteryInfo"
|
||||
else:
|
||||
return
|
||||
result.update(xml[0].attrib)
|
||||
else: # for non-'type' result with no child element, e.g., result of PlaySound
|
||||
return
|
||||
else: # response includes 'td'
|
||||
result['event'] = result.pop('td')
|
||||
if xml:
|
||||
result.update(xml[0].attrib)
|
||||
for key in result:
|
||||
#Check for RepresentInt to handle negative int values, and ',' for ignoring position updates
|
||||
if not RepresentsInt(result[key]) and ',' not in result[key]:
|
||||
result[key] = stringcase.snakecase(result[key])
|
||||
return result
|
||||
@@ -1,143 +0,0 @@
|
||||
import stringcase
|
||||
import random
|
||||
from threading import Event
|
||||
from sleekxmppfs import ClientXMPP, Callback, MatchXPath
|
||||
from sleekxmppfs.xmlstream import ET
|
||||
#from sleekxmppfs.exceptions import XMPPError
|
||||
from .const import LOGGER
|
||||
|
||||
#This is used by EcoVacsIOTMQ and EcoVacsXMPP for _ctl_to_dict
|
||||
def RepresentsInt(stringvar):
|
||||
try:
|
||||
int(stringvar)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
class EcoVacsXMPP(ClientXMPP):
|
||||
def __init__(self, user, domain, resource, secret, continent, vacuum, server_address=None ):
|
||||
ClientXMPP.__init__(self, "{}@{}/{}".format(user, domain,resource), '0/' + resource + '/' + secret) #Init with resource to bind it
|
||||
self.user = user
|
||||
self.domain = domain
|
||||
self.boundjid.resource = resource
|
||||
self.continent = continent
|
||||
self.vacuum = vacuum
|
||||
self.credentials['authzid'] = user
|
||||
if server_address is None:
|
||||
self.server_address = ('msg-{}.ecouser.net'.format(self.continent), '5223')
|
||||
else:
|
||||
self.server_address = server_address
|
||||
self.add_event_handler("session_start", self.session_start)
|
||||
self.ctl_subscribers = []
|
||||
self.ready_flag = Event()
|
||||
|
||||
def wait_until_ready(self):
|
||||
self.ready_flag.wait()
|
||||
|
||||
def session_start(self, event):
|
||||
LOGGER.debug("----------------- starting session ----------------")
|
||||
LOGGER.debug("event = {}".format(event))
|
||||
self.register_handler(Callback("general",
|
||||
MatchXPath('{jabber:client}iq/{com:ctl}query/{com:ctl}'),
|
||||
self._handle_ctl))
|
||||
# register a ping handler, not really needed but keeps from errors being thrown
|
||||
self.register_handler(Callback("Ping",
|
||||
MatchXPath('{jabber:client}iq/{urn:xmpp:ping}ping/{urn:xmpp:ping}'),
|
||||
self._handle_ping))
|
||||
self.ready_flag.set()
|
||||
|
||||
def subscribe_to_ctls(self, function):
|
||||
self.ctl_subscribers.append(function)
|
||||
|
||||
def _handle_ctl(self, message):
|
||||
the_good_part = message.get_payload()[0][0]
|
||||
as_dict = self._ctl_to_dict(the_good_part)
|
||||
if as_dict is not None:
|
||||
for s in self.ctl_subscribers:
|
||||
s(as_dict)
|
||||
|
||||
def _ctl_to_dict(self, xml):
|
||||
#Including changes from jasonarends @ 28da7c2 below
|
||||
result = xml.attrib.copy()
|
||||
childxml = None
|
||||
try: # check for child xml
|
||||
childxml = xml[0]
|
||||
except IndexError:
|
||||
LOGGER.debug("No child xml")
|
||||
if 'td' not in result:
|
||||
# Handle response data with no 'td'
|
||||
if 'type' in result: # single element with type and val
|
||||
result['event'] = "LifeSpan" # seems to always be LifeSpan type
|
||||
else:
|
||||
if childxml is not None:
|
||||
if 'clean' in childxml.tag:
|
||||
result['event'] = "CleanReport"
|
||||
elif 'charge' in childxml.tag:
|
||||
result['event'] = "ChargeState"
|
||||
elif 'battery' in childxml.tag:
|
||||
result['event'] = "BatteryInfo"
|
||||
else:
|
||||
return
|
||||
result.update(childxml.attrib)
|
||||
else: # for non-'type' result with no child element, e.g., result of PlaySound
|
||||
return
|
||||
else: # response includes 'td'
|
||||
result['event'] = result.pop('td')
|
||||
if xml:
|
||||
result.update(xml[0].attrib) # reponses with td seem to always have child component
|
||||
for key in result:
|
||||
#Check for RepresentInt to handle negative int values, and ',' for ignoring position updates
|
||||
if not RepresentsInt(result[key]) and ',' not in result[key]:
|
||||
result[key] = stringcase.snakecase(result[key])
|
||||
return result
|
||||
|
||||
def register_callback(self, userdata, message):
|
||||
self.register_handler(Callback(kind,
|
||||
MatchXPath('{jabber:client}iq/{com:ctl}query/{com:ctl}ctl[@td="' + kind + '"]'),
|
||||
function))
|
||||
|
||||
def send_command(self, xml, recipient):
|
||||
c = self._wrap_command(xml, recipient)
|
||||
LOGGER.debug('Sending command {0}'.format(c))
|
||||
c.send()
|
||||
|
||||
def _wrap_command(self, ctl, recipient):
|
||||
q = self.make_iq_query(xmlns=u'com:ctl', ito=recipient, ifrom=self._my_address())
|
||||
q['type'] = 'set'
|
||||
if not "id" in ctl.attrib:
|
||||
ctl.attrib["id"] = self.getReqID() #If no ctl id provided, add an id to the ctl. This was required for the ozmo930 and shouldn't hurt others
|
||||
for child in q.xml:
|
||||
if child.tag.endswith('query'):
|
||||
child.append(ctl)
|
||||
return q
|
||||
|
||||
def getReqID(self, customid="0"): #Generate a somewhat random string for request id, with minium 8 chars. Works similar to ecovacs app.
|
||||
if customid != "0":
|
||||
return "{}".format(customid) #return provided id as string
|
||||
else:
|
||||
rtnval = str(random.randint(1,50))
|
||||
while len(str(rtnval)) <= 8:
|
||||
rtnval = "{}{}".format(rtnval,random.randint(0,50))
|
||||
return "{}".format(rtnval) #return as string
|
||||
|
||||
def _my_address(self):
|
||||
if not self.vacuum['iotmq']:
|
||||
return self.user + '@' + self.domain + '/' + self.boundjid.resource
|
||||
else:
|
||||
return self.user + '@' + self.domain + '/' + self.resource
|
||||
|
||||
def send_ping(self, to):
|
||||
q = self.make_iq_get(ito=to, ifrom=self._my_address())
|
||||
q.xml.append(ET.Element('ping', {'xmlns': 'urn:xmpp:ping'}))
|
||||
LOGGER.debug("*** sending ping ***")
|
||||
q.send()
|
||||
|
||||
# used some code from a sleekxmppfs plugin, seems to work fine
|
||||
def _handle_ping(self, iq):
|
||||
LOGGER.debug("Pinged by %s", iq['from'])
|
||||
iq.reply().send()
|
||||
|
||||
def connect_and_wait_until_ready(self):
|
||||
self.connect(self.server_address)
|
||||
self.process()
|
||||
self.wait_until_ready()
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -5,12 +5,9 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
#sucks
|
||||
from . import sucks
|
||||
from . import sucksbumper
|
||||
|
||||
from homeassistant.components.vacuum import (
|
||||
VacuumEntity,
|
||||
VacuumEntityFeature,
|
||||
)
|
||||
from homeassistant.components.vacuum import VacuumEntity, VacuumEntityFeature
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.icon import icon_for_battery_level
|
||||
@@ -23,7 +20,7 @@ _LOGGER = logging.getLogger(__name__)
|
||||
ATTR_ERROR = "error"
|
||||
ATTR_COMPONENT_PREFIX = "component_"
|
||||
|
||||
"""
|
||||
|
||||
def setup_platform(
|
||||
hass: HomeAssistant,
|
||||
config: ConfigType,
|
||||
@@ -36,33 +33,15 @@ def setup_platform(
|
||||
vacuums.append(EcovacsVacuum(device))
|
||||
_LOGGER.debug("Adding Ecovacs Vacuums to Home Assistant: %s", vacuums)
|
||||
add_entities(vacuums, True)
|
||||
"""
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
config_entry: ConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
discovery_info: DiscoveryInfoType | None = None,
|
||||
) -> None:
|
||||
"""Set up the Ecovacs vacuums."""
|
||||
coordinator: SharkIqUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
|
||||
devices: Iterable[SharkIqVacuum] = coordinator.shark_vacs.values()
|
||||
device_names = [d.name for d in devices]
|
||||
LOGGER.debug(
|
||||
"Found %d Shark IQ device(s): %s",
|
||||
len(device_names),
|
||||
", ".join([d.name for d in devices]),
|
||||
)
|
||||
async_add_entities([SharkVacuumEntity(d, coordinator) for d in devices])
|
||||
|
||||
class EcovacsVacuum(VacuumEntity):
|
||||
"""Ecovacs Vacuums such as Deebot."""
|
||||
|
||||
_attr_fan_speed_list = [sucks.FAN_SPEED_NORMAL, sucks.FAN_SPEED_HIGH]
|
||||
_attr_fan_speed_list = [sucksbumper.FAN_SPEED_NORMAL, sucksbumper.FAN_SPEED_HIGH]
|
||||
_attr_should_poll = False
|
||||
_attr_supported_features = (
|
||||
VacuumEntityFeature.BATTERY
|
||||
| VacuumEntityFeature.FAN_SPEED
|
||||
| VacuumEntityFeature.RETURN_HOME
|
||||
| VacuumEntityFeature.CLEAN_SPOT
|
||||
| VacuumEntityFeature.STOP
|
||||
@@ -71,10 +50,10 @@ class EcovacsVacuum(VacuumEntity):
|
||||
| VacuumEntityFeature.LOCATE
|
||||
| VacuumEntityFeature.STATUS
|
||||
| VacuumEntityFeature.SEND_COMMAND
|
||||
|
||||
| VacuumEntityFeature.FAN_SPEED
|
||||
)
|
||||
|
||||
def __init__(self, device: sucks.VacBot) -> None:
|
||||
def __init__(self, device: sucksbumper.VacBot) -> None:
|
||||
"""Initialize the Ecovacs Vacuum."""
|
||||
self.device = device
|
||||
self.device.connect_and_wait_until_ready()
|
||||
@@ -96,6 +75,7 @@ class EcovacsVacuum(VacuumEntity):
|
||||
|
||||
def on_error(self, error):
|
||||
"""Handle an error event from the robot.
|
||||
|
||||
This will not change the entity's state. If the error caused the state
|
||||
to change, that will come through as a separate on_status event
|
||||
"""
|
||||
@@ -132,7 +112,7 @@ class EcovacsVacuum(VacuumEntity):
|
||||
def return_to_base(self, **kwargs: Any) -> None:
|
||||
"""Set the vacuum cleaner to return to the dock."""
|
||||
|
||||
self.device.run(sucks.Charge())
|
||||
self.device.run(sucksbumper.Charge())
|
||||
|
||||
@property
|
||||
def battery_icon(self) -> str:
|
||||
@@ -146,6 +126,7 @@ class EcovacsVacuum(VacuumEntity):
|
||||
"""Return the battery level of the vacuum cleaner."""
|
||||
if self.device.battery_status is not None:
|
||||
return self.device.battery_status * 100
|
||||
|
||||
return super().battery_level
|
||||
|
||||
@property
|
||||
@@ -155,7 +136,8 @@ class EcovacsVacuum(VacuumEntity):
|
||||
|
||||
def turn_on(self, **kwargs: Any) -> None:
|
||||
"""Turn the vacuum on and start cleaning."""
|
||||
self.device.run(sucks.Clean())
|
||||
|
||||
self.device.run(sucksbumper.Clean())
|
||||
|
||||
def turn_off(self, **kwargs: Any) -> None:
|
||||
"""Turn the vacuum off stopping the cleaning and returning home."""
|
||||
@@ -163,20 +145,24 @@ class EcovacsVacuum(VacuumEntity):
|
||||
|
||||
def stop(self, **kwargs: Any) -> None:
|
||||
"""Stop the vacuum cleaner."""
|
||||
self.device.run(sucks.Stop())
|
||||
|
||||
self.device.run(sucksbumper.Stop())
|
||||
|
||||
def clean_spot(self, **kwargs: Any) -> None:
|
||||
"""Perform a spot clean-up."""
|
||||
self.device.run(sucks.Spot())
|
||||
|
||||
self.device.run(sucksbumper.Spot())
|
||||
|
||||
def locate(self, **kwargs: Any) -> None:
|
||||
"""Locate the vacuum cleaner."""
|
||||
self.device.run(sucks.PlaySound())
|
||||
|
||||
self.device.run(sucksbumper.PlaySound())
|
||||
|
||||
def set_fan_speed(self, fan_speed: str, **kwargs: Any) -> None:
|
||||
"""Set fan speed."""
|
||||
if self.is_on:
|
||||
self.device.run(sucks.Clean(mode=self.device.clean_status, speed=fan_speed))
|
||||
|
||||
self.device.run(sucksbumper.Clean(mode=self.device.clean_status, speed=fan_speed))
|
||||
|
||||
def send_command(
|
||||
self,
|
||||
@@ -185,14 +171,16 @@ class EcovacsVacuum(VacuumEntity):
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Send a command to a vacuum cleaner."""
|
||||
self.device.run(sucks.VacBotCommand(command, params))
|
||||
self.device.run(sucksbumper.VacBotCommand(command, params))
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self) -> dict[str, Any]:
|
||||
"""Return the device-specific state attributes of this vacuum."""
|
||||
data: dict[str, Any] = {}
|
||||
data[ATTR_ERROR] = self._error
|
||||
|
||||
for key, val in self.device.components.items():
|
||||
attr_name = ATTR_COMPONENT_PREFIX + key
|
||||
data[attr_name] = int(val * 100)
|
||||
|
||||
return data
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"name": "EcovacsBumper",
|
||||
"domains": ["vacuum"],
|
||||
"render_readme": true
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
language: python
|
||||
python:
|
||||
- "3.4"
|
||||
- "3.5"
|
||||
- "3.6"
|
||||
install:
|
||||
- pip install -e .[dev]
|
||||
|
||||
script: nosetests
|
||||
@@ -1,46 +0,0 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at william-sucks@scissor.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/4/
|
||||
@@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -1,24 +0,0 @@
|
||||
environment:
|
||||
|
||||
matrix:
|
||||
|
||||
# For Python versions available on Appveyor, see
|
||||
# http://www.appveyor.com/docs/installed-software#python
|
||||
|
||||
- PYTHON: "C:\\Python35"
|
||||
|
||||
install:
|
||||
# We need wheel installed to build wheels
|
||||
- "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
|
||||
- python --version
|
||||
- pip install -e .[dev]
|
||||
|
||||
build: off
|
||||
|
||||
test_script:
|
||||
# Put your test command here.
|
||||
# Note that you must use the environment variable %PYTHON% to refer to
|
||||
# the interpreter you're using - Appveyor does not do anything special
|
||||
# to put the Python version you want to use on PATH.
|
||||
- "nosetests"
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
# Development resources and information for Ecovacs Robot Vacuums
|
||||
|
||||
For a description of the Ecovacs API protocols, see
|
||||
[the protocol documentation](protocol.md)
|
||||
|
||||
|
||||
## Getting started with Sucks
|
||||
|
||||
If you'd like to join in on developing, I recommend checking out the code,
|
||||
[setting up a virtual environment](https://packaging.python.org/guides/installing-using-pip-and-virtualenv/),
|
||||
and installing this package in dev mode. You can confirm your environment
|
||||
works by running the tests. The commands for that look something like
|
||||
like
|
||||
|
||||
```
|
||||
% python3 -m virtualenv env
|
||||
% source env/bin/activate
|
||||
% pip install -e .[dev]
|
||||
% nosetests
|
||||
```
|
||||
|
||||
If the test run is successful, it will say something like
|
||||
|
||||
```
|
||||
Ran 44 tests in 0.734s
|
||||
|
||||
OK
|
||||
```
|
||||
|
||||
Current test are not yet
|
||||
comprehensive, as the integrated nature of this makes it difficult.
|
||||
But we aim to reduce that problem over time, so please add tests as you go.
|
||||
|
||||
|
||||
## MITM XMPP traffic between the Android or iOS App and the Ecovacs server
|
||||
|
||||
1. Download [xmpppeek](https://www.beneaththewaves.net/Software/XMPPPeek.html)
|
||||
2. Create a self-signed certificate with the following command
|
||||
|
||||
`openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes`
|
||||
|
||||
3. Edit xmpppeek.py and change port to 5223
|
||||
|
||||
4. Look at the [the protocol documentation](protocol.md) for information on which
|
||||
Ecovacs XMPP server is the right one for your Country. For example, a US user will
|
||||
be using msg-na.ecouser.net. Find and note the IP address for the server.
|
||||
|
||||
5. Make sure the mobile App talks to your machine instead of the server. This can be
|
||||
accomplished modifying your router's DNS configuration to have the Ecovacs domain
|
||||
name point to your IP.
|
||||
|
||||
6. Run xmppeek as follows.
|
||||
|
||||
`python ./xmpppeek.py <ECOVACS XMPP SERVER IP> cert.pem key.pem`
|
||||
|
||||
|
||||
## Reset robot to factory settings
|
||||
|
||||
Ecovacs robots have an undocumented hardware reset button that can be useful
|
||||
in case you run into trouble. Under the dustbin lid there is a small round hole
|
||||
that hides the button (confirmed on models M80 and M81).
|
||||
|
||||
With the robot on, use something thin like a paper clip or needle to press and
|
||||
hold the reset button. After about three seconds the robot will beep three times
|
||||
to indicate successful reset.
|
||||
|
||||
You will have to delete the robot from the mobile app and go through the setup
|
||||
process.
|
||||
@@ -1,86 +0,0 @@
|
||||
import base64
|
||||
import re
|
||||
import sys
|
||||
|
||||
# a script to take an xmpppeek log of a Ecovacs app session with a Deebot N79 and strip out some of the nonsense,
|
||||
# including any private identifiers
|
||||
|
||||
source_ip = None
|
||||
userid = None
|
||||
resourceid = None
|
||||
robotid = None
|
||||
auth_glob = None
|
||||
|
||||
for line in sys.stdin:
|
||||
# remove the garbage
|
||||
line = line.rstrip()
|
||||
line = re.sub("\[\\d{4}-\\d{2}-\\d{2} ", '', line)
|
||||
line = re.sub("\.\\d{6}-\\d{2}:\\d{2}\] \[", ' ', line)
|
||||
line = re.sub("]$", ' ', line)
|
||||
line = re.sub("\(([SC])2[SC]\) [.0-9]+:\\d+ -> [.0-9]+:\d+\]", '\\1', line)
|
||||
line = re.sub("\}\}\}", '', line)
|
||||
line = re.sub("\{\{\{", '', line)
|
||||
|
||||
# find the private bits and remove them
|
||||
if not source_ip:
|
||||
match = re.search('Client connect from ([.0-9]+)', line)
|
||||
if match:
|
||||
source_ip = match.group(1)
|
||||
if not userid:
|
||||
match = re.search('(20\d{6}[0-9a-f]{13})@ecouser.net/([0-9a-f]{8})', line)
|
||||
if match:
|
||||
userid = match.group(1)
|
||||
resourceid = match.group(2)
|
||||
if not robotid:
|
||||
match = re.search('(E\d{8,})@126.ecorobot.net/atom', line)
|
||||
if match:
|
||||
robotid = match.group(1)
|
||||
if not auth_glob:
|
||||
match = re.search('<auth mechanism="PLAIN" xmlns="urn:ietf:params:xml:ns:xmpp-sasl">([-A-Za-z0-9+/=]+)</auth>',
|
||||
line)
|
||||
if match:
|
||||
auth_glob = match.group(1)
|
||||
if source_ip:
|
||||
line = re.sub(source_ip, 'SOURCEIP', line)
|
||||
if userid:
|
||||
line = re.sub(userid, 'USERID', line)
|
||||
if resourceid:
|
||||
line = re.sub(resourceid, 'RESOURCEID', line)
|
||||
if robotid:
|
||||
line = re.sub(robotid, 'ROBOTID', line)
|
||||
if auth_glob:
|
||||
line = re.sub(auth_glob, 'AUTHGLOB', line)
|
||||
|
||||
# translate client commmands
|
||||
|
||||
line = re.sub(
|
||||
'<iq id="(\d+)" to="ROBOTID@126.ecorobot.net/atom" from="USERID@ecouser.net/RESOURCEID" type="set"><query xmlns="com:ctl">(<ctl .*>)</query></iq>',
|
||||
'id=\\1 command=\\2', line)
|
||||
|
||||
# translate server responses
|
||||
|
||||
line = re.sub(
|
||||
'<iq to="USERID@ecouser.net/RESOURCEID" type="result" id="(\d+)" from="ROBOTID@126.ecorobot.net/atom"/>',
|
||||
'id=\\1 result =empty', line)
|
||||
line = re.sub(
|
||||
'<iq to="USERID@ecouser.net/RESOURCEID" type="set" id="(\d+)" from="ROBOTID@126.ecorobot.net/atom"><query xmlns="com:ctl"><ctl id="(\d+)" ret="([^"]+)"/></query></iq>',
|
||||
'id=\\1 id=\\2 result=\\3', line)
|
||||
line = re.sub(
|
||||
'<iq to="USERID@ecouser.net/RESOURCEID" type="set" id="(\d+)" from="ROBOTID@126.ecorobot.net/atom"><query xmlns="com:ctl">(<ctl .*)</query></iq>',
|
||||
'id=\\1 response=\\2', line)
|
||||
|
||||
print(line)
|
||||
|
||||
# per SASL plain auth: https://tools.ietf.org/html/rfc4616
|
||||
(authentication_id, authorization_id, password) = base64.b64decode(auth_glob).decode().split(sep='\0')
|
||||
|
||||
# no idea what the leading field is, and the resource appears to be the same
|
||||
(mystery, resource, secret) = password.split('/')
|
||||
|
||||
print("------------------")
|
||||
print("sample config:")
|
||||
print("user=" + userid)
|
||||
print("domain=ecouser.net")
|
||||
print("resource=" + resourceid)
|
||||
print("secret=" + secret)
|
||||
print("vacuum=" + robotid + "@126.ecorobot.net")
|
||||
@@ -1,402 +0,0 @@
|
||||
# Ecovacs Protocol
|
||||
|
||||
Depending on the device there are a few different protocols involved in the communication between the client and Ecovacs systems. There are a series of HTTPS requests
|
||||
used to log in and find devices. Once logged in, you get a token that is
|
||||
used for connecting to different services. In many cases this involves connecting to an XMPP server, which mediates communication with the
|
||||
vacuum. That's right, your robot housecleaner, like an errant teen, spends
|
||||
all its free time hanging out in an internet chat room.
|
||||
|
||||
This is all taken from MITMing the Android app. The iOS app appears to
|
||||
follow the same protocol conventions.
|
||||
|
||||
|
||||
## Location
|
||||
|
||||
It appears that Ecovacs have broken up their API servers by location. Some
|
||||
are designated by country, others by continent. All appear to use the
|
||||
two-letter ISO codes, but at this time it doesn't look like all codes
|
||||
map to valid servers.
|
||||
|
||||
The HTTPS and XMPP servers do not appear to be following the same convention.
|
||||
For example, a Canadian user must authenticate on country-specific HTTPS
|
||||
server, but XMPP commands work both on the worldwide server
|
||||
msg-ww.ecouser.net) and the North America server (msg-na.ecouser.net)
|
||||
|
||||
|
||||
## HTTPS
|
||||
|
||||
There are two sorts of URLs in the basic login flow. The first set use
|
||||
a format like this:
|
||||
|
||||
`
|
||||
https://eco-{country}-api.ecovacs.com/v1/private/{country}/{lang}/{deviceId}/{appCode}/{appVersion}/{channel}/{deviceType}
|
||||
`
|
||||
|
||||
They also have a complicated API request signature that seems overelaborate
|
||||
to me. See the Python code for more details.
|
||||
|
||||
1. GET eco-us-api.ecovacs.com ... common/checkVersion - appears to just check
|
||||
the app version
|
||||
2. GET eco-us-api.ecovacs.com ... user/login - Sends encrypted versions of
|
||||
the username and password. The response is some json containing a uid and
|
||||
access token.
|
||||
3. GET eco-us-api.ecovacs.com ... user/getAuthCode - sends uid, accessToken;
|
||||
gets back an auth code
|
||||
|
||||
*Under mysterious circumstances, for some people the getAuthCode call will
|
||||
return a different userId than is passed in. In that case, apparently the new userId should be used for future calls, or an Auth 1004 error results.*
|
||||
|
||||
Now we switch to posting to a different server, and the request and response
|
||||
style change substantially. I think of this at the user server, or perhaps
|
||||
the XMPP/device server.
|
||||
|
||||
`
|
||||
https://portal-{continent}.ecouser.net/api
|
||||
`
|
||||
|
||||
There are a few different endpoints within the API that have been seen and are used in the library:
|
||||
|
||||
|
||||
| Endpoint | Description |
|
||||
| - | - |
|
||||
| /users/user.do | Handles user / account functions |
|
||||
| /iot/devmanager.do | Provides a RestAPI that handles sending commands to "IOTMQ" devices |
|
||||
| /pim/product/getProductIotMap | Provides a listing of "IOT" Products |
|
||||
|
||||
|
||||
1. POST portal-na.ecouser.net/api/users/user.do loginByItToken - trades the
|
||||
authCode from the previous call for yet another token
|
||||
5. POST ne-na.ecouser.net:8018/notify_engine.do - not sure what this is
|
||||
for; my script skips this and seems to work fine
|
||||
6. POST portal-na.ecouser.net/api/users/user.do GetDeviceList - Using the token
|
||||
from step 4, gets the list of devices; that's needed for talking to the
|
||||
vacuum via XMPP
|
||||
7. POST
|
||||
portal-na.ecouser.net/api/pim/product/getProductIotMap
|
||||
getProductIotMap - Provides a list of "IOT" products, it isn't clear what the app uses these for at this time, possibly for determining how to get updates.
|
||||
|
||||
At this point depending on your device you will connect to either an XMPP server, or an MQTT server.
|
||||
|
||||
| "IOT XMPP" Products | "IOT MQ" Products |
|
||||
| - | - |
|
||||
| Connect to an XMPP server to send commands to devices and receive status results | Connect to an MQTT server to subscribe to status messages and results. A Rest API is utilized to send commands to devices, but can also be used to obtain statuses. |
|
||||
|
||||
|
||||
## XMPP - ("IOT XMPP")
|
||||
|
||||
The app establishes a connection to an XMPP server and logs in using
|
||||
a secret that comes from the earlier HTTPS calls. It then sends XMPP IQ
|
||||
commands. It describes them as queries, but they all contain "ctl"
|
||||
elements that appear to be commands.
|
||||
|
||||
The Android App uses the following XMPP messaging servers:
|
||||
|
||||
|Country|URL|
|
||||
| - | - |
|
||||
|CH|msg.ecouser.net|
|
||||
|TW, MY, JP, SG, TH, HK, IN, KR|msg-as.ecouser.net|
|
||||
|US|msg-na.ecouser.net|
|
||||
|FR, ES, UK, NO, MX, DE, PT, CH, AU, IT, NL, SE, BE, DK|msg-eu.ecouser.net|
|
||||
|Any other|msg-ww.ecouser.net|
|
||||
|
||||
## MQTT - ("IOT MQ")
|
||||
|
||||
The app establishes a connection to an MQTT server and logs in using
|
||||
a secret that comes from the earlier HTTPS calls.
|
||||
|
||||
It then subscribes to a topic where various status and result messages are published by the device.
|
||||
The topic looks like this:
|
||||
|
||||
`
|
||||
iot/atr/+/{deviceID}/{deviceClass}/{deviceResource}/+
|
||||
`
|
||||
|
||||
It is believed the MQTT servers mirror the XMPP servers, but only the NA and WW have been tested so far.
|
||||
|
||||
|Country|URL|
|
||||
|-|-|
|
||||
|US|mq-na.ecouser.net|
|
||||
|"World-wide"|mq-ww.ecouser.net|
|
||||
|
||||
## Rest API - ("IOT MQ")
|
||||
|
||||
For IOT MQ devices the app sends commands to the device over a Rest API utilizing the secret that comes from the earlier HTTPS calls. This API has only been tested from an "IOT MQ" device, but could possibly work for other devices as well.
|
||||
|
||||
The Rest API utilizes the same portal URL as used previously, but with the iot/devmanager endpoint:
|
||||
`
|
||||
https://portal-{continent}.ecouser.net/api/iot/devmanager.do
|
||||
`
|
||||
Commands are sent via POST in the format of:
|
||||
```json
|
||||
{
|
||||
"auth": {
|
||||
"realm": "ecouser.net",
|
||||
"resource": "resource",
|
||||
"token": "token",
|
||||
"userid": "userid",
|
||||
"with": "users",
|
||||
},
|
||||
"cmdName": "cmd.name",
|
||||
"payload": "cmd.args",
|
||||
"payloadType": "x",
|
||||
"td": "q",
|
||||
"toId": "vacuum.serial",
|
||||
"toRes": "vacuum.resource",
|
||||
"toType": "vacuum.class"
|
||||
}
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
### Cleaning
|
||||
|
||||
**Command**
|
||||
- `<ctl td="Clean"><clean type="auto" speed="standard"/></ctl>`
|
||||
|
||||
**State**
|
||||
- **Request** `<ctl td="GetCleanState" />`
|
||||
- **Response** `<ctl td="CleanReport"><clean type="stop" speed="standard" /></ctl>`
|
||||
- type `auto` automatic cleaning program
|
||||
- type `border` edge cleaning program
|
||||
- type `spot` spot cleaning program
|
||||
- type `singleroom` cleaning a single room
|
||||
- type `stop` bot at full stop
|
||||
- type `SpotArea` cleaning a mapped room (mapping robots only)
|
||||
- speed `standard` regular fan speed (suction)
|
||||
- speed `strong` high fan speed (suction)
|
||||
|
||||
|
||||
### Charging
|
||||
|
||||
**Command**
|
||||
- `<query xmlns="com:ctl"><ctl td="Charge"><charge type="go"/></ctl>`
|
||||
- `go` order bot to return to charger
|
||||
|
||||
**State**
|
||||
- *Request* `<query xmlns="com:ctl"><ctl td="GetChargeState" />`
|
||||
- *Response* `<ctl td="ChargeState"><charge type="SlotCharging" /></ctl>`
|
||||
- `Idle` not trying to charge
|
||||
- `Going` trying to return to charger
|
||||
- `SlotCharging` currently charging in dock
|
||||
- `WireCharging` currently charging by cable
|
||||
|
||||
|
||||
### Battery State
|
||||
|
||||
Battery charge level. 080 = 80% charged. State is broadcast
|
||||
continously when the robot is running or charging, but can also
|
||||
be requested manually.
|
||||
|
||||
- *Request* `<ctl td="GetBatteryInfo" />`
|
||||
- *Response* `<ctl td="BatteryInfo"><battery power="080" /></ctl>`
|
||||
|
||||
|
||||
### Component lifespan
|
||||
|
||||
The remaining lifespan of components. Based on an internal counters
|
||||
that can be reset with command ResetLifeSpan (untested).
|
||||
|
||||
It's presumed that the timers need to be reset manually.
|
||||
|
||||
- *Request* `<ctl td="GetLifeSpan" type="Brush" />`
|
||||
- *Response* `<ctl td="LifeSpan" type="Brush" val="095" total="365" />`
|
||||
- Brush
|
||||
- SideBrush
|
||||
- DustCaseHeap
|
||||
|
||||
|
||||
### Manually moving around
|
||||
|
||||
|**Command**|**Control**|
|
||||
|-|-|
|
||||
|Move forward|`<ctl td="Move"><move action="forward"/></ctl>`|
|
||||
|Move backward|`<ctl td="Move"><move action="backward"/></ctl>`|
|
||||
|Spin left 360 degrees|`<ctl td="Move"><move action="SpinLeft"/></ctl>`|
|
||||
|Spin right 360 degrees|`<ctl td="Move"><move action="SpinRight"/></ctl>`|
|
||||
|Turn 180 degrees|`<ctl td="Move"><move action="TurnAround"/></ctl>`|
|
||||
|Stop the ongoing action|`<ctl td="Move"><move action="stop"/></ctl>`|
|
||||
|
||||
|
||||
### Configuration
|
||||
|
||||
#### Set/get robot internal clock
|
||||
- `<ctl td="SetTime"><time t="1509622697" tz="+8"/></ctl>`
|
||||
- `<ctl td="GetTime"></ctl>`
|
||||
- Time is specified as a UNIX timestamp and timezone + or - UTC offset.
|
||||
|
||||
#### Get firmware version
|
||||
`<ctl td="GetVersion" name="FW"/>`
|
||||
|
||||
#### Get robot logs
|
||||
`<ctl td="GetLog"></ctl>`
|
||||
|
||||
#### Get/Set option value
|
||||
Gets or sets value for option (0==Off, 1==On)
|
||||
##### GetOnOff
|
||||
- Do Not Disturb - `<ctl td="GetOnOff" t="b"/>`
|
||||
- Continuous Cleaning - `<ctl td="GetOnOff" t="g"/>`
|
||||
- Silence Voice Report - `<ctl td="GetOnOff" t="s"/>`
|
||||
|
||||
Returns `<ctl ret='ok' on='1'/>`
|
||||
##### SetOnOff
|
||||
- Do Not Disturb - `<ctl td="SetOnOff" t="b" on="0"/>`
|
||||
- Continuous Cleaning - `<ctl td="SetOnOff" t="g" on="0"/>`
|
||||
- Silence Voice Report - `<ctl td="SetOnOff" t="s" on="0"/>`
|
||||
|
||||
Returns `<ctl ret='ok'/>`
|
||||
|
||||
#### Mopping Water Amount
|
||||
Models with mopping capability (Ozmo) allow for changing the amount of water dispersed. The value ranges from 1 (low) to 3 (high).
|
||||
|
||||
`<ctl td="SetWaterPermeability" v="1"/>`
|
||||
|
||||
|
||||
#### Schedules
|
||||
##### GetSched
|
||||
`<ctl td="GetSched"/>`
|
||||
|
||||
Gets any schedules for the robot.
|
||||
|
||||
- No Schedules
|
||||
- `<ctl ret='ok'/>`
|
||||
- Schedule
|
||||
- `<ctl ret='ok'><s n='FRASITLP' o='0' h='13' m='2' r='0000000' f='p'><ctl td='Clean'><clean type='auto'/></ctl></s></ctl>`
|
||||
|
||||
### Errors
|
||||
|
||||
The bot broadcasts error codes for a number of cases.
|
||||
|
||||
`<ctl td="error" error="BatteryLow" errno="101"></ctl>`
|
||||
|
||||
The latest error can be requested like so:
|
||||
|
||||
- **Request** `<ctl td="GetError" />`
|
||||
- **Response** `<ctl ret="ok" errs="100"/>`
|
||||
|
||||
However in some cases the robot sends to code 100 shortly
|
||||
after an error has occurred, meaning that we cannot trust
|
||||
the GetError request to contain the last relevant error.
|
||||
For example, if the robot gets stuck it broadcasts 102
|
||||
HostHang, then proceeds to stop and broadcasts 100 NoError.
|
||||
|
||||
|
||||
**Known error codes**
|
||||
|
||||
|Code|Description|
|
||||
|-|-|
|
||||
|100|NoError: Robot is operational|
|
||||
|101|BatteryLow: Low battery|
|
||||
|102|HostHang: Robot is off the floor|
|
||||
|103|WheelAbnormal: Driving Wheel malfunction|
|
||||
|104|DownSensorAbnormal: Excess dust on the Anti-Drop Sensors|
|
||||
|105|Stuck: Robot is stuck|
|
||||
|106|SideBrushExhausted: Side Brushes have expired|
|
||||
|107|DustCaseHeapExhausted: Dust case filter expired|
|
||||
|108|SideAbnormal: Side Brushes are tangled|
|
||||
|109|RollAbnormal: Main Brush is tangled|
|
||||
|110|NoDustBox: Dust Bin Not installed|
|
||||
|111|BumpAbnormal: Bump sensor stuck|
|
||||
|112|LDS: LDS "Laser Distance Sensor" malfunction|
|
||||
|113|MainBrushExhausted: Main brush has expired|
|
||||
|114|DustCaseFilled: Dust bin full|
|
||||
|115|BatteryError: |
|
||||
|116|ForwardLookingError: |
|
||||
|117|GyroscopeError: |
|
||||
|118|StrainerBlock: |
|
||||
|119|FanError: |
|
||||
|120|WaterBoxError: |
|
||||
|201|AirFilterUninstall: |
|
||||
|202|UltrasonicComponentAbnormal|
|
||||
|203|SmallWheelError|
|
||||
|UNKNOW|"unknow"|
|
||||
|
||||
These codes were gathered from the Android app source, but may differ
|
||||
between models.
|
||||
|
||||
### Sounds
|
||||
Different sid "Sound IDs" will play different sounds. If the vacuum has Voice Report disabled, these won't play. The table below was compiled by testing against a D900 series.
|
||||
|
||||
`<ctl td="PlaySound" sid="0" />`
|
||||
|
||||
| SID | Description |
|
||||
|-|-|
|
||||
| 0 | Startup Music Chime |
|
||||
| 3 | I Am Suspended |
|
||||
| 4 | Check Driving Wheels |
|
||||
| 5 | Please Help Me Out |
|
||||
| 6 | Please Install Dust Bin |
|
||||
| 17 | Chime / Beep |
|
||||
| 18 | My Battery Is Low |
|
||||
| 29 | Please power me on before charging |
|
||||
| 30 | I Am Here |
|
||||
| 31 | Brush is tangled please clean my brush |
|
||||
| 35 | Please clean my antidrop sensors |
|
||||
| 48 | Brush is tangled |
|
||||
| 55 | I am relocating |
|
||||
| 56 | Upgrade succeeded |
|
||||
| 63 | I am returning to the charging dock |
|
||||
| 65 | Cleaning paused |
|
||||
| 69 | Connected please go back to ecovacs app to continue setup |
|
||||
| 71 | I am restoring the map please do not stand beside me |
|
||||
| 73 | My battery is low returning to the charging dock |
|
||||
| 74 | Difficult to locate I am starting a new cleaning cycle |
|
||||
| 75 | I am resuming the clean |
|
||||
| 76 | Upgrade failed please try again |
|
||||
| 77 | Please place me on the charging dock |
|
||||
| 79 | Resume the clean |
|
||||
| 80 | I am starting the clean |
|
||||
| 81 | I am starting the clean |
|
||||
| 82 | I am starting the clean |
|
||||
| 84 | I am ready for mopping |
|
||||
| 85 | Please remove the mopping plate when I am building the map |
|
||||
| 86 | Cleaning is complete returning to the charging dock |
|
||||
| 89 | LDS Malfunction please try to tap the LDS |
|
||||
| 90 | I am upgrading please wait |
|
||||
|
||||
### SpotAreas
|
||||
For bots with mapping capability this tells a bot to clean specified rooms.
|
||||
|
||||
For the CLI - the `area` command takes a csv of ints - ex `area 0,1`
|
||||
|
||||
You can add the option `--map-position` or `-p` to clean a specified map coordinate - ex `area -p "-602,1812,800,723"`
|
||||
|
||||
For the Library - you could use `vacbot.run(SpotArea('start', '0,1'))`
|
||||
|
||||
"0,1" is a list of mapIDs the bot should clean. Each of these corresponds to a room or area the bot mapped. In the app, these are what show the letters over rooms mapID (0) == room ("A"), (1) == "B", etc.
|
||||
|
||||
If you want to see your MapSet areas, you can use the library. Set --debug for sucks and then use a custom command:
|
||||
`vacbot.run(VacBotCommand("GetMapSet", {"tp":"sa"}))`
|
||||
|
||||
You'll see in DEBUG something like:
|
||||
```
|
||||
sucks DEBUG got {'id': 'ralnsy', 'ret': 'ok', 'resp': "<ctl ret='ok' tp='sa' msid='11'><m mid='0' p='1'/><m mid='1' p='1'/><m mid='2' p='1'/><m mid='3' p='1'/><m mid='4' p='1'/><m mid='5' p='1'/><m mid='6' p='1'/><m mid='7' p='1'/><m mid='8' p='1'/></ctl>"}
|
||||
```
|
||||
This tells you I have 9 rooms mapped (mid= 0 - 8) or A-I, but you should be able to compare to the map in the app now to know which mid == what room.
|
||||
|
||||
#### SpotArea Friendly Names
|
||||
For bots with mapping capability the app automatically names areas (rooms) A-Z. You can rename these to "friendly names" - something the app won't let you do natively.
|
||||
|
||||
Use the above "GetMapSet" custom command and then convert the xml to json:
|
||||
``` xml
|
||||
<ctl ret='ok' tp='sa' msid='11'><m mid='0' p='1'/><m mid='1' p='1'/><m mid='2' p='1'/><m mid='3' p='1'/><m mid='4' p='1'/><m mid='5' p='1'/><m mid='6' p='1'/><m mid='7' p='1'/><m mid='8' p='1'/></ctl>
|
||||
```
|
||||
becomes
|
||||
``` javascript
|
||||
{"ctl":{"ret":"ok","tp":"sa","msid":"11","m":[{"mid":"0","p":"1"},{"mid":"1","p":"1"},{"mid":"2","p":"1"},{"mid":"3","p":"1"},{"mid":"4","p":"1"},{"mid":"5","p":"1"},{"mid":"6","p":"1"},{"mid":"7","p":"1"},{"mid":"8","p":"1"}]}}
|
||||
```
|
||||
Now you need to add a "n" attribute which contains the friendly name:
|
||||
``` javascript
|
||||
{"ctl":{"ret":"ok","tp":"sa","msid":"11","m":[{"mid":"0","n":"Entry"},{"mid":"1","n":"Master Bath"},{"mid":"2","n":"Master"},{"mid":"3","n":"Office"},{"mid":"4","n":"Play Room"},{"mid":"5","n":"Craft Room"},{"mid":"6","n":"Kitchen"},{"mid":"7","n":"Sun Room"},{"mid":"8","n":"Garage Entry"}]}}
|
||||
```
|
||||
Remove the api response details ("ctl" and "ret"):
|
||||
``` javascript
|
||||
{"tp":"sa","msid":"11","m":[{"mid":"0","n":"Entry"},{"mid":"1","n":"Master Bath"},{"mid":"2","n":"Master"},{"mid":"3","n":"Office"},{"mid":"4","n":"Play Room"},{"mid":"5","n":"Craft Room"},{"mid":"6","n":"Kitchen"},{"mid":"7","n":"Sun Room"},{"mid":"8","n":"Garage Entry"}]}
|
||||
```
|
||||
Lastly use the below command to issue the rename:
|
||||
```
|
||||
vacbot.run(VacBotCommand("RenameM", {"tp":"sa","msid":"11","m":[{"mid":"0","n":"Entry"},{"mid":"1","n":"Master Bath"},{"mid":"2","n":"Master"},{"mid":"3","n":"Office"},{"mid":"4","n":"Play Room"},{"mid":"5","n":"Craft Room"},{"mid":"6","n":"Kitchen"},{"mid":"7","n":"Sun Room"},{"mid":"8","n":"Garage Entry"}]}))
|
||||
```
|
||||
You should then see the friendly names in the app when selecting an area to clean.
|
||||
|
||||
**Note:** You cannot use the friendly names when starting a clean, you must use the mid.
|
||||
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
from codecs import open
|
||||
from os import path
|
||||
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
here = path.abspath(path.dirname(__file__))
|
||||
|
||||
# Get the long description from the README file
|
||||
long_description = ''
|
||||
try:
|
||||
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
|
||||
long_description = f.read()
|
||||
except FileNotFoundError:
|
||||
print("can't find python README; skipping")
|
||||
|
||||
setup(
|
||||
name='sucks',
|
||||
version='0.9.3',
|
||||
|
||||
description='a library for controlling certain robot vacuums',
|
||||
long_description=long_description,
|
||||
|
||||
url='https://github.com/wpietri/sucks',
|
||||
|
||||
# Author details
|
||||
author='William Pietri',
|
||||
author_email='sucks-users@googlegroups.com',
|
||||
|
||||
# Choose your license
|
||||
license='GPL-3.0',
|
||||
|
||||
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
|
||||
classifiers=[
|
||||
# How mature is this project? Common values are
|
||||
# 3 - Alpha
|
||||
# 4 - Beta
|
||||
# 5 - Production/Stable
|
||||
'Development Status :: 4 - Beta',
|
||||
|
||||
# Indicate who your project is intended for
|
||||
'Intended Audience :: Developers',
|
||||
'Topic :: Software Development :: Libraries',
|
||||
'Topic :: Home Automation',
|
||||
|
||||
# Pick your license as you wish (should match "license" above)
|
||||
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
|
||||
|
||||
# Specify the Python versions you support here. In particular, ensure
|
||||
# that you indicate whether you support Python 2, Python 3 or both.
|
||||
'Programming Language :: Python :: 3.5',
|
||||
],
|
||||
|
||||
# What does your project relate to?
|
||||
keywords='home automation vacuum robot',
|
||||
|
||||
# You can just specify the packages manually here if your project is
|
||||
# simple. Or you can use find_packages().
|
||||
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
|
||||
|
||||
# List run-time dependencies here. These will be installed by pip when
|
||||
# your project is installed. For an analysis of "install_requires" vs pip's
|
||||
# requirements files see:
|
||||
# https://packaging.python.org/en/latest/requirements.html
|
||||
|
||||
install_requires=[
|
||||
'sleekxmppfs>=1.3.4',
|
||||
'click>=6',
|
||||
'requests>=2.18',
|
||||
'pycryptodome>=3.4',
|
||||
'pycountry-convert>=0.5',
|
||||
'paho-mqtt>=1.4',
|
||||
'stringcase>=1.2'
|
||||
],
|
||||
|
||||
# List additional groups of dependencies here (e.g. development
|
||||
# dependencies). You can install these using the following syntax,
|
||||
# for example:
|
||||
# $ pip install -e .[dev,test]
|
||||
extras_require={
|
||||
'dev': [
|
||||
'nose',
|
||||
'requests-mock>=1.3'
|
||||
],
|
||||
},
|
||||
|
||||
# If there are data files included in your packages that need to be
|
||||
# installed, specify them here. If using Python 2.6 or less, then these
|
||||
# have to be included in MANIFEST.in as well.
|
||||
# package_data={
|
||||
# 'sample': ['package_data.dat'],
|
||||
# },
|
||||
|
||||
# To provide executable scripts, use entry points in preference to the
|
||||
# "scripts" keyword. Entry points provide cross-platform support and allow
|
||||
# pip to create the appropriate form of executable for the target platform.
|
||||
entry_points={
|
||||
'console_scripts': [
|
||||
'sucks=sucks.cli:cli',
|
||||
],
|
||||
},
|
||||
)
|
||||
@@ -1,11 +0,0 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# A command-line script for running the cli if
|
||||
# you haven't installed it using pip. Mainly
|
||||
# useful for developers, I think.
|
||||
|
||||
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
|
||||
cd ${DIR}
|
||||
pipenv run -- python -m sucks.cli "$@"
|
||||
@@ -1,596 +0,0 @@
|
||||
import hashlib
|
||||
import time
|
||||
import requests
|
||||
import os
|
||||
from base64 import b64decode, b64encode
|
||||
from collections import OrderedDict
|
||||
from sleekxmppfs.xmlstream import ET
|
||||
from sleekxmppfs.exceptions import XMPPError
|
||||
|
||||
from .mqtt_ecovacs import EcoVacsIOTMQ
|
||||
from .xmpp_ecovacs import EcoVacsXMPP
|
||||
|
||||
from .const import LOGGER
|
||||
from .sucks_const import *
|
||||
|
||||
def str_to_bool_or_cert(s):
|
||||
if s == 'True' or s == True:
|
||||
return True
|
||||
elif s == 'False' or s == False:
|
||||
return False
|
||||
else:
|
||||
if not s == None:
|
||||
if os.path.exists(s): # User could provide a path to a CA Cert as well, which is useful for Bumper
|
||||
if os.path.isfile(s):
|
||||
return s
|
||||
else:
|
||||
raise ValueError("Certificate path provided is not a file - {}".format(s))
|
||||
raise ValueError("Cannot covert {} to a bool or certificate path".format(s))
|
||||
|
||||
class EcoVacsAPI:
|
||||
CLIENT_KEY = "eJUWrzRv34qFSaYk"
|
||||
SECRET = "Cyu5jcR4zyK6QEPn1hdIGXB5QIDAQABMA0GC"
|
||||
PUBLIC_KEY = 'MIIB/TCCAWYCCQDJ7TMYJFzqYDANBgkqhkiG9w0BAQUFADBCMQswCQYDVQQGEwJjbjEVMBMGA1UEBwwMRGVmYXVsdCBDaXR5MRwwGgYDVQQKDBNEZWZhdWx0IENvbXBhbnkgTHRkMCAXDTE3MDUwOTA1MTkxMFoYDzIxMTcwNDE1MDUxOTEwWjBCMQswCQYDVQQGEwJjbjEVMBMGA1UEBwwMRGVmYXVsdCBDaXR5MRwwGgYDVQQKDBNEZWZhdWx0IENvbXBhbnkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDb8V0OYUGP3Fs63E1gJzJh+7iqeymjFUKJUqSD60nhWReZ+Fg3tZvKKqgNcgl7EGXp1yNifJKUNC/SedFG1IJRh5hBeDMGq0m0RQYDpf9l0umqYURpJ5fmfvH/gjfHe3Eg/NTLm7QEa0a0Il2t3Cyu5jcR4zyK6QEPn1hdIGXB5QIDAQABMA0GCSqGSIb3DQEBBQUAA4GBANhIMT0+IyJa9SU8AEyaWZZmT2KEYrjakuadOvlkn3vFdhpvNpnnXiL+cyWy2oU1Q9MAdCTiOPfXmAQt8zIvP2JC8j6yRTcxJCvBwORDyv/uBtXFxBPEC6MDfzU2gKAaHeeJUWrzRv34qFSaYkYta8canK+PSInylQTjJK9VqmjQ'
|
||||
MAIN_URL_FORMAT = 'https://eco-{country}-api.ecovacs.com/v1/private/{country}/{lang}/{deviceId}/{appCode}/{appVersion}/{channel}/{deviceType}'
|
||||
USER_URL_FORMAT = 'https://users-{continent}.ecouser.net:8000/user.do'
|
||||
PORTAL_URL_FORMAT = 'https://portal-{continent}.ecouser.net/api'
|
||||
USERSAPI = 'users/user.do'
|
||||
IOTDEVMANAGERAPI = 'iot/devmanager.do' # IOT Device Manager - This provides control of "IOT" products via RestAPI, some bots use this instead of XMPP
|
||||
PRODUCTAPI = 'pim/product' # Leaving this open, the only endpoint known currently is "Product IOT Map" - pim/product/getProductIotMap - This provides a list of "IOT" products. Not sure what this provides the app.
|
||||
REALM = 'ecouser.net'
|
||||
|
||||
def __init__(self, device_id, account_id, password_hash, country, continent, verify_ssl=True):
|
||||
self.meta = {
|
||||
'country': country,
|
||||
'lang': 'en',
|
||||
'deviceId': device_id,
|
||||
'appCode': 'i_eco_e',
|
||||
#'appCode': 'i_eco_a' - iphone
|
||||
'appVersion': '1.3.5',
|
||||
#'appVersion': '1.4.6' - iphone
|
||||
'channel': 'c_googleplay',
|
||||
#'channel': 'c_iphone', - iphone
|
||||
'deviceType': '1'
|
||||
#'deviceType': '2' - iphone
|
||||
}
|
||||
self.verify_ssl = str_to_bool_or_cert(verify_ssl)
|
||||
LOGGER.debug("Setting up EcoVacsAPI")
|
||||
self.resource = device_id[0:8]
|
||||
self.country = country
|
||||
self.continent = continent
|
||||
login_info = self.__call_main_api('user/login',
|
||||
('account', self.encrypt(account_id)),
|
||||
('password', self.encrypt(password_hash)))
|
||||
self.uid = login_info['uid']
|
||||
self.login_access_token = login_info['accessToken']
|
||||
self.auth_code = self.__call_main_api('user/getAuthCode',
|
||||
('uid', self.uid),
|
||||
('accessToken', self.login_access_token))['authCode']
|
||||
login_response = self.__call_login_by_it_token()
|
||||
self.user_access_token = login_response['token']
|
||||
if login_response['userId'] != self.uid:
|
||||
LOGGER.debug("Switching to shorter UID " + login_response['userId'])
|
||||
self.uid = login_response['userId']
|
||||
LOGGER.debug("EcoVacsAPI connection complete")
|
||||
|
||||
def __sign(self, params):
|
||||
result = params.copy()
|
||||
result['authTimespan'] = int(time.time() * 1000)
|
||||
result['authTimeZone'] = 'GMT-8'
|
||||
sign_on = self.meta.copy()
|
||||
sign_on.update(result)
|
||||
sign_on_text = EcoVacsAPI.CLIENT_KEY + ''.join(
|
||||
[k + '=' + str(sign_on[k]) for k in sorted(sign_on.keys())]) + EcoVacsAPI.SECRET
|
||||
result['authAppkey'] = EcoVacsAPI.CLIENT_KEY
|
||||
result['authSign'] = self.md5(sign_on_text)
|
||||
return result
|
||||
|
||||
def __call_main_api(self, function, *args):
|
||||
LOGGER.debug("calling main api {} with {}".format(function, args))
|
||||
params = OrderedDict(args)
|
||||
params['requestId'] = self.md5(time.time())
|
||||
url = (EcoVacsAPI.MAIN_URL_FORMAT + "/" + function).format(**self.meta)
|
||||
api_response = requests.get(url, self.__sign(params), verify=self.verify_ssl)
|
||||
json = api_response.json()
|
||||
LOGGER.debug("got {}".format(json))
|
||||
if json['code'] == '0000':
|
||||
return json['data']
|
||||
elif json['code'] == '1005':
|
||||
LOGGER.error("incorrect email or password")
|
||||
raise ValueError("incorrect email or password")
|
||||
else:
|
||||
LOGGER.error("call to {} failed with {}".format(function, json))
|
||||
raise RuntimeError("failure code {} ({}) for call {} and parameters {}".format(
|
||||
json['code'], json['msg'], function, args))
|
||||
|
||||
def __call_user_api(self, function, args):
|
||||
LOGGER.debug("calling user api {} with {}".format(function, args))
|
||||
params = {'todo': function}
|
||||
params.update(args)
|
||||
response = requests.post(EcoVacsAPI.USER_URL_FORMAT.format(continent=self.continent), json=params, verify=self.verify_ssl)
|
||||
json = response.json()
|
||||
LOGGER.debug("got {}".format(json))
|
||||
if json['result'] == 'ok':
|
||||
return json
|
||||
else:
|
||||
LOGGER.error("call to {} failed with {}".format(function, json))
|
||||
raise RuntimeError(
|
||||
"failure {} ({}) for call {} and parameters {}".format(json['error'], json['errno'], function, params))
|
||||
|
||||
def __call_portal_api(self, api, function, args, verify_ssl=True, **kwargs):
|
||||
if api == self.USERSAPI:
|
||||
params = {'todo': function}
|
||||
params.update(args)
|
||||
else:
|
||||
params = {}
|
||||
params.update(args)
|
||||
LOGGER.debug("calling portal api {} function {} with {}".format(api, function, params))
|
||||
continent = self.continent
|
||||
if 'continent' in kwargs:
|
||||
continent = kwargs.get('continent')
|
||||
url = (EcoVacsAPI.PORTAL_URL_FORMAT + "/" + api).format(continent=continent, **self.meta)
|
||||
response = requests.post(url, json=params, verify=verify_ssl)
|
||||
json = response.json()
|
||||
LOGGER.debug("got {}".format(json))
|
||||
if api == self.USERSAPI:
|
||||
if json['result'] == 'ok':
|
||||
return json
|
||||
elif json['result'] == 'fail':
|
||||
if json['error'] == 'set token error.': # If it is a set token error try again
|
||||
if not 'set_token' in kwargs:
|
||||
LOGGER.debug("loginByItToken set token error, trying again (2/3)")
|
||||
return self.__call_portal_api(self.USERSAPI, function, args, verify_ssl=verify_ssl, set_token=1)
|
||||
elif kwargs.get('set_token') == 1:
|
||||
LOGGER.debug("loginByItToken set token error, trying again with ww (3/3)")
|
||||
return self.__call_portal_api(self.USERSAPI, function, args, verify_ssl=verify_ssl, set_token=2, continent="ww")
|
||||
else:
|
||||
LOGGER.debug("loginByItToken set token error, failed after 3 attempts")
|
||||
if api.startswith(self.PRODUCTAPI):
|
||||
if json['code'] == 0:
|
||||
return json
|
||||
|
||||
else:
|
||||
LOGGER.error("call to {} failed with {}".format(function, json))
|
||||
raise RuntimeError(
|
||||
"failure {} ({}) for call {} and parameters {}".format(json['error'], json['errno'], function, params))
|
||||
|
||||
def __call_login_by_it_token(self):
|
||||
return self.__call_portal_api(self.USERSAPI,'loginByItToken',
|
||||
{'country': self.meta['country'].upper(),
|
||||
'resource': self.resource,
|
||||
'realm': EcoVacsAPI.REALM,
|
||||
'userId': self.uid,
|
||||
'token': self.auth_code}
|
||||
, verify_ssl=self.verify_ssl)
|
||||
|
||||
def getdevices(self):
|
||||
return self.__call_portal_api(self.USERSAPI,'GetDeviceList', {
|
||||
'userid': self.uid,
|
||||
'auth': {
|
||||
'with': 'users',
|
||||
'userid': self.uid,
|
||||
'realm': EcoVacsAPI.REALM,
|
||||
'token': self.user_access_token,
|
||||
'resource': self.resource
|
||||
}
|
||||
}, verify_ssl=self.verify_ssl)['devices']
|
||||
|
||||
def getiotProducts(self):
|
||||
return self.__call_portal_api(self.PRODUCTAPI + '/getProductIotMap','', {
|
||||
'channel': '',
|
||||
'auth': {
|
||||
'with': 'users',
|
||||
'userid': self.uid,
|
||||
'realm': EcoVacsAPI.REALM,
|
||||
'token': self.user_access_token,
|
||||
'resource': self.resource
|
||||
}
|
||||
}, verify_ssl=self.verify_ssl)['data']
|
||||
|
||||
def SetIOTDevices(self, devices, iotproducts):
|
||||
#Originally added for D900, and not actively used in code now - Not sure what the app checks the items in this list for
|
||||
for device in devices: #Check if the device is part of iotProducts
|
||||
device['iot_product'] = False
|
||||
for iotProduct in iotproducts:
|
||||
if device['class'] in iotProduct['classid']:
|
||||
device['iot_product'] = True
|
||||
|
||||
return devices
|
||||
|
||||
def SetIOTMQDevices(self, devices):
|
||||
#Added for devices that utilize MQTT instead of XMPP for communication
|
||||
for device in devices:
|
||||
device['iotmq'] = False
|
||||
if device['company'] == 'eco-ng': #Check if the device is part of the list
|
||||
device['iotmq'] = True
|
||||
|
||||
return devices
|
||||
|
||||
def devices(self):
|
||||
return self.SetIOTMQDevices(self.getdevices())
|
||||
|
||||
@staticmethod
|
||||
def md5(text):
|
||||
return hashlib.md5(bytes(str(text), 'utf8')).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def encrypt(text):
|
||||
from Crypto.PublicKey import RSA
|
||||
from Crypto.Cipher import PKCS1_v1_5
|
||||
key = RSA.import_key(b64decode(EcoVacsAPI.PUBLIC_KEY))
|
||||
cipher = PKCS1_v1_5.new(key)
|
||||
result = cipher.encrypt(bytes(text, 'utf8'))
|
||||
return str(b64encode(result), 'utf8')
|
||||
|
||||
class EventEmitter(object):
|
||||
"""A very simple event emitting system."""
|
||||
def __init__(self):
|
||||
self._subscribers = []
|
||||
|
||||
def subscribe(self, callback):
|
||||
listener = EventListener(self, callback)
|
||||
self._subscribers.append(listener)
|
||||
return listener
|
||||
|
||||
def unsubscribe(self, listener):
|
||||
self._subscribers.remove(listener)
|
||||
|
||||
def notify(self, event):
|
||||
for subscriber in self._subscribers:
|
||||
subscriber.callback(event)
|
||||
|
||||
class EventListener(object):
|
||||
"""Object that allows event consumers to easily unsubscribe from events."""
|
||||
def __init__(self, emitter, callback):
|
||||
self._emitter = emitter
|
||||
self.callback = callback
|
||||
|
||||
def unsubscribe(self):
|
||||
self._emitter.unsubscribe(self)
|
||||
|
||||
class VacBot():
|
||||
# switched verify and monitor just to be consistent
|
||||
def __init__(self, user, domain, resource, secret, vacuum, continent, server_address=None, verify_ssl=True, monitor=False):
|
||||
self.vacuum = vacuum
|
||||
self.server_address = server_address
|
||||
# If True, the VacBot object will handle keeping track of all statuses,
|
||||
# including the initial request for statuses, and new requests after the
|
||||
# VacBot returns from being offline. It will also cause it to regularly
|
||||
# request component lifespans
|
||||
self._monitor = monitor
|
||||
self._failed_pings = 0
|
||||
# These three are representations of the vacuum state as reported by the API
|
||||
self.clean_status = None
|
||||
self.charge_status = None
|
||||
self.battery_status = None
|
||||
# This is an aggregate state managed by the sucks library, combining the clean and charge events to a single state
|
||||
self.vacuum_status = None
|
||||
self.fan_speed = None
|
||||
# Populated by component Lifespan reports
|
||||
self.components = {}
|
||||
self.statusEvents = EventEmitter()
|
||||
self.batteryEvents = EventEmitter()
|
||||
self.lifespanEvents = EventEmitter()
|
||||
self.errorEvents = EventEmitter()
|
||||
#Set none for clients to start
|
||||
self.xmpp = None
|
||||
self.iotmq = None
|
||||
if not vacuum['iotmq']:
|
||||
self.xmpp = EcoVacsXMPP(user, domain, resource, secret, continent, vacuum, server_address)
|
||||
#Uncomment line to allow unencrypted plain auth
|
||||
#self.xmpp['feature_mechanisms'].unencrypted_plain = True
|
||||
self.xmpp.subscribe_to_ctls(self._handle_ctl)
|
||||
else:
|
||||
self.iotmq = EcoVacsIOTMQ(user, domain, resource, secret, continent, vacuum, server_address, verify_ssl=verify_ssl)
|
||||
self.iotmq.subscribe_to_ctls(self._handle_ctl)
|
||||
#The app still connects to XMPP as well, but only issues ping commands.
|
||||
#Everything works without XMPP, so leaving the below commented out.
|
||||
#self.xmpp = EcoVacsXMPP(user, domain, resource, secret, continent, vacuum, server_address)
|
||||
#Uncomment line to allow unencrypted plain auth
|
||||
#self.xmpp['feature_mechanisms'].unencrypted_plain = True
|
||||
#self.xmpp.subscribe_to_ctls(self._handle_ctl)
|
||||
|
||||
def connect_and_wait_until_ready(self):
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.connect_and_wait_until_ready()
|
||||
self.xmpp.schedule('Ping', 300, lambda: self.send_ping(), repeat=True)
|
||||
else:
|
||||
self.iotmq.connect_and_wait_until_ready()
|
||||
self.iotmq.schedule(30, self.send_ping)
|
||||
#self.xmpp.connect_and_wait_until_ready() #Leaving in case xmpp is given to iotmq in the future
|
||||
if self._monitor:
|
||||
# Do a first ping, which will also fetch initial statuses if the ping succeeds
|
||||
self.send_ping()
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.schedule('Components', 3600, lambda: self.refresh_components(), repeat=True)
|
||||
else:
|
||||
self.iotmq.schedule(3600,self.refresh_components)
|
||||
|
||||
def _handle_ctl(self, ctl):
|
||||
method = '_handle_' + ctl['event']
|
||||
if hasattr(self, method):
|
||||
getattr(self, method)(ctl)
|
||||
|
||||
def _handle_error(self, event):
|
||||
if 'error' in event:
|
||||
error = event['error']
|
||||
elif 'errs' in event:
|
||||
error = event['errs']
|
||||
if not error == '':
|
||||
self.errorEvents.notify(error)
|
||||
LOGGER.error("*** error = " + error)
|
||||
|
||||
def _handle_life_span(self, event):
|
||||
type = event['type']
|
||||
try:
|
||||
type = COMPONENT_FROM_ECOVACS[type]
|
||||
except KeyError:
|
||||
LOGGER.warning("Unknown component type: '" + type + "'")
|
||||
if 'val' in event:
|
||||
lifespan = int(event['val']) / 100
|
||||
LOGGER.info("**********Component " + type + " has lifespan of " + str(lifespan) + ".")
|
||||
else:
|
||||
lifespan = int(event['left']) / 60 #This works for a D901
|
||||
self.components[type] = lifespan
|
||||
lifespan_event = {'type': type, 'lifespan': lifespan}
|
||||
self.lifespanEvents.notify(lifespan_event)
|
||||
LOGGER.info("*** life_span " + type + " = " + str(lifespan))
|
||||
|
||||
def _handle_clean_report(self, event):
|
||||
type = event['type']
|
||||
try:
|
||||
type = CLEAN_MODE_FROM_ECOVACS[type]
|
||||
if self.vacuum['iotmq']: #Was able to parse additional status from the IOTMQ, may apply to XMPP too
|
||||
statustype = event['st']
|
||||
statustype = CLEAN_ACTION_FROM_ECOVACS[statustype]
|
||||
if statustype == CLEAN_ACTION_STOP or statustype == CLEAN_ACTION_PAUSE:
|
||||
type = statustype
|
||||
except KeyError:
|
||||
LOGGER.warning("Unknown cleaning status '" + type + "'")
|
||||
self.clean_status = type
|
||||
self.vacuum_status = type
|
||||
fan = event.get('speed', None)
|
||||
if fan is not None:
|
||||
try:
|
||||
fan = FAN_SPEED_FROM_ECOVACS[fan]
|
||||
except KeyError:
|
||||
LOGGER.warning("Unknown fan speed: '" + fan + "'")
|
||||
self.fan_speed = fan
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
if self.fan_speed:
|
||||
LOGGER.info("*** clean_status = " + self.clean_status + " fan_speed = " + self.fan_speed)
|
||||
else:
|
||||
LOGGER.info("*** clean_status = " + self.clean_status + " fan_speed = None")
|
||||
|
||||
def _handle_battery_info(self, iq):
|
||||
try:
|
||||
self.battery_status = float(iq['power']) / 100
|
||||
except ValueError:
|
||||
LOGGER.warning("couldn't parse battery status " + ET.tostring(iq))
|
||||
else:
|
||||
self.batteryEvents.notify(self.battery_status)
|
||||
LOGGER.info("*** battery_status = {:.0%}".format(self.battery_status))
|
||||
|
||||
def _handle_charge_state(self, event):
|
||||
if 'type' in event:
|
||||
status = event['type']
|
||||
elif 'errno' in event: #Handle error
|
||||
if event['ret'] == 'fail' and event['errno'] == '8': #Already charging
|
||||
status = 'slot_charging'
|
||||
elif event['ret'] == 'fail' and event['errno'] == '5': #Busy with another command
|
||||
status = 'idle'
|
||||
elif event['ret'] == 'fail' and event['errno'] == '3': #Bot in stuck state, example dust bin out
|
||||
status = 'idle'
|
||||
else:
|
||||
status = 'idle' #Fall back to Idle status
|
||||
LOGGER.error("Unknown charging status '" + event['errno'] + "'") #Log this so we can identify more errors
|
||||
try:
|
||||
status = CHARGE_MODE_FROM_ECOVACS[status]
|
||||
except KeyError:
|
||||
LOGGER.warning("Unknown charging status '" + status + "'")
|
||||
self.charge_status = status
|
||||
if status != 'idle' or self.vacuum_status == 'charging':
|
||||
# We have to ignore the idle messages, because all it means is that it's not
|
||||
# currently charging, in which case the clean_status is a better indicator
|
||||
# of what the vacuum is currently up to.
|
||||
self.vacuum_status = status
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
LOGGER.info("*** charge_status = " + self.charge_status)
|
||||
|
||||
def _vacuum_address(self):
|
||||
if not self.vacuum['iotmq']:
|
||||
return self.vacuum['did'] + '@' + self.vacuum['class'] + '.ecorobot.net/atom'
|
||||
else:
|
||||
return self.vacuum['did'] #IOTMQ only uses the did
|
||||
|
||||
@property
|
||||
def is_charging(self) -> bool:
|
||||
return self.vacuum_status in CHARGING_STATES
|
||||
|
||||
@property
|
||||
def is_cleaning(self) -> bool:
|
||||
return self.vacuum_status in CLEANING_STATES
|
||||
|
||||
def send_ping(self):
|
||||
try:
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.send_ping(self._vacuum_address())
|
||||
elif self.vacuum['iotmq']:
|
||||
if not self.iotmq.send_ping():
|
||||
raise RuntimeError()
|
||||
except XMPPError as err:
|
||||
LOGGER.warning("Ping did not reach VacBot. Will retry.")
|
||||
LOGGER.error("*** Error type: " + err.etype)
|
||||
LOGGER.error("*** Error condition: " + err.condition)
|
||||
self._failed_pings += 1
|
||||
if self._failed_pings >= 4:
|
||||
self.vacuum_status = 'offline'
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
except RuntimeError as err:
|
||||
LOGGER.warning("Ping did not reach VacBot. Will retry.")
|
||||
self._failed_pings += 1
|
||||
if self._failed_pings >= 4:
|
||||
self.vacuum_status = 'offline'
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
else:
|
||||
self._failed_pings = 0
|
||||
if self._monitor:
|
||||
# If we don't yet have a vacuum status, request initial statuses again now that the ping succeeded
|
||||
if self.vacuum_status == 'offline' or self.vacuum_status is None:
|
||||
self.request_all_statuses()
|
||||
else:
|
||||
# If we're not auto-monitoring the status, then just reset the status to None, which indicates unknown
|
||||
if self.vacuum_status == 'offline':
|
||||
self.vacuum_status = None
|
||||
self.statusEvents.notify(self.vacuum_status)
|
||||
|
||||
def refresh_components(self):
|
||||
try:
|
||||
self.run(GetLifeSpan('main_brush'))
|
||||
self.run(GetLifeSpan('side_brush'))
|
||||
self.run(GetLifeSpan('filter'))
|
||||
except XMPPError as err:
|
||||
LOGGER.warning("Component refresh requests failed to reach VacBot. Will try again later.")
|
||||
LOGGER.error("*** Error type: " + err.etype)
|
||||
LOGGER.error("*** Error condition: " + err.condition)
|
||||
|
||||
def refresh_statuses(self):
|
||||
try:
|
||||
self.run(GetCleanState())
|
||||
self.run(GetChargeState())
|
||||
self.run(GetBatteryState())
|
||||
except XMPPError as err:
|
||||
LOGGER.warning("Initial status requests failed to reach VacBot. Will try again on next ping.")
|
||||
LOGGER.error("*** Error type: " + err.etype)
|
||||
LOGGER.error("*** Error condition: " + err.condition)
|
||||
|
||||
def request_all_statuses(self):
|
||||
self.refresh_statuses()
|
||||
self.refresh_components()
|
||||
|
||||
def send_command(self, action):
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.send_command(action.to_xml(), self._vacuum_address())
|
||||
else:
|
||||
#IOTMQ issues commands via RestAPI, and listens on MQTT for status updates
|
||||
self.iotmq.send_command(action, self._vacuum_address()) #IOTMQ devices need the full action for additional parsing
|
||||
|
||||
def run(self, action):
|
||||
self.send_command(action)
|
||||
|
||||
def disconnect(self, wait=False):
|
||||
if not self.vacuum['iotmq']:
|
||||
self.xmpp.disconnect(wait=wait)
|
||||
else:
|
||||
self.iotmq._disconnect()
|
||||
#self.xmpp.disconnect(wait=wait) #Leaving in case xmpp is added to iotmq in the future
|
||||
|
||||
class VacBotCommand:
|
||||
ACTION = {
|
||||
'forward': 'forward',
|
||||
'backward': 'backward',
|
||||
'left': 'SpinLeft',
|
||||
'right': 'SpinRight',
|
||||
'turn_around': 'TurnAround',
|
||||
'stop': 'stop'
|
||||
}
|
||||
|
||||
def __init__(self, name, args=None, **kwargs):
|
||||
if args is None:
|
||||
args = {}
|
||||
self.name = name
|
||||
self.args = args
|
||||
|
||||
def to_xml(self):
|
||||
ctl = ET.Element('ctl', {'td': self.name})
|
||||
for key, value in self.args.items():
|
||||
if type(value) is dict:
|
||||
inner = ET.Element(key, value)
|
||||
ctl.append(inner)
|
||||
elif type(value) is list:
|
||||
for item in value:
|
||||
ixml = self.listobject_to_xml(key, item)
|
||||
ctl.append(ixml)
|
||||
else:
|
||||
ctl.set(key, value)
|
||||
return ctl
|
||||
|
||||
def __str__(self, *args, **kwargs):
|
||||
return self.command_name() + " command"
|
||||
|
||||
def command_name(self):
|
||||
return self.__class__.__name__.lower()
|
||||
|
||||
def listobject_to_xml(self, tag, conv_object):
|
||||
rtnobject = ET.Element(tag)
|
||||
if type(conv_object) is dict:
|
||||
for key, value in conv_object.items():
|
||||
rtnobject.set(key, value)
|
||||
else:
|
||||
rtnobject.set(tag, conv_object)
|
||||
return rtnobject
|
||||
|
||||
class Clean(VacBotCommand):
|
||||
def __init__(self, mode='auto', speed='normal', iotmq=False, action='start',terminal=False, **kwargs):
|
||||
if kwargs == {}:
|
||||
#Looks like action is needed for some bots, shouldn't affect older models
|
||||
super().__init__('Clean', {'clean': {'type': CLEAN_MODE_TO_ECOVACS[mode], 'speed': FAN_SPEED_TO_ECOVACS[speed],'act': CLEAN_ACTION_TO_ECOVACS[action]}})
|
||||
else:
|
||||
initcmd = {'type': CLEAN_MODE_TO_ECOVACS[mode], 'speed': FAN_SPEED_TO_ECOVACS[speed]}
|
||||
for kkey, kvalue in kwargs.items():
|
||||
initcmd[kkey] = kvalue
|
||||
super().__init__('Clean', {'clean': initcmd})
|
||||
|
||||
class Edge(Clean):
|
||||
def __init__(self):
|
||||
super().__init__('edge', 'high')
|
||||
|
||||
class Spot(Clean):
|
||||
def __init__(self):
|
||||
super().__init__('spot', 'high')
|
||||
|
||||
class Stop(Clean):
|
||||
def __init__(self):
|
||||
super().__init__('stop', 'normal')
|
||||
|
||||
class SpotArea(Clean):
|
||||
def __init__(self, action='start', area='', map_position='', cleanings='1'):
|
||||
if area != '': #For cleaning specified area
|
||||
super().__init__('spot_area', 'normal', act=CLEAN_ACTION_TO_ECOVACS[action], mid=area)
|
||||
elif map_position != '': #For cleaning custom map area, and specify deep amount 1x/2x
|
||||
super().__init__('spot_area' ,'normal',act=CLEAN_ACTION_TO_ECOVACS[action], p=map_position, deep=cleanings)
|
||||
else:
|
||||
#no valid entries
|
||||
raise ValueError("must provide area or map_position for spotarea clean")
|
||||
|
||||
class Charge(VacBotCommand):
|
||||
def __init__(self):
|
||||
super().__init__('Charge', {'charge': {'type': CHARGE_MODE_TO_ECOVACS['return']}})
|
||||
|
||||
class Move(VacBotCommand):
|
||||
def __init__(self, action):
|
||||
super().__init__('Move', {'move': {'action': self.ACTION[action]}})
|
||||
|
||||
class PlaySound(VacBotCommand):
|
||||
def __init__(self, sid="0"):
|
||||
super().__init__('PlaySound', {'sid': sid})
|
||||
|
||||
class GetCleanState(VacBotCommand):
|
||||
def __init__(self):
|
||||
super().__init__('GetCleanState')
|
||||
|
||||
class GetChargeState(VacBotCommand):
|
||||
def __init__(self):
|
||||
super().__init__('GetChargeState')
|
||||
|
||||
class GetBatteryState(VacBotCommand):
|
||||
def __init__(self):
|
||||
super().__init__('GetBatteryInfo')
|
||||
|
||||
class GetLifeSpan(VacBotCommand):
|
||||
def __init__(self, component):
|
||||
super().__init__('GetLifeSpan', {'type': COMPONENT_TO_ECOVACS[component]})
|
||||
|
||||
class SetTime(VacBotCommand):
|
||||
def __init__(self, timestamp, timezone):
|
||||
super().__init__('SetTime', {'time': {'t': timestamp, 'tz': timezone}})
|
||||
@@ -1,244 +0,0 @@
|
||||
import configparser
|
||||
import itertools
|
||||
import os
|
||||
import platform
|
||||
import random
|
||||
import re
|
||||
|
||||
import click
|
||||
from pycountry_convert import country_alpha2_to_continent_code
|
||||
|
||||
from sucks import *
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class FrequencyParamType(click.ParamType):
|
||||
name = 'frequency'
|
||||
RATIONAL_PATTERN = re.compile(r'([.0-9]+)/([.0-9]+)')
|
||||
|
||||
def convert(self, value, param, ctx):
|
||||
result = None
|
||||
try:
|
||||
search = self.RATIONAL_PATTERN.search(value)
|
||||
if search:
|
||||
result = float(search.group(1)) / float(search.group(2))
|
||||
else:
|
||||
try:
|
||||
result = float(value)
|
||||
except ValueError:
|
||||
pass
|
||||
except (ValueError, ArithmeticError):
|
||||
pass
|
||||
|
||||
if result is None:
|
||||
self.fail('%s is not a valid frequency' % value, param, ctx)
|
||||
if 0 <= result <= 1:
|
||||
return result
|
||||
|
||||
self.fail('%s is not between 0 and 1' % value, param, ctx)
|
||||
|
||||
|
||||
FREQUENCY = FrequencyParamType()
|
||||
|
||||
|
||||
class BotWait():
|
||||
pass
|
||||
|
||||
def wait(self, bot):
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class TimeWait(BotWait):
|
||||
def __init__(self, seconds):
|
||||
super().__init__()
|
||||
self.seconds = seconds
|
||||
|
||||
def wait(self, bot):
|
||||
click.echo("waiting for " + str(self.seconds) + "s")
|
||||
time.sleep(self.seconds)
|
||||
|
||||
|
||||
class StatusWait(BotWait):
|
||||
def __init__(self, wait_on, wait_for):
|
||||
super().__init__()
|
||||
self.wait_on = wait_on
|
||||
self.wait_for = wait_for
|
||||
|
||||
def wait(self, bot):
|
||||
if not hasattr(bot, self.wait_on):
|
||||
raise ValueError("object " + bot + " does not have method " + self.wait_on)
|
||||
_LOGGER.debug("waiting on " + self.wait_on + " for value " + self.wait_for)
|
||||
|
||||
while getattr(bot, self.wait_on) != self.wait_for:
|
||||
time.sleep(0.5)
|
||||
_LOGGER.debug("wait complete; " + self.wait_on + " is now " + self.wait_for)
|
||||
|
||||
|
||||
class CliAction:
|
||||
def __init__(self, vac_command, terminal=False, wait=None):
|
||||
self.vac_command = vac_command
|
||||
self.terminal = terminal
|
||||
self.wait = wait
|
||||
|
||||
|
||||
def config_file():
|
||||
if platform.system() == 'Windows':
|
||||
return os.path.join(os.getenv('APPDATA'), 'sucks.conf')
|
||||
else:
|
||||
return os.path.expanduser('~/.config/sucks.conf')
|
||||
|
||||
|
||||
def config_file_exists():
|
||||
return os.path.isfile(config_file())
|
||||
|
||||
|
||||
def read_config():
|
||||
parser = configparser.ConfigParser()
|
||||
with open(config_file()) as fp:
|
||||
parser.read_file(itertools.chain(['[global]'], fp), source=config_file())
|
||||
return parser['global']
|
||||
|
||||
|
||||
def write_config(config):
|
||||
os.makedirs(os.path.dirname(config_file()), exist_ok=True)
|
||||
with open(config_file(), 'w') as fp:
|
||||
for key in config:
|
||||
fp.write(key + '=' + str(config[key]) + "\n")
|
||||
|
||||
|
||||
def current_country():
|
||||
# noinspection PyBroadException
|
||||
try:
|
||||
return requests.get('http://ipinfo.io/json').json()['country'].lower()
|
||||
except:
|
||||
return 'us'
|
||||
|
||||
|
||||
def continent_for_country(country_code):
|
||||
return country_alpha2_to_continent_code(country_code.upper()).lower()
|
||||
|
||||
|
||||
def should_run(frequency):
|
||||
if frequency is None:
|
||||
return True
|
||||
n = random.random()
|
||||
result = n <= frequency
|
||||
_LOGGER.debug("tossing coin: {:0.3f} <= {:0.3f}: {}".format(n, frequency, result))
|
||||
return result
|
||||
|
||||
|
||||
@click.group(chain=True)
|
||||
@click.option('--debug/--no-debug', default=False)
|
||||
def cli(debug):
|
||||
logging.basicConfig(format='%(name)-10s %(levelname)-8s %(message)s')
|
||||
_LOGGER.parent.setLevel(logging.DEBUG if debug else logging.ERROR)
|
||||
|
||||
|
||||
@cli.command(help='logs in with specified email; run this first')
|
||||
@click.option('--email', prompt='Ecovacs app email')
|
||||
@click.option('--password', prompt='Ecovacs app password', hide_input=True)
|
||||
@click.option('--country-code', prompt='your two-letter country code', default=lambda: current_country())
|
||||
@click.option('--continent-code', prompt='your two-letter continent code',
|
||||
default=lambda: continent_for_country(click.get_current_context().params['country_code']))
|
||||
@click.option('--verify-ssl', prompt='Verify SSL for API requests', default=True)
|
||||
def login(email, password, country_code, continent_code, verify_ssl):
|
||||
if config_file_exists() and not click.confirm('overwrite existing config?'):
|
||||
click.echo("Skipping login.")
|
||||
exit(0)
|
||||
config = OrderedDict()
|
||||
password_hash = EcoVacsAPI.md5(password)
|
||||
device_id = EcoVacsAPI.md5(str(time.time()))
|
||||
try:
|
||||
EcoVacsAPI(device_id, email, password_hash, country_code, continent_code, verify_ssl)
|
||||
except ValueError as e:
|
||||
click.echo(e.args[0])
|
||||
exit(1)
|
||||
config['email'] = email
|
||||
config['password_hash'] = password_hash
|
||||
config['device_id'] = device_id
|
||||
config['country'] = country_code.lower()
|
||||
config['continent'] = continent_code.lower()
|
||||
config['verify_ssl'] = verify_ssl
|
||||
write_config(config)
|
||||
click.echo("Config saved.")
|
||||
exit(0)
|
||||
|
||||
|
||||
@cli.command(help='auto-cleans for the specified number of minutes, if minutes is 0 auto clean until bot returns to charger by itself')
|
||||
@click.option('--frequency', '-f', type=FREQUENCY, help='frequency with which to run; e.g. 0.5 or 3/7')
|
||||
@click.argument('minutes', type=click.FLOAT)
|
||||
def clean(frequency, minutes):
|
||||
waiter = StatusWait('charge_status', 'charging')
|
||||
if minutes > 0:
|
||||
waiter = TimeWait(minutes * 60)
|
||||
|
||||
if should_run(frequency):
|
||||
return CliAction(Clean(), wait=waiter)
|
||||
|
||||
|
||||
@cli.command(help='cleans room edges for the specified number of minutes')
|
||||
@click.option('--frequency', '-f', type=FREQUENCY, help='frequency with which to run; e.g. 0.5 or 3/7')
|
||||
@click.argument('minutes', type=click.FLOAT)
|
||||
def edge(frequency, minutes):
|
||||
if should_run(frequency):
|
||||
return CliAction(Edge(), wait=TimeWait(minutes * 60))
|
||||
|
||||
|
||||
@cli.command(help='cleans provided area(s), ex: "0,1"',context_settings={"ignore_unknown_options": True}) #ignore_unknown for map coordinates with negatives
|
||||
@click.option("--map-position","-p", is_flag=True, help='clean provided map position instead of area, ex: "-602,1812,800,723"')
|
||||
@click.argument('area', type=click.STRING, required=True)
|
||||
def area(area, map_position):
|
||||
if map_position:
|
||||
return CliAction(SpotArea('start', map_position=area), wait=StatusWait('charge_status', 'returning'))
|
||||
else:
|
||||
return CliAction(SpotArea('start', area=area), wait=StatusWait('charge_status', 'returning'))
|
||||
|
||||
|
||||
@cli.command(help='returns to charger')
|
||||
def charge():
|
||||
return charge_action()
|
||||
|
||||
|
||||
def charge_action():
|
||||
return CliAction(Charge(), terminal=True, wait=StatusWait('charge_status', 'charging'))
|
||||
|
||||
|
||||
@cli.command(help='stops the robot in its current position')
|
||||
def stop():
|
||||
return CliAction(Stop(), terminal=True, wait=StatusWait('clean_status', 'stop'))
|
||||
|
||||
|
||||
@cli.resultcallback()
|
||||
def run(actions, debug):
|
||||
actions = list(filter(None.__ne__, actions))
|
||||
if actions and charge and not actions[-1].terminal:
|
||||
actions.append(charge_action())
|
||||
|
||||
if not config_file_exists():
|
||||
click.echo("Not logged in. Do 'click login' first.")
|
||||
exit(1)
|
||||
|
||||
if debug:
|
||||
_LOGGER.debug("will run {}".format(actions))
|
||||
|
||||
if actions:
|
||||
config = read_config()
|
||||
api = EcoVacsAPI(config['device_id'], config['email'], config['password_hash'],
|
||||
config['country'], config['continent'], verify_ssl=config['verify_ssl'])
|
||||
vacuum = api.devices()[0]
|
||||
vacbot = VacBot(api.uid, api.REALM, api.resource, api.user_access_token, vacuum, config['continent'], verify_ssl=config['verify_ssl'])
|
||||
vacbot.connect_and_wait_until_ready()
|
||||
|
||||
for action in actions:
|
||||
click.echo("performing " + str(action.vac_command))
|
||||
vacbot.run(action.vac_command)
|
||||
action.wait.wait(vacbot)
|
||||
|
||||
vacbot.disconnect(wait=True)
|
||||
|
||||
click.echo("done")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
cli()
|
||||
@@ -1,8 +0,0 @@
|
||||
import logging
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
#ecovacs constants
|
||||
#init constants
|
||||
ECOVACS_DEVICES = "ecovacs_devices"
|
||||
DOMAIN = "ecovacs"
|
||||
CONF_CONTINENT = "continent"
|
||||
@@ -1,236 +0,0 @@
|
||||
import time
|
||||
|
||||
import sched
|
||||
import threading
|
||||
import ssl
|
||||
import requests
|
||||
import stringcase
|
||||
from threading import Event
|
||||
from paho.mqtt.client import Client as ClientMQTT
|
||||
from paho.mqtt import publish as MQTTPublish
|
||||
from paho.mqtt import subscribe as MQTTSubscribe
|
||||
from sleekxmppfs.xmlstream import ET
|
||||
|
||||
from .const import LOGGER
|
||||
|
||||
#This is used by EcoVacsIOTMQ and EcoVacsXMPP for _ctl_to_dict
|
||||
def RepresentsInt(stringvar):
|
||||
try:
|
||||
int(stringvar)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
class EcoVacsIOTMQ(ClientMQTT):
|
||||
def __init__(self, user, domain, resource, secret, continent, vacuum, server_address=None, verify_ssl=True):
|
||||
ClientMQTT.__init__(self)
|
||||
self.ctl_subscribers = []
|
||||
self.user = user
|
||||
self.domain = str(domain).split(".")[0] #MQTT is using domain without tld extension
|
||||
self.resource = resource
|
||||
self.secret = secret
|
||||
self.continent = continent
|
||||
self.vacuum = vacuum
|
||||
self.scheduler = sched.scheduler(time.time, time.sleep)
|
||||
self.scheduler_thread = threading.Thread(target=self.scheduler.run, daemon=True, name="mqtt_schedule_thread")
|
||||
self.verify_ssl = str_to_bool_or_cert(verify_ssl)
|
||||
if server_address is None:
|
||||
self.hostname = ('mq-{}.ecouser.net'.format(self.continent))
|
||||
self.port = 8883
|
||||
else:
|
||||
saddress = server_address.split(":")
|
||||
if len(saddress) > 1:
|
||||
self.hostname = saddress[0]
|
||||
if RepresentsInt(saddress[1]):
|
||||
self.port = int(saddress[1])
|
||||
else:
|
||||
self.port = 8883
|
||||
self._client_id = self.user + '@' + self.domain.split(".")[0] + '/' + self.resource
|
||||
self.username_pw_set(self.user + '@' + self.domain, secret)
|
||||
self.ready_flag = Event()
|
||||
|
||||
def connect_and_wait_until_ready(self):
|
||||
#self._on_log = self.on_log #This provides more logging than needed, even for debug
|
||||
self._on_message = self._handle_ctl_mqtt
|
||||
self._on_connect = self.on_connect
|
||||
#TODO: This is pretty insecure and accepts any cert, maybe actually check?
|
||||
ssl_ctx = ssl.create_default_context()
|
||||
ssl_ctx.check_hostname = False
|
||||
ssl_ctx.verify_mode = ssl.CERT_NONE
|
||||
self.tls_set_context(ssl_ctx)
|
||||
self.tls_insecure_set(True)
|
||||
self.connect(self.hostname, self.port)
|
||||
self.loop_start()
|
||||
self.wait_until_ready()
|
||||
|
||||
def subscribe_to_ctls(self, function):
|
||||
self.ctl_subscribers.append(function)
|
||||
|
||||
def _disconnect(self):
|
||||
self.disconnect() #disconnect mqtt connection
|
||||
self.scheduler.empty() #Clear schedule queue
|
||||
|
||||
def _run_scheduled_func(self, timer_seconds, timer_function):
|
||||
timer_function()
|
||||
self.schedule(timer_seconds, timer_function)
|
||||
|
||||
def schedule(self, timer_seconds, timer_function):
|
||||
self.scheduler.enter(timer_seconds, 1, self._run_scheduled_func,(timer_seconds, timer_function))
|
||||
if not self.scheduler_thread.isAlive():
|
||||
self.scheduler_thread.start()
|
||||
|
||||
def wait_until_ready(self):
|
||||
self.ready_flag.wait()
|
||||
|
||||
def on_connect(self, client, userdata, flags, rc):
|
||||
if rc != 0:
|
||||
LOGGER.error("EcoVacsMQTT - error connecting with MQTT Return {}".format(rc))
|
||||
raise RuntimeError("EcoVacsMQTT - error connecting with MQTT Return {}".format(rc))
|
||||
else:
|
||||
LOGGER.debug("EcoVacsMQTT - Connected with result code "+str(rc))
|
||||
LOGGER.debug("EcoVacsMQTT - Subscribing to all")
|
||||
self.subscribe('iot/atr/+/' + self.vacuum['did'] + '/' + self.vacuum['class'] + '/' + self.vacuum['resource'] + '/+', qos=0)
|
||||
self.ready_flag.set()
|
||||
|
||||
#def on_log(self, client, userdata, level, buf): #This is very noisy and verbose
|
||||
# LOGGER.debug("EcoVacsMQTT Log: {} ".format(buf))
|
||||
|
||||
def send_ping(self):
|
||||
LOGGER.debug("*** MQTT sending ping ***")
|
||||
rc = self._send_simple_command(MQTTPublish.paho.PINGREQ)
|
||||
if rc == MQTTPublish.paho.MQTT_ERR_SUCCESS:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def send_command(self, action, recipient):
|
||||
if action.name == "Clean": #For handling Clean when action not specified (i.e. CLI)
|
||||
action.args['clean']['act'] = CLEAN_ACTION_TO_ECOVACS['start'] #Inject a start action
|
||||
c = self._wrap_command(action, recipient)
|
||||
LOGGER.debug('Sending command {0}'.format(c))
|
||||
self._handle_ctl_api(action,
|
||||
self.__call_iotdevmanager_api(c ,verify_ssl=self.verify_ssl )
|
||||
)
|
||||
|
||||
def _wrap_command(self, cmd, recipient):
|
||||
#Remove the td from ctl xml for RestAPI
|
||||
payloadxml = cmd.to_xml()
|
||||
payloadxml.attrib.pop("td")
|
||||
return {
|
||||
'auth': {
|
||||
'realm': EcoVacsAPI.REALM,
|
||||
'resource': self.resource,
|
||||
'token': self.secret,
|
||||
'userid': self.user,
|
||||
'with': 'users',
|
||||
},
|
||||
"cmdName": cmd.name,
|
||||
"payload": ET.tostring(payloadxml).decode(),
|
||||
|
||||
"payloadType": "x",
|
||||
"td": "q",
|
||||
"toId": recipient,
|
||||
"toRes": self.vacuum['resource'],
|
||||
"toType": self.vacuum['class']
|
||||
}
|
||||
|
||||
def __call_iotdevmanager_api(self, args, verify_ssl=True):
|
||||
LOGGER.debug("calling iotdevmanager api with {}".format(args))
|
||||
params = {}
|
||||
params.update(args)
|
||||
url = (EcoVacsAPI.PORTAL_URL_FORMAT + "/iot/devmanager.do").format(continent=self.continent)
|
||||
response = None
|
||||
try: #The RestAPI sometimes doesnt provide a response depending on command, reduce timeout to 3 to accomodate and make requests faster
|
||||
response = requests.post(url, json=params, timeout=3, verify=verify_ssl) #May think about having timeout as an arg that could be provided in the future
|
||||
except requests.exceptions.ReadTimeout:
|
||||
LOGGER.debug("call to iotdevmanager failed with ReadTimeout")
|
||||
return {}
|
||||
json = response.json()
|
||||
if json['ret'] == 'ok':
|
||||
return json
|
||||
elif json['ret'] == 'fail':
|
||||
if 'debug' in json:
|
||||
if json['debug'] == 'wait for response timed out':
|
||||
#TODO - Maybe handle timeout for IOT better in the future
|
||||
LOGGER.error("call to iotdevmanager failed with {}".format(json))
|
||||
return {}
|
||||
else:
|
||||
#TODO - Not sure if we want to raise an error yet, just return empty for now
|
||||
LOGGER.error("call to iotdevmanager failed with {}".format(json))
|
||||
return {}
|
||||
#raise RuntimeError(
|
||||
#"failure {} ({}) for call {} and parameters {}".format(json['error'], json['errno'], function, params))
|
||||
|
||||
def _handle_ctl_api(self, action, message):
|
||||
if not message == {}:
|
||||
resp = self._ctl_to_dict_api(action, message['resp'])
|
||||
if resp is not None:
|
||||
for s in self.ctl_subscribers:
|
||||
s(resp)
|
||||
|
||||
def _ctl_to_dict_api(self, action, xmlstring):
|
||||
xml = ET.fromstring(xmlstring)
|
||||
xmlchild = xml.getchildren()
|
||||
if len(xmlchild) > 0:
|
||||
result = xmlchild[0].attrib.copy()
|
||||
#Fix for difference in XMPP vs API response
|
||||
#Depending on the report will use the tag and add "report" to fit the mold of sucks library
|
||||
if xmlchild[0].tag == "clean":
|
||||
result['event'] = "CleanReport"
|
||||
elif xmlchild[0].tag == "charge":
|
||||
result['event'] = "ChargeState"
|
||||
elif xmlchild[0].tag == "battery":
|
||||
result['event'] = "BatteryInfo"
|
||||
else: #Default back to replacing Get from the api cmdName
|
||||
result['event'] = action.name.replace("Get","",1)
|
||||
else:
|
||||
result = xml.attrib.copy()
|
||||
result['event'] = action.name.replace("Get","",1)
|
||||
if 'ret' in result: #Handle errors as needed
|
||||
if result['ret'] == 'fail':
|
||||
if action.name == "Charge": #So far only seen this with Charge, when already docked
|
||||
result['event'] = "ChargeState"
|
||||
for key in result:
|
||||
if not RepresentsInt(result[key]): #Fix to handle negative int values
|
||||
result[key] = stringcase.snakecase(result[key])
|
||||
return result
|
||||
|
||||
def _handle_ctl_mqtt(self, client, userdata, message):
|
||||
#LOGGER.debug("EcoVacs MQTT Received Message on Topic: {} - Message: {}".format(message.topic, str(message.payload.decode("utf-8"))))
|
||||
as_dict = self._ctl_to_dict_mqtt(message.topic, str(message.payload.decode("utf-8")))
|
||||
if as_dict is not None:
|
||||
for s in self.ctl_subscribers:
|
||||
s(as_dict)
|
||||
|
||||
def _ctl_to_dict_mqtt(self, topic, xmlstring):
|
||||
#I haven't seen the need to fall back to data within the topic (like we do with IOT rest call actions), but it is here in case of future need
|
||||
xml = ET.fromstring(xmlstring) #Convert from string to xml (like IOT rest calls), other than this it is similar to XMPP
|
||||
#Including changes from jasonarends @ 28da7c2 below
|
||||
result = xml.attrib.copy()
|
||||
if 'td' not in result:
|
||||
# This happens for commands with no response data, such as PlaySound
|
||||
# Handle response data with no 'td'
|
||||
if 'type' in result: # single element with type and val
|
||||
result['event'] = "LifeSpan" # seems to always be LifeSpan type
|
||||
else:
|
||||
if len(xml) > 0: # case where there is child element
|
||||
if 'clean' in xml[0].tag:
|
||||
result['event'] = "CleanReport"
|
||||
elif 'charge' in xml[0].tag:
|
||||
result['event'] = "ChargeState"
|
||||
elif 'battery' in xml[0].tag:
|
||||
result['event'] = "BatteryInfo"
|
||||
else:
|
||||
return
|
||||
result.update(xml[0].attrib)
|
||||
else: # for non-'type' result with no child element, e.g., result of PlaySound
|
||||
return
|
||||
else: # response includes 'td'
|
||||
result['event'] = result.pop('td')
|
||||
if xml:
|
||||
result.update(xml[0].attrib)
|
||||
for key in result:
|
||||
#Check for RepresentInt to handle negative int values, and ',' for ignoring position updates
|
||||
if not RepresentsInt(result[key]) and ',' not in result[key]:
|
||||
result[key] = stringcase.snakecase(result[key])
|
||||
return result
|
||||
@@ -1,109 +0,0 @@
|
||||
#sucks constants
|
||||
# These consts define all of the vocabulary used by this library when presenting various states and components.
|
||||
# Applications implementing this library should import these rather than hard-code the strings, for future-proofing.
|
||||
|
||||
CLEAN_MODE_AUTO = 'auto'
|
||||
CLEAN_MODE_EDGE = 'edge'
|
||||
CLEAN_MODE_SPOT = 'spot'
|
||||
CLEAN_MODE_SPOT_AREA = 'spot_area'
|
||||
CLEAN_MODE_SINGLE_ROOM = 'single_room'
|
||||
CLEAN_MODE_STOP = 'stop'
|
||||
|
||||
CLEAN_ACTION_START = 'start'
|
||||
CLEAN_ACTION_PAUSE = 'pause'
|
||||
CLEAN_ACTION_RESUME = 'resume'
|
||||
CLEAN_ACTION_STOP = 'stop'
|
||||
|
||||
FAN_SPEED_NORMAL = 'normal'
|
||||
FAN_SPEED_HIGH = 'high'
|
||||
|
||||
CHARGE_MODE_RETURN = 'return'
|
||||
CHARGE_MODE_RETURNING = 'returning'
|
||||
CHARGE_MODE_CHARGING = 'charging'
|
||||
CHARGE_MODE_IDLE = 'idle'
|
||||
|
||||
COMPONENT_SIDE_BRUSH = 'side_brush'
|
||||
COMPONENT_MAIN_BRUSH = 'main_brush'
|
||||
COMPONENT_FILTER = 'filter'
|
||||
|
||||
VACUUM_STATUS_OFFLINE = 'offline'
|
||||
|
||||
CLEANING_STATES = {CLEAN_MODE_AUTO, CLEAN_MODE_EDGE, CLEAN_MODE_SPOT, CLEAN_MODE_SPOT_AREA, CLEAN_MODE_SINGLE_ROOM}
|
||||
CHARGING_STATES = {CHARGE_MODE_CHARGING}
|
||||
|
||||
# These dictionaries convert to and from Sucks's consts (which closely match what the UI and manuals use)
|
||||
# to and from what the Ecovacs API uses (which are sometimes very oddly named and have random capitalization.)
|
||||
CLEAN_MODE_TO_ECOVACS = {
|
||||
CLEAN_MODE_AUTO: 'auto',
|
||||
CLEAN_MODE_EDGE: 'border',
|
||||
CLEAN_MODE_SPOT: 'spot',
|
||||
CLEAN_MODE_SPOT_AREA: 'SpotArea',
|
||||
CLEAN_MODE_SINGLE_ROOM: 'singleroom',
|
||||
CLEAN_MODE_STOP: 'stop'
|
||||
}
|
||||
|
||||
CLEAN_ACTION_TO_ECOVACS = {
|
||||
CLEAN_ACTION_START: 's',
|
||||
CLEAN_ACTION_PAUSE: 'p',
|
||||
CLEAN_ACTION_RESUME: 'r',
|
||||
CLEAN_ACTION_STOP: 'h',
|
||||
}
|
||||
|
||||
CLEAN_ACTION_FROM_ECOVACS = {
|
||||
's': CLEAN_ACTION_START,
|
||||
'p': CLEAN_ACTION_PAUSE,
|
||||
'r': CLEAN_ACTION_RESUME,
|
||||
'h': CLEAN_ACTION_STOP,
|
||||
}
|
||||
|
||||
CLEAN_MODE_FROM_ECOVACS = {
|
||||
'auto': CLEAN_MODE_AUTO,
|
||||
'border': CLEAN_MODE_EDGE,
|
||||
'spot': CLEAN_MODE_SPOT,
|
||||
'spot_area': CLEAN_MODE_SPOT_AREA,
|
||||
'SpotArea': CLEAN_MODE_SPOT_AREA,
|
||||
'singleroom': CLEAN_MODE_SINGLE_ROOM,
|
||||
'stop': CLEAN_MODE_STOP,
|
||||
'going': CHARGE_MODE_RETURNING,
|
||||
}
|
||||
|
||||
FAN_SPEED_TO_ECOVACS = {
|
||||
FAN_SPEED_NORMAL: 'standard',
|
||||
FAN_SPEED_HIGH: 'strong'
|
||||
}
|
||||
|
||||
FAN_SPEED_FROM_ECOVACS = {
|
||||
'standard': FAN_SPEED_NORMAL,
|
||||
'strong': FAN_SPEED_HIGH,
|
||||
}
|
||||
|
||||
CHARGE_MODE_TO_ECOVACS = {
|
||||
CHARGE_MODE_RETURN: 'go',
|
||||
CHARGE_MODE_RETURNING: 'Going',
|
||||
CHARGE_MODE_CHARGING: 'SlotCharging',
|
||||
CHARGE_MODE_IDLE: 'Idle',
|
||||
}
|
||||
|
||||
CHARGE_MODE_FROM_ECOVACS = {
|
||||
'going': CHARGE_MODE_RETURNING,
|
||||
# 'Going': CHARGE_MODE_RETURNING,
|
||||
'slot_charging': CHARGE_MODE_CHARGING,
|
||||
# 'SlotCharging': CHARGE_MODE_CHARGING,
|
||||
'idle': CHARGE_MODE_IDLE,
|
||||
# 'Idle': CHARGE_MODE_IDLE,
|
||||
}
|
||||
|
||||
COMPONENT_TO_ECOVACS = {
|
||||
COMPONENT_MAIN_BRUSH: 'Brush',
|
||||
COMPONENT_SIDE_BRUSH: 'SideBrush',
|
||||
COMPONENT_FILTER: 'DustCaseHeap',
|
||||
}
|
||||
|
||||
COMPONENT_FROM_ECOVACS = {
|
||||
'brush': COMPONENT_MAIN_BRUSH,
|
||||
# 'Brush': COMPONENT_MAIN_BRUSH,
|
||||
'side_brush': COMPONENT_SIDE_BRUSH,
|
||||
# 'SideBrush': COMPONENT_SIDE_BRUSH,
|
||||
'dust_case_heap': COMPONENT_FILTER,
|
||||
# 'DustCaseHeap': COMPONENT_FILTER,
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
import stringcase
|
||||
import random
|
||||
from threading import Event
|
||||
from sleekxmppfs import ClientXMPP, Callback, MatchXPath
|
||||
from sleekxmppfs.xmlstream import ET
|
||||
#from sleekxmppfs.exceptions import XMPPError
|
||||
from .const import LOGGER
|
||||
|
||||
#This is used by EcoVacsIOTMQ and EcoVacsXMPP for _ctl_to_dict
|
||||
def RepresentsInt(stringvar):
|
||||
try:
|
||||
int(stringvar)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
class EcoVacsXMPP(ClientXMPP):
|
||||
def __init__(self, user, domain, resource, secret, continent, vacuum, server_address=None ):
|
||||
ClientXMPP.__init__(self, "{}@{}/{}".format(user, domain,resource), '0/' + resource + '/' + secret) #Init with resource to bind it
|
||||
self.user = user
|
||||
self.domain = domain
|
||||
self.boundjid.resource = resource
|
||||
self.continent = continent
|
||||
self.vacuum = vacuum
|
||||
self.credentials['authzid'] = user
|
||||
if server_address is None:
|
||||
self.server_address = ('msg-{}.ecouser.net'.format(self.continent), '5223')
|
||||
else:
|
||||
self.server_address = server_address
|
||||
self.add_event_handler("session_start", self.session_start)
|
||||
self.ctl_subscribers = []
|
||||
self.ready_flag = Event()
|
||||
|
||||
def wait_until_ready(self):
|
||||
self.ready_flag.wait()
|
||||
|
||||
def session_start(self, event):
|
||||
LOGGER.debug("----------------- starting session ----------------")
|
||||
LOGGER.debug("event = {}".format(event))
|
||||
self.register_handler(Callback("general",
|
||||
MatchXPath('{jabber:client}iq/{com:ctl}query/{com:ctl}'),
|
||||
self._handle_ctl))
|
||||
# register a ping handler, not really needed but keeps from errors being thrown
|
||||
self.register_handler(Callback("Ping",
|
||||
MatchXPath('{jabber:client}iq/{urn:xmpp:ping}ping/{urn:xmpp:ping}'),
|
||||
self._handle_ping))
|
||||
self.ready_flag.set()
|
||||
|
||||
def subscribe_to_ctls(self, function):
|
||||
self.ctl_subscribers.append(function)
|
||||
|
||||
def _handle_ctl(self, message):
|
||||
the_good_part = message.get_payload()[0][0]
|
||||
as_dict = self._ctl_to_dict(the_good_part)
|
||||
if as_dict is not None:
|
||||
for s in self.ctl_subscribers:
|
||||
s(as_dict)
|
||||
|
||||
def _ctl_to_dict(self, xml):
|
||||
#Including changes from jasonarends @ 28da7c2 below
|
||||
result = xml.attrib.copy()
|
||||
childxml = None
|
||||
try: # check for child xml
|
||||
childxml = xml[0]
|
||||
except IndexError:
|
||||
LOGGER.debug("No child xml")
|
||||
if 'td' not in result:
|
||||
# Handle response data with no 'td'
|
||||
if 'type' in result: # single element with type and val
|
||||
result['event'] = "LifeSpan" # seems to always be LifeSpan type
|
||||
else:
|
||||
if childxml is not None:
|
||||
if 'clean' in childxml.tag:
|
||||
result['event'] = "CleanReport"
|
||||
elif 'charge' in childxml.tag:
|
||||
result['event'] = "ChargeState"
|
||||
elif 'battery' in childxml.tag:
|
||||
result['event'] = "BatteryInfo"
|
||||
else:
|
||||
return
|
||||
result.update(childxml.attrib)
|
||||
else: # for non-'type' result with no child element, e.g., result of PlaySound
|
||||
return
|
||||
else: # response includes 'td'
|
||||
result['event'] = result.pop('td')
|
||||
if xml:
|
||||
result.update(xml[0].attrib) # reponses with td seem to always have child component
|
||||
for key in result:
|
||||
#Check for RepresentInt to handle negative int values, and ',' for ignoring position updates
|
||||
if not RepresentsInt(result[key]) and ',' not in result[key]:
|
||||
result[key] = stringcase.snakecase(result[key])
|
||||
return result
|
||||
|
||||
def register_callback(self, userdata, message):
|
||||
self.register_handler(Callback(kind,
|
||||
MatchXPath('{jabber:client}iq/{com:ctl}query/{com:ctl}ctl[@td="' + kind + '"]'),
|
||||
function))
|
||||
|
||||
def send_command(self, xml, recipient):
|
||||
c = self._wrap_command(xml, recipient)
|
||||
LOGGER.debug('Sending command {0}'.format(c))
|
||||
c.send()
|
||||
|
||||
def _wrap_command(self, ctl, recipient):
|
||||
q = self.make_iq_query(xmlns=u'com:ctl', ito=recipient, ifrom=self._my_address())
|
||||
q['type'] = 'set'
|
||||
if not "id" in ctl.attrib:
|
||||
ctl.attrib["id"] = self.getReqID() #If no ctl id provided, add an id to the ctl. This was required for the ozmo930 and shouldn't hurt others
|
||||
for child in q.xml:
|
||||
if child.tag.endswith('query'):
|
||||
child.append(ctl)
|
||||
return q
|
||||
|
||||
def getReqID(self, customid="0"): #Generate a somewhat random string for request id, with minium 8 chars. Works similar to ecovacs app.
|
||||
if customid != "0":
|
||||
return "{}".format(customid) #return provided id as string
|
||||
else:
|
||||
rtnval = str(random.randint(1,50))
|
||||
while len(str(rtnval)) <= 8:
|
||||
rtnval = "{}{}".format(rtnval,random.randint(0,50))
|
||||
return "{}".format(rtnval) #return as string
|
||||
|
||||
def _my_address(self):
|
||||
if not self.vacuum['iotmq']:
|
||||
return self.user + '@' + self.domain + '/' + self.boundjid.resource
|
||||
else:
|
||||
return self.user + '@' + self.domain + '/' + self.resource
|
||||
|
||||
def send_ping(self, to):
|
||||
q = self.make_iq_get(ito=to, ifrom=self._my_address())
|
||||
q.xml.append(ET.Element('ping', {'xmlns': 'urn:xmpp:ping'}))
|
||||
LOGGER.debug("*** sending ping ***")
|
||||
q.send()
|
||||
|
||||
# used some code from a sleekxmppfs plugin, seems to work fine
|
||||
def _handle_ping(self, iq):
|
||||
LOGGER.debug("Pinged by %s", iq['from'])
|
||||
iq.reply().send()
|
||||
|
||||
def connect_and_wait_until_ready(self):
|
||||
self.connect(self.server_address)
|
||||
self.process()
|
||||
self.wait_until_ready()
|
||||
@@ -1,62 +0,0 @@
|
||||
import tempfile
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from nose.tools import *
|
||||
|
||||
from sucks.cli import *
|
||||
|
||||
|
||||
def test_config_file_name():
|
||||
if platform.system() == 'Windows':
|
||||
print(config_file())
|
||||
assert_true(re.match(r'[A-Z]:\\.+\\\w+\\AppData(\\Roaming)?\\sucks.conf', config_file()))
|
||||
else:
|
||||
assert_true(re.match(r'/.+/\w+/.config/sucks.conf', config_file()))
|
||||
|
||||
|
||||
def test_write_and_read_config():
|
||||
with patch('sucks.cli.config_file',
|
||||
Mock(return_value=os.path.join(tempfile.mkdtemp(), 'some_other_dir', 'sucks.conf'))):
|
||||
write_config({'a': "ayyy", 'b': 2})
|
||||
config2 = read_config()
|
||||
assert_equals(config2['a'], 'ayyy')
|
||||
assert_equals(config2['b'], '2')
|
||||
|
||||
|
||||
def test_frequency_param_type():
|
||||
t = FREQUENCY
|
||||
assert_equals(t.convert('0', None, None), 0)
|
||||
assert_equals(t.convert('1', None, None), 1.0)
|
||||
assert_equals(t.convert('1/2', None, None), 0.5)
|
||||
assert_equals(t.convert('1/7', None, None), 1.0 / 7.0)
|
||||
assert_equals(t.convert('1/14', None, None), 1.0 / 14.0)
|
||||
assert_equals(t.convert('1/1000', None, None), 1.0 / 1000.0)
|
||||
assert_equals(t.convert('1.5/2', None, None), 1.5 / 2.0)
|
||||
assert_equals(t.convert('0/2', None, None), 0)
|
||||
with assert_raises(click.exceptions.BadParameter):
|
||||
t.convert('bob', None, None)
|
||||
with assert_raises(click.exceptions.BadParameter):
|
||||
t.convert('2', None, None)
|
||||
with assert_raises(click.exceptions.BadParameter):
|
||||
t.convert('7/5', None, None)
|
||||
with assert_raises(click.exceptions.BadParameter):
|
||||
t.convert('1/0', None, None)
|
||||
|
||||
|
||||
def test_should_run():
|
||||
count = 0
|
||||
for _ in range(10000):
|
||||
if should_run(0.1):
|
||||
count += 1
|
||||
assert_almost_equal(count, 1000, delta=200)
|
||||
|
||||
count = 0
|
||||
for _ in range(10000):
|
||||
if should_run(0.9):
|
||||
count += 1
|
||||
assert_almost_equal(count, 9000, delta=200)
|
||||
|
||||
|
||||
def test_continent_for_country():
|
||||
assert_equal(continent_for_country('us'), 'na')
|
||||
assert_equal(continent_for_country('fr'), 'eu')
|
||||
@@ -1,184 +0,0 @@
|
||||
from xml.etree import ElementTree
|
||||
|
||||
from nose.tools import *
|
||||
|
||||
from sucks import *
|
||||
|
||||
|
||||
def test_custom_command():
|
||||
# Ensure a custom-built command generates the expected XML payload
|
||||
c = VacBotCommand('CustomCommand', {'type': 'customtype'})
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="CustomCommand" type="customtype" />')
|
||||
|
||||
|
||||
def test_custom_command_inner_tag():
|
||||
# Ensure a custom-built command generates the expected XML payload
|
||||
c = VacBotCommand('CustomCommand', {'customtag': {'customvar': 'customvalue'}})
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="CustomCommand"><customtag customvar="customvalue" /></ctl>')
|
||||
|
||||
|
||||
def test_custom_command_multiple_inner_tag():
|
||||
# Ensure a custom-built command with multiple inner tags generates the expected XML payload
|
||||
c = VacBotCommand('CustomCommand', {"customtag":[{"customvar":"customvalue1"},{"customvar":"customvalue2"}]})
|
||||
logging.info(ElementTree.tostring(c.to_xml()))
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="CustomCommand"><customtag customvar="customvalue1" /><customtag customvar="customvalue2" /></ctl>')
|
||||
|
||||
def test_custom_command_args_multiple_inner_tag():
|
||||
# Ensure a custom-built command with args and multiple inner tags generates the expected XML payload
|
||||
c = VacBotCommand('CustomCommand', {"arg1":"value1","customtag":[{"customvar":"customvalue1"},{"customvar":"customvalue2"}]})
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl arg1="value1" td="CustomCommand"><customtag customvar="customvalue1" /><customtag customvar="customvalue2" /></ctl>')
|
||||
|
||||
|
||||
def test_custom_command_noargs():
|
||||
# Ensure a custom-built command with no args generates XML without an args element
|
||||
c = VacBotCommand('CustomCommand')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="CustomCommand" />')
|
||||
|
||||
|
||||
def test_clean_command():
|
||||
c = Clean()
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" speed="standard" type="auto" /></ctl>') # protocol has attribs in other order
|
||||
|
||||
c = Clean('edge', 'high')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" speed="strong" type="border" /></ctl>') # protocol has attribs in other order
|
||||
|
||||
c = Clean(iotmq=True)
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" speed="standard" type="auto" /></ctl>') # test for iot act is added
|
||||
|
||||
|
||||
def test_spotarea_command():
|
||||
assert_raises(ValueError, SpotArea, 'start') #Value error if SpotArea doesn't include a mid or p
|
||||
|
||||
c = SpotArea('start', '0')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" mid="0" speed="standard" type="SpotArea" /></ctl>') #Test namedarea clean
|
||||
|
||||
c = SpotArea('start', area='0')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" mid="0" speed="standard" type="SpotArea" /></ctl>') #Test namedarea keyword clean
|
||||
|
||||
c = SpotArea('start', '', '-602,1812,800,723')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" deep="1" p="-602,1812,800,723" speed="standard" type="SpotArea" /></ctl>') #Test customarea clean
|
||||
|
||||
c = SpotArea('start', '', '-602,1812,800,723', '2')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" deep="2" p="-602,1812,800,723" speed="standard" type="SpotArea" /></ctl>') #Test customarea clean with deep 2
|
||||
|
||||
c = SpotArea('start', '', map_position='-602,1812,800,723')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" deep="1" p="-602,1812,800,723" speed="standard" type="SpotArea" /></ctl>') #Test customarea keyword clean with deep default
|
||||
|
||||
c = SpotArea('start', map_position='-602,1812,800,723', cleanings='2')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" deep="2" p="-602,1812,800,723" speed="standard" type="SpotArea" /></ctl>') #Test customarea keyword and cleanings keyword clean with deep default
|
||||
|
||||
c = SpotArea('start', area='0', map_position='-602,1812,800,723', cleanings='2')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" mid="0" speed="standard" type="SpotArea" /></ctl>') #Test all keywords specified, should default to only mid
|
||||
|
||||
c = SpotArea('start', '0', '-602,1812,800,723','2')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" mid="0" speed="standard" type="SpotArea" /></ctl>') #Test all keywords specified, should default to only mid
|
||||
|
||||
|
||||
def test_edge_command():
|
||||
c = Edge()
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" speed="strong" type="border" /></ctl>') # protocol has attribs in other order
|
||||
|
||||
|
||||
def test_spot_command():
|
||||
c = Spot()
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" speed="strong" type="spot" /></ctl>') # protocol has attribs in other order
|
||||
|
||||
|
||||
def test_charge_command():
|
||||
c = Charge()
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Charge"><charge type="go" /></ctl>')
|
||||
|
||||
|
||||
def test_stop_command():
|
||||
c = Stop()
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Clean"><clean act="s" speed="standard" type="stop" /></ctl>')
|
||||
|
||||
|
||||
def test_play_sound_command():
|
||||
c = PlaySound()
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl sid="0" td="PlaySound" />')
|
||||
|
||||
|
||||
def test_play_sound_command_with_sid():
|
||||
c = PlaySound(sid="1")
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl sid="1" td="PlaySound" />')
|
||||
|
||||
|
||||
def test_get_clean_state_command():
|
||||
c = GetCleanState()
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="GetCleanState" />')
|
||||
|
||||
|
||||
def test_get_charge_state_command():
|
||||
c = GetChargeState()
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="GetChargeState" />')
|
||||
|
||||
|
||||
def test_get_battery_state_command():
|
||||
c = GetBatteryState()
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="GetBatteryInfo" />')
|
||||
|
||||
|
||||
def test_move_command():
|
||||
c = Move(action='left')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Move"><move action="SpinLeft" /></ctl>')
|
||||
c = Move(action='right')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Move"><move action="SpinRight" /></ctl>')
|
||||
c = Move(action='turn_around')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Move"><move action="TurnAround" /></ctl>')
|
||||
c = Move(action='forward')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Move"><move action="forward" /></ctl>')
|
||||
c = Move(action='backward')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Move"><move action="backward" /></ctl>')
|
||||
c = Move(action='stop')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="Move"><move action="stop" /></ctl>')
|
||||
|
||||
|
||||
def test_get_lifepsan_command():
|
||||
c = GetLifeSpan('main_brush')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="GetLifeSpan" type="Brush" />')
|
||||
|
||||
c = GetLifeSpan('side_brush')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="GetLifeSpan" type="SideBrush" />')
|
||||
|
||||
c = GetLifeSpan('filter')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="GetLifeSpan" type="DustCaseHeap" />')
|
||||
|
||||
def test_set_time_command():
|
||||
c = SetTime('1234', 'GMT-5')
|
||||
assert_equals(ElementTree.tostring(c.to_xml()),
|
||||
b'<ctl td="SetTime"><time t="1234" tz="GMT-5" /></ctl>')
|
||||
@@ -1,190 +0,0 @@
|
||||
from re import compile
|
||||
|
||||
import requests_mock
|
||||
from nose.tools import *
|
||||
|
||||
from sucks import *
|
||||
|
||||
|
||||
def test_md5():
|
||||
assert_equal(EcoVacsAPI.md5("fnord"), "b15e400c8dbd6697f26385216d32a40f")
|
||||
|
||||
|
||||
def test_encrypt():
|
||||
assert_equal(len(EcoVacsAPI.encrypt("fnord")), 172)
|
||||
|
||||
|
||||
def test_main_api_setup():
|
||||
with requests_mock.mock() as m:
|
||||
r1 = m.get(compile('user/login'),
|
||||
text='{"time": 1511200804243, "data": {"accessToken": "7a375650b0b1efd780029284479c4e41", "uid": "2017102559f0ee63c588d", "username": null, "email": "william-ecovacs@pota.to", "country": "us"}, "code": "0000", "msg": "X"}')
|
||||
r2 = m.get(compile('user/getAuthCode'),
|
||||
text='{"time": 1511200804607, "data": {"authCode": "5c28dac1ff580210e11292df57e87bef"}, "code": "0000", "msg": "X"}')
|
||||
r3 = m.post(compile('user.do'),
|
||||
text='{"todo": "result", "token": "jt5O7oDR3gPHdVKCeb8Czx8xw8mDXM6s", "result": "ok", "userId": "2017102559f0ee63c588d", "resource": "f8d99c4d"}')
|
||||
|
||||
api = EcoVacsAPI("long_device_id", "account_id", "password_hash", 'us', 'na')
|
||||
|
||||
# verify setup
|
||||
assert_equals(api.resource, "long_dev")
|
||||
|
||||
# verify calls
|
||||
assert_equals(r1.call_count, 1)
|
||||
assert_equals(r2.call_count, 1)
|
||||
assert_equals(r3.call_count, 1)
|
||||
|
||||
# verify state
|
||||
assert_equals(api.uid, "2017102559f0ee63c588d")
|
||||
assert_equals(api.login_access_token, "7a375650b0b1efd780029284479c4e41")
|
||||
assert_equals(api.auth_code, "5c28dac1ff580210e11292df57e87bef")
|
||||
assert_equals(api.user_access_token, "jt5O7oDR3gPHdVKCeb8Czx8xw8mDXM6s")
|
||||
|
||||
#Test old user api endpoint
|
||||
postdata = {'country': 'US',
|
||||
'resource': "f8d99c4d",
|
||||
'realm': EcoVacsAPI.REALM,
|
||||
'userId': "2017102559f0ee63c588d",
|
||||
'token': "jt5O7oDR3gPHdVKCeb8Czx8xw8mDXM6s"}
|
||||
|
||||
r = api._EcoVacsAPI__call_user_api("loginByItToken", postdata)
|
||||
assert_equals(r3.call_count, 2)
|
||||
# verify state
|
||||
assert_equals(api.uid, "2017102559f0ee63c588d")
|
||||
assert_equals(api.login_access_token, "7a375650b0b1efd780029284479c4e41")
|
||||
assert_equals(api.auth_code, "5c28dac1ff580210e11292df57e87bef")
|
||||
assert_equals(api.user_access_token, "jt5O7oDR3gPHdVKCeb8Czx8xw8mDXM6s")
|
||||
|
||||
|
||||
|
||||
|
||||
def test_main_api_setup_with_alternate_uid():
|
||||
# Under mysterious circumstances, for certain people the last call sometimes returns a different userId
|
||||
# along with the user access token. If that's the case, we should use that as the UID for future calls
|
||||
|
||||
with requests_mock.mock() as m:
|
||||
r1 = m.get(compile('user/login'),
|
||||
text='{"time": 1511200804243, "data": {"accessToken": "7a375650b0b1efd780029284479c4e41", "uid": "2017102559f0ee63c588d", "username": null, "email": "william-ecovacs@pota.to", "country": "us"}, "code": "0000", "msg": "X"}')
|
||||
r2 = m.get(compile('user/getAuthCode'),
|
||||
text='{"time": 1511200804607, "data": {"authCode": "5c28dac1ff580210e11292df57e87bef"}, "code": "0000", "msg": "X"}')
|
||||
r3 = m.post(compile('user.do'),
|
||||
text='{"todo": "result", "token": "jt5O7oDR3gPHdVKCeb8Czx8xw8mDXM6s", "result": "ok", "userId": "abcdef", "resource": "f8d99c4d"}')
|
||||
|
||||
api = EcoVacsAPI("long_device_id", "account_id", "password_hash", 'us', 'na')
|
||||
|
||||
assert_equals(r1.call_count, 1)
|
||||
assert_equals(r2.call_count, 1)
|
||||
assert_equals(r3.call_count, 1)
|
||||
|
||||
# verify state
|
||||
assert_equals(api.uid, "abcdef")
|
||||
assert_equals(api.login_access_token, "7a375650b0b1efd780029284479c4e41")
|
||||
assert_equals(api.auth_code, "5c28dac1ff580210e11292df57e87bef")
|
||||
assert_equals(api.user_access_token, "jt5O7oDR3gPHdVKCeb8Czx8xw8mDXM6s")
|
||||
|
||||
def test_main_api_errorcode():
|
||||
with requests_mock.mock() as m:
|
||||
r1 = m.get(compile('user/login'), #test with 0004 (invalid token)
|
||||
text='{"time": 1511200804243, "code": "0004", "msg": "X", "data": null}')
|
||||
|
||||
assert_raises(RuntimeError, EcoVacsAPI, "long_device_id", "account_id", "password_hash", 'us', 'na') #Runtime error from code 0004
|
||||
|
||||
|
||||
def test_main_api_badpassword():
|
||||
with requests_mock.mock() as m:
|
||||
r1 = m.get(compile('user/login'), #test with 1005 (incorrect email or password)
|
||||
text='{"time": 1511200804243, "code": "1005", "msg": "X", "data": null}')
|
||||
|
||||
assert_raises(ValueError, EcoVacsAPI, "long_device_id", "account_id", "password_hash", 'us', 'na') #ValueError error from code 1005
|
||||
|
||||
|
||||
def test_device_lookup():
|
||||
api = make_api()
|
||||
with requests_mock.mock() as m:
|
||||
|
||||
#Not IOTMQ
|
||||
device_id = 'E0000001234567890123'
|
||||
device_class = '126'
|
||||
device_company = 'eco-legacy'
|
||||
r = m.post(compile('user.do'),
|
||||
text='{"todo": "result", "devices": [{"did": "%s", "company": "%s", "class": "%s", "nick": "bob"}], "result": "ok"}' %(device_id, device_company, device_class))
|
||||
|
||||
d = api.devices()
|
||||
assert_equals(r.call_count, 1)
|
||||
assert_equals(len(d), 1)
|
||||
vacuum = d[0]
|
||||
assert_equals(vacuum['did'], device_id)
|
||||
assert_equals(vacuum['class'], '126')
|
||||
assert_equals(vacuum['iotmq'], False)
|
||||
|
||||
#Is IOTMQ
|
||||
device_class = 'ls1ok3' #D900
|
||||
device_company = 'eco-ng'
|
||||
r = m.post(compile('user.do'),
|
||||
text='{"todo": "result", "devices": [{"did": "%s", "company": "%s", "class": "%s", "nick": "bob"}], "result": "ok"}' %(device_id, device_company, device_class))
|
||||
|
||||
d = api.devices()
|
||||
assert_equals(r.call_count, 1)
|
||||
assert_equals(len(d), 1)
|
||||
vacuum = d[0]
|
||||
assert_equals(vacuum['did'], device_id)
|
||||
assert_equals(vacuum['class'], device_class)
|
||||
assert_equals(vacuum['iotmq'], True)
|
||||
|
||||
|
||||
def test_device_lookup_IOTProduct():
|
||||
api = make_api()
|
||||
with requests_mock.mock() as m:
|
||||
|
||||
#Is IOTProduct
|
||||
device_id = 'E0000001234567890123'
|
||||
device_class = 'ls1ok3' #D900
|
||||
device_company = 'eco-ng'
|
||||
|
||||
r = m.post(compile('user.do'),
|
||||
text='{"todo": "result", "devices": [{"did": "%s", "company": "%s", "class": "%s", "nick": "bob"}], "result": "ok"}' %(device_id, device_company, device_class))
|
||||
r = m.post(compile('pim/product/getProductIotMap'),
|
||||
text='{"code":0,"data":[{"classid":"dl8fht","product":{"_id":"5acb0fa87c295c0001876ecf","name":"DEEBOT 600 Series","icon":"5acc32067c295c0001876eea","UILogicId":"dl8fht","ota":false,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5acc32067c295c0001876eea"}},{"classid":"02uwxm","product":{"_id":"5ae1481e7ccd1a0001e1f69e","name":"DEEBOT OZMO Slim10 Series","icon":"5b1dddc48bc45700014035a1","UILogicId":"02uwxm","ota":false,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b1dddc48bc45700014035a1"}},{"classid":"y79a7u","product":{"_id":"5b04c0227ccd1a0001e1f6a8","name":"DEEBOT OZMO 900","icon":"5b04c0217ccd1a0001e1f6a7","UILogicId":"y79a7u","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b04c0217ccd1a0001e1f6a7"}},{"classid":"jr3pqa","product":{"_id":"5b43077b8bc457000140363e","name":"DEEBOT 711","icon":"5b5ac4cc8d5a56000111e769","UILogicId":"jr3pqa","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4cc8d5a56000111e769"}},{"classid":"uv242z","product":{"_id":"5b5149b4ac0b87000148c128","name":"DEEBOT 710","icon":"5b5ac4e45f21100001882bb9","UILogicId":"uv242z","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4e45f21100001882bb9"}},{"classid":"ls1ok3","product":{"_id":"5b6561060506b100015c8868","name":"DEEBOT 900 Series","icon":"5ba4a2cb6c2f120001c32839","UILogicId":"ls1ok3","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5ba4a2cb6c2f120001c32839"}}]}')
|
||||
|
||||
d = api.devices()
|
||||
d = api.SetIOTDevices(d, api.getiotProducts())
|
||||
|
||||
assert_equals(r.call_count, 1)
|
||||
assert_equals(len(d), 1)
|
||||
vacuum = d[0]
|
||||
assert_equals(vacuum['did'], device_id)
|
||||
assert_equals(vacuum['class'], device_class)
|
||||
assert_equals(vacuum['iot_product'], True)
|
||||
assert_equals(vacuum['iotmq'], True)
|
||||
|
||||
#Not IOTProduct
|
||||
device_id = 'E0000001234567890123'
|
||||
device_class = '126'
|
||||
device_company = 'eco-legacy'
|
||||
|
||||
r = m.post(compile('user.do'),
|
||||
text='{"todo": "result", "devices": [{"did": "%s", "company": "%s", "class": "%s", "nick": "bob"}], "result": "ok"}' %(device_id, device_company, device_class))
|
||||
r = m.post(compile('pim/product/getProductIotMap'),
|
||||
text='{"code":0,"data":[{"classid":"dl8fht","product":{"_id":"5acb0fa87c295c0001876ecf","name":"DEEBOT 600 Series","icon":"5acc32067c295c0001876eea","UILogicId":"dl8fht","ota":false,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5acc32067c295c0001876eea"}},{"classid":"02uwxm","product":{"_id":"5ae1481e7ccd1a0001e1f69e","name":"DEEBOT OZMO Slim10 Series","icon":"5b1dddc48bc45700014035a1","UILogicId":"02uwxm","ota":false,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b1dddc48bc45700014035a1"}},{"classid":"y79a7u","product":{"_id":"5b04c0227ccd1a0001e1f6a8","name":"DEEBOT OZMO 900","icon":"5b04c0217ccd1a0001e1f6a7","UILogicId":"y79a7u","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b04c0217ccd1a0001e1f6a7"}},{"classid":"jr3pqa","product":{"_id":"5b43077b8bc457000140363e","name":"DEEBOT 711","icon":"5b5ac4cc8d5a56000111e769","UILogicId":"jr3pqa","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4cc8d5a56000111e769"}},{"classid":"uv242z","product":{"_id":"5b5149b4ac0b87000148c128","name":"DEEBOT 710","icon":"5b5ac4e45f21100001882bb9","UILogicId":"uv242z","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4e45f21100001882bb9"}},{"classid":"ls1ok3","product":{"_id":"5b6561060506b100015c8868","name":"DEEBOT 900 Series","icon":"5ba4a2cb6c2f120001c32839","UILogicId":"ls1ok3","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5ba4a2cb6c2f120001c32839"}}]}')
|
||||
|
||||
d = api.devices()
|
||||
d = api.SetIOTDevices(d, api.getiotProducts())
|
||||
|
||||
assert_equals(r.call_count, 1)
|
||||
assert_equals(len(d), 1)
|
||||
vacuum = d[0]
|
||||
assert_equals(vacuum['did'], device_id)
|
||||
assert_equals(vacuum['class'], device_class)
|
||||
assert_equals(vacuum['iot_product'], False)
|
||||
assert_equals(vacuum['iotmq'], False)
|
||||
|
||||
def make_api():
|
||||
with requests_mock.mock() as m:
|
||||
m.get(compile('user/login'),
|
||||
text='{"time": 1511200804243, "data": {"accessToken": "0123456789abcdef0123456789abcdef", "uid": "20170101abcdefabcdefa", "username": null, "email": "username@example.com", "country": "us"}, "code": "0000", "msg": "X"}')
|
||||
m.get(compile('user/getAuthCode'),
|
||||
text='{"time": 1511200804607, "data": {"authCode": "abcdef01234567890abcdef012345678"}, "code": "0000", "msg": "X"}')
|
||||
m.post(compile('user.do'),
|
||||
text='{"todo": "result", "token": "base64base64base64base64base64ba", "result": "ok", "userId": "20170101abcdefabcdefa", "resource": "abcdef12"}')
|
||||
m.post(compile('pim/product/getProductIotMap'),
|
||||
text='{"code":0,"data":[{"classid":"dl8fht","product":{"_id":"5acb0fa87c295c0001876ecf","name":"DEEBOT 600 Series","icon":"5acc32067c295c0001876eea","UILogicId":"dl8fht","ota":false,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5acc32067c295c0001876eea"}},{"classid":"02uwxm","product":{"_id":"5ae1481e7ccd1a0001e1f69e","name":"DEEBOT OZMO Slim10 Series","icon":"5b1dddc48bc45700014035a1","UILogicId":"02uwxm","ota":false,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b1dddc48bc45700014035a1"}},{"classid":"y79a7u","product":{"_id":"5b04c0227ccd1a0001e1f6a8","name":"DEEBOT OZMO 900","icon":"5b04c0217ccd1a0001e1f6a7","UILogicId":"y79a7u","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b04c0217ccd1a0001e1f6a7"}},{"classid":"jr3pqa","product":{"_id":"5b43077b8bc457000140363e","name":"DEEBOT 711","icon":"5b5ac4cc8d5a56000111e769","UILogicId":"jr3pqa","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4cc8d5a56000111e769"}},{"classid":"uv242z","product":{"_id":"5b5149b4ac0b87000148c128","name":"DEEBOT 710","icon":"5b5ac4e45f21100001882bb9","UILogicId":"uv242z","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4e45f21100001882bb9"}},{"classid":"ls1ok3","product":{"_id":"5b6561060506b100015c8868","name":"DEEBOT 900 Series","icon":"5ba4a2cb6c2f120001c32839","UILogicId":"ls1ok3","ota":true,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5ba4a2cb6c2f120001c32839"}}]}')
|
||||
return EcoVacsAPI("long_device_id", "account_id", "password_hash", 'us', 'na')
|
||||
@@ -1,236 +0,0 @@
|
||||
from re import search
|
||||
|
||||
from nose.tools import *
|
||||
|
||||
import requests_mock
|
||||
import requests
|
||||
|
||||
from sucks import *
|
||||
import paho.mqtt
|
||||
|
||||
# There are few tests for the MQTT stuff here because it's relatively complicated to test given
|
||||
# the library's design and its multithreaded nature and lack of explicit testing support.
|
||||
|
||||
def test_subscribe_to_ctls():
|
||||
response = None
|
||||
|
||||
def save_response(value):
|
||||
nonlocal response
|
||||
response = value
|
||||
|
||||
x = make_ecovacs_iotmq()
|
||||
x.subscribe_to_ctls(save_response)
|
||||
|
||||
#Test MQTT ctl
|
||||
mqtt_message = paho.mqtt.client.MQTTMessage
|
||||
mqtt_message.topic = 'iot/atr/CleanReport/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
mqtt_message.payload = b"<ctl ts='1547824270099' td='CleanReport'><clean type='auto' speed='standard' st='h' rsn='a' a='' l='' sts=''/></ctl>"
|
||||
x._handle_ctl_mqtt('','',mqtt_message)
|
||||
assert_dict_equal(response, {'event': 'clean_report', 'ts':'1547824270099','type': 'auto','speed':'standard', 'st':'h','rsn':'a', 'a':'', 'l':'', 'sts':''})
|
||||
|
||||
#Test API ctl
|
||||
api_message = {}
|
||||
api_message['resp'] = '<ctl td="CleanReport"> <clean type="auto" /> </ctl>'
|
||||
x.subscribe_to_ctls(save_response)
|
||||
x._handle_ctl_api("Clean", api_message)
|
||||
assert_dict_equal(response, {'event': 'clean_report', 'type': 'auto'})
|
||||
|
||||
|
||||
def test_is_iotmq():
|
||||
x = make_ecovacs_iotmq()
|
||||
assert_equal(x.vacuum['iotmq'], True)
|
||||
|
||||
def test_wrap_command():
|
||||
x = make_ecovacs_iotmq()
|
||||
|
||||
c = x._wrap_command(Charge(), 'E0000000001234567890')
|
||||
assert_equal(c['cmdName'], Charge().name)
|
||||
assert_equal(c['toId'], 'E0000000001234567890')
|
||||
assert_equal(c['payload'], '<ctl><charge type="go" /></ctl>')
|
||||
|
||||
|
||||
def test_iotapi_response():
|
||||
x = make_ecovacs_iotmq()
|
||||
|
||||
with requests_mock.mock() as m:
|
||||
url = (EcoVacsAPI.PORTAL_URL_FORMAT + "/iot/devmanager.do").format(continent=x.continent)
|
||||
#Test GetCleanState
|
||||
resp = {"ret":"ok","resp":"<ctl ret='ok'><clean type='auto' speed='standard' st='h' t='1159' a='15' s='0' tr=''/></ctl>","id":"Qgxa"}
|
||||
r1 = m.post(url, json=resp)
|
||||
#r1 = m.post(compile('devmanager.do'), json=resp)
|
||||
cmd = VacBotCommand("GetCleanState")
|
||||
c = x._wrap_command(cmd, x.vacuum['did'])
|
||||
rtnval = x._EcoVacsIOTMQ__call_iotdevmanager_api(c)
|
||||
assert_equal(rtnval, {'ret':'ok','resp':"<ctl ret='ok'><clean type='auto' speed='standard' st='h' t='1159' a='15' s='0' tr=''/></ctl>",'id':'Qgxa'})
|
||||
|
||||
#Test Exception ReadTimeout
|
||||
r2 = m.post(url, exc=requests.exceptions.ReadTimeout)
|
||||
#r2 = m.post(compile('iot/devmanager.do'),exc=requests.exceptions.ReadTimeout)
|
||||
cmd = VacBotCommand("GetCleanState")
|
||||
c = x._wrap_command(cmd, x.vacuum['did'])
|
||||
rtnval = x._EcoVacsIOTMQ__call_iotdevmanager_api(c)
|
||||
assert_equal(rtnval, {}) #Right now it sends back a blank object
|
||||
|
||||
#Test Response Fail - Timeout
|
||||
resp = {"ret":"fail","resp": None, "debug":"wait for response timed out" ,"id":"Qgxa"}
|
||||
r2 = m.post(url, json=resp)
|
||||
#r1 = m.post(compile('devmanager.do'), json=resp)
|
||||
cmd = VacBotCommand("TestCommand")
|
||||
c = x._wrap_command(cmd, x.vacuum['did'])
|
||||
rtnval = x._EcoVacsIOTMQ__call_iotdevmanager_api(c)
|
||||
assert_equal(rtnval, {})
|
||||
|
||||
#Test Response Fail - No debug
|
||||
resp = {"ret":"fail","resp": None ,"id":"Qgxa"}
|
||||
r2 = m.post(url, json=resp)
|
||||
#r1 = m.post(compile('devmanager.do'), json=resp)
|
||||
cmd = VacBotCommand("TestCommand")
|
||||
c = x._wrap_command(cmd, x.vacuum['did'])
|
||||
rtnval = x._EcoVacsIOTMQ__call_iotdevmanager_api(c)
|
||||
assert_equal(rtnval, {})
|
||||
|
||||
def test_send_command():
|
||||
from unittest.mock import MagicMock
|
||||
x = make_ecovacs_iotmq()
|
||||
x._handle_ctl_api = MagicMock()
|
||||
EcoVacsIOTMQ._EcoVacsIOTMQ__call_iotdevmanager_api = MagicMock()
|
||||
x.send_command(Clean(iotmq=True), '123')
|
||||
|
||||
def test_send_ping():
|
||||
from unittest.mock import MagicMock
|
||||
x = make_ecovacs_iotmq()
|
||||
EcoVacsIOTMQ._send_simple_command = MagicMock(return_value=MQTTPublish.paho.MQTT_ERR_SUCCESS)
|
||||
assert_true(x.send_ping()) #Test ping response success
|
||||
|
||||
EcoVacsIOTMQ._send_simple_command = MagicMock(return_value=MQTTPublish.paho.MQTT_ERR_NOT_FOUND)
|
||||
assert_false(x.send_ping()) #Test ping response fail
|
||||
|
||||
def test_on_connect_rc_nonzero():
|
||||
x = make_ecovacs_iotmq()
|
||||
assert_raises(RuntimeError, x.on_connect, "client", "userdata", "flags", 1)
|
||||
|
||||
def test_xml_to_dict_mqtt():
|
||||
x = make_ecovacs_iotmq()
|
||||
|
||||
test_topic = 'iot/atr/CleanReport/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547824270099' td='CleanReport'><clean type='auto' speed='standard' st='h' rsn='a' a='' l='' sts=''/></ctl>"),
|
||||
{'event': 'clean_report', 'ts':'1547824270099','type': 'auto','speed':'standard', 'st':'h','rsn':'a', 'a':'', 'l':'', 'sts':''})
|
||||
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547824270099' td='CleanReport'><clean type='auto' speed='strong' st='h' rsn='a' a='' l='' sts=''/></ctl>"),
|
||||
{'event': 'clean_report', 'ts':'1547824270099','type': 'auto','speed':'strong', 'st':'h','rsn':'a', 'a':'', 'l':'', 'sts':''})
|
||||
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547824270099'><clean type='auto' speed='strong' st='h' rsn='a' a='' l='' sts=''/></ctl>"),
|
||||
{'event': 'clean_report', 'ts':'1547824270099','type': 'auto','speed':'strong', 'st':'h','rsn':'a', 'a':'', 'l':'', 'sts':''}) #Test without td
|
||||
|
||||
test_topic = 'iot/atr/BatteryInfo/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547823289924' td='BatteryInfo'><battery power='64'/></ctl>"),
|
||||
{'event': 'battery_info', 'ts':'1547823289924', 'power': '64'})
|
||||
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547823289924'><battery power='64'/></ctl>"),
|
||||
{'event': 'battery_info', 'ts':'1547823289924', 'power': '64'}) #Test without td
|
||||
|
||||
test_topic = 'iot/atr/SleepStatus/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547823129670' td='SleepStatus' st='1'/>"),
|
||||
{'event': 'sleep_status', 'ts':'1547823129670', 'st': '1'})
|
||||
|
||||
test_topic = 'iot/atr/errors/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547822982581' td='errors' old='' new='102'/>"),
|
||||
{'event': 'errors', 'ts':'1547822982581','old':'','new':'102'})
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547822982581' td='errors' old='102' new=''/>"),
|
||||
{'event': 'errors', 'ts':'1547822982581','old':'102','new':''})
|
||||
|
||||
test_topic = 'iot/atr/Pos/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl td='Pos' t='p' p='7,-10' a='-42' valid='0'/>"),
|
||||
{'event': 'pos', 't':'p', 'p':'7,-10', 'a':'-42','valid':'0'})
|
||||
|
||||
test_topic = 'iot/atr/DustCaseST/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547822871328' td='DustCaseST' st='1'/>"),
|
||||
{'event': 'dust_case_s_t', 'ts':'1547822871328','st':'1'})
|
||||
|
||||
test_topic = 'iot/atr/MapSt/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ts='1547823592934' td='MapSt' st='relocGoChgStart' method='' info=''/>"),
|
||||
{'event': 'map_st', 'ts':'1547823592934', 'st':'reloc_go_chg_start', 'method':'', 'info':''})
|
||||
|
||||
test_topic = 'iot/atr/LifeSpan/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, "<ctl ret='ok' type='Brush' left='9876' total='18000'/>"),
|
||||
{'event': 'life_span','ret':'ok', 'type': 'brush', 'left': '9876', 'total': '18000'})
|
||||
|
||||
test_topic = 'iot/atr/CustomCommand/%s/%s/%s/x'.format(x.vacuum['did'], x.vacuum['class'], x.vacuum['resource'])
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_mqtt(test_topic, '<ctl td="CustomCommand"><customtag customvar="customvalue1" /></ctl>'),
|
||||
{'event': 'custom_command', 'customvar': 'customvalue1'})
|
||||
|
||||
|
||||
def test_xml_to_dict_api():
|
||||
x = make_ecovacs_iotmq()
|
||||
message = {}
|
||||
|
||||
cmd = VacBotCommand("Clean")
|
||||
message['resp'] = "<ctl ret='ok'><clean type='auto' speed='standard' st='h' t='1159' a='15' s='0' tr=''/></ctl>"
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_api(cmd,message['resp']),
|
||||
{'event': 'clean_report', 'type': 'auto', 'speed': 'standard', 'st':'h','t':'1159','a':'15','s':'0','tr':''})
|
||||
|
||||
cmd = VacBotCommand("Clean")
|
||||
message['resp'] = "<ctl ret='ok'><clean type='auto' speed='strong' st='h' t='1159' a='15' s='0' tr=''/></ctl>"
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_api(cmd,message['resp']),
|
||||
{'event': 'clean_report', 'type': 'auto', 'speed': 'strong', 'st':'h','t':'1159','a':'15','s':'0','tr':''})
|
||||
|
||||
cmd = VacBotCommand("GetBatteryInfo")
|
||||
message['resp'] = "<ctl ret='ok'><battery power='82'/></ctl>"
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_api(cmd,message['resp']),
|
||||
{'event': 'battery_info', 'power': '82'})
|
||||
|
||||
cmd = VacBotCommand("GetLifeSpan")
|
||||
message['resp'] = "<ctl ret='ok' type='Brush' left='9876' total='18000'/>"
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_api(cmd,message['resp']),
|
||||
{'event': 'life_span','ret':'ok', 'type': 'brush', 'left': '9876', 'total': '18000'})
|
||||
|
||||
cmd = VacBotCommand("Charge")
|
||||
message['resp'] = "<ctl ts='1547823651958' td='ChargeState'><charge type='Going' h='' r='a' s='' g='0'/></ctl>"
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_api(cmd,message['resp']),
|
||||
{'type': 'going', 'h': '', 'r': 'a', 's': '', 'g': '0', 'event': 'charge_state'})
|
||||
|
||||
cmd = VacBotCommand("GetTestCommand")
|
||||
message['resp'] = "<ctl td='TestCommand'><test type='command'/></ctl>"
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_api(cmd,message['resp']),
|
||||
{'type': 'command', 'event': 'test_command'}) #Test action.name.replace Get
|
||||
|
||||
cmd = VacBotCommand("Charge")
|
||||
message['resp'] = "<ctl ret='fail' errno='8'/>"
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict_api(cmd,message['resp']),
|
||||
{'event': 'charge_state','ret':'fail', 'errno': '8'}) #Test fail from charge command
|
||||
|
||||
|
||||
def test_bad_port():
|
||||
bot = {"did": "E0000000001234567890", "class": "126","resource":"test_resource", "nick": "bob", "iotmq": True}
|
||||
mqtt = EcoVacsIOTMQ('20170101abcdefabcdefa', 'ecouser.net', 'abcdef12', 'A1b2C3d4efghijklmNOPQrstuvwxyz12', 'na', bot, server_address='test.com:f123')
|
||||
assert_equal(8883, mqtt.port)
|
||||
|
||||
def test_good_port():
|
||||
bot = {"did": "E0000000001234567890", "class": "126","resource":"test_resource", "nick": "bob", "iotmq": True}
|
||||
mqtt = EcoVacsIOTMQ('20170101abcdefabcdefa', 'ecouser.net', 'abcdef12', 'A1b2C3d4efghijklmNOPQrstuvwxyz12', 'na', bot, server_address='test.com:8000')
|
||||
assert_equal(8000, mqtt.port)
|
||||
|
||||
def make_ecovacs_iotmq(bot=None):
|
||||
if bot is None:
|
||||
bot = {"did": "E0000000001234567890", "class": "126","resource":"test_resource", "nick": "bob", "iotmq": True}
|
||||
return EcoVacsIOTMQ('20170101abcdefabcdefa', 'ecouser.net', 'abcdef12', 'A1b2C3d4efghijklmNOPQrstuvwxyz12', 'na', bot)
|
||||
@@ -1,91 +0,0 @@
|
||||
from re import search
|
||||
|
||||
from nose.tools import *
|
||||
|
||||
from sucks import *
|
||||
|
||||
|
||||
# There are few tests for the XMPP stuff here because it's relatively complicated to test given
|
||||
# the library's design and its multithreaded nature and lack of explicit testing support.
|
||||
|
||||
def test_wrap_command():
|
||||
x = make_ecovacs_xmpp()
|
||||
c = str(x._wrap_command(Clean().to_xml(), 'E0000000001234567890@126.ecorobot.net/atom'))
|
||||
assert_true(search(r'from="20170101abcdefabcdefa@ecouser.net/abcdef12"', c))
|
||||
assert_true(search(r'to="E0000000001234567890@126.ecorobot.net/atom"', c))
|
||||
#Convert to XML to make it easy to see if id was added to ctl
|
||||
xml_test = ET.fromstring(c)
|
||||
ctl = xml_test.getchildren()[0][0]
|
||||
assert_true(ctl.get("id")) #Check that an id was added to ctl
|
||||
|
||||
#Test if customid is added to ctl
|
||||
cwithid = Clean().to_xml()
|
||||
cwithid.attrib["id"] = "12345678" #customid 12345678
|
||||
c = str(x._wrap_command(cwithid, 'E0000000001234567890@126.ecorobot.net/atom'))
|
||||
#Convert to XML to make it easy to see if id was added to ctl
|
||||
xml_test = ET.fromstring(c)
|
||||
ctl = xml_test.getchildren()[0][0]
|
||||
assert_equals(ctl.get("id"), "12345678") #Check that an id was added to ctl
|
||||
|
||||
|
||||
def test_getReqID():
|
||||
x = make_ecovacs_xmpp()
|
||||
rid = x.getReqID("12345678")
|
||||
assert_equals(rid, "12345678") #Check returned ID is the same as provided
|
||||
|
||||
rid2 = x.getReqID()
|
||||
assert_true(len(rid2) >= 8) #Check returned random ID is at least 8 chars
|
||||
|
||||
def test_subscribe_to_ctls():
|
||||
response = None
|
||||
|
||||
def save_response(value):
|
||||
nonlocal response
|
||||
response = value
|
||||
|
||||
x = make_ecovacs_xmpp()
|
||||
|
||||
query = x.make_iq_query()
|
||||
query.set_payload(
|
||||
ET.fromstring('<query xmlns="com:ctl"><ctl td="CleanReport"> <clean type="auto" /> </ctl></query>'))
|
||||
|
||||
x.subscribe_to_ctls(save_response)
|
||||
x._handle_ctl(query)
|
||||
assert_dict_equal(response, {'event': 'clean_report', 'type': 'auto'})
|
||||
|
||||
def test_xml_to_dict():
|
||||
x = make_ecovacs_xmpp()
|
||||
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict(make_ctl('<ctl td="CleanReport"> <clean type="auto" /> </ctl>')),
|
||||
{'event': 'clean_report', 'type': 'auto'})
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict(make_ctl('<ctl td="CleanReport"> <clean type="auto" speed="strong" /> </ctl>')),
|
||||
{'event': 'clean_report', 'type': 'auto', 'speed': 'strong'})
|
||||
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict(make_ctl('<ctl td="BatteryInfo"><battery power="095"/></ctl>')),
|
||||
{'event': 'battery_info', 'power': '095'})
|
||||
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict(make_ctl('# <ctl td="LifeSpan" type="Brush" val="099" total="365"/>')),
|
||||
{'event': 'life_span', 'type': 'brush', 'val': '099', 'total': '365'})
|
||||
|
||||
assert_dict_equal(
|
||||
x._ctl_to_dict(make_ctl('<ctl td="LifeSpan" type="DustCaseHeap" val="-050" total="365"/>')),
|
||||
{'event': 'life_span', 'type': 'dust_case_heap', 'val': '-050', 'total': '365'})
|
||||
|
||||
assert_equals(x._ctl_to_dict(make_ctl('<ctl />')), None)
|
||||
|
||||
|
||||
def make_ecovacs_xmpp(bot=None, server_address=None):
|
||||
if bot is None:
|
||||
bot = {"did": "E0000000001234567890", "class": "126", "nick": "bob", "iotmq": False}
|
||||
return EcoVacsXMPP('20170101abcdefabcdefa', 'ecouser.net', 'abcdef12', 'A1b2C3d4efghijklmNOPQrstuvwxyz12', 'na', bot, server_address=server_address)
|
||||
|
||||
def test_xmpp_customaddress():
|
||||
x = make_ecovacs_xmpp(server_address="test.xmppserver.com")
|
||||
assert_equals(x.server_address, "test.xmppserver.com")
|
||||
|
||||
def make_ctl(string):
|
||||
return ET.fromstring('<query xmlns="com:ctl">' + string + '</query>')[0]
|
||||
@@ -1,398 +0,0 @@
|
||||
from nose.tools import *
|
||||
|
||||
from sucks import *
|
||||
from unittest.mock import Mock, patch
|
||||
from sleekxmppfs.exceptions import XMPPError
|
||||
from paho.mqtt.client import MQTT_ERR_UNKNOWN as MQTTError
|
||||
|
||||
|
||||
def test_handle_clean_report():
|
||||
v = a_vacbot()
|
||||
assert_equals(None, v.clean_status)
|
||||
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'auto', 'speed': 'strong'})
|
||||
assert_equals('auto', v.clean_status)
|
||||
assert_equals('high', v.fan_speed)
|
||||
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'border', 'speed': 'standard'})
|
||||
assert_equals('edge', v.clean_status)
|
||||
assert_equals('normal', v.fan_speed)
|
||||
|
||||
# Missing fan_speed
|
||||
v = a_vacbot()
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'border'})
|
||||
assert_equals('edge', v.clean_status)
|
||||
assert_is_none(v.fan_speed)
|
||||
|
||||
# For states not handled by sucks constants, fall back to just using whatever the vacuum said
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'a_type_not_supported_by_sucks', 'speed': 'a_weird_speed'})
|
||||
assert_equals('a_type_not_supported_by_sucks', v.clean_status)
|
||||
assert_equals('a_weird_speed', v.fan_speed)
|
||||
|
||||
|
||||
|
||||
def test_not_iot_send_command_clean():
|
||||
from unittest.mock import MagicMock
|
||||
v = a_vacbot(iotmq=False)
|
||||
v.xmpp.send_command = MagicMock()
|
||||
v.send_command(VacBotCommand('Clean'))
|
||||
assert v.xmpp.send_command.called #test when iot is False it uses xmpp.send_command
|
||||
|
||||
|
||||
def test_iot_send_command_clean():
|
||||
from unittest.mock import MagicMock
|
||||
v = a_vacbot(iotmq=True)
|
||||
v.iotmq.send_command = MagicMock()
|
||||
v.send_command(VacBotCommand('Clean'))
|
||||
assert v.iotmq.send_command.called #test when iot is True it uses iotmq.send_command
|
||||
|
||||
|
||||
def test_handle_charge_state():
|
||||
v = a_vacbot()
|
||||
assert_equals(None, v.clean_status)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'going'})
|
||||
assert_equals('returning', v.charge_status)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'slot_charging'})
|
||||
assert_equals('charging', v.charge_status)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'idle'})
|
||||
assert_equals('idle', v.charge_status)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'ret': 'fail', 'errno': '9'}) #Seen in IOT - "but on charger, but turned off"
|
||||
assert_equals('idle', v.charge_status)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'ret': 'fail', 'errno': '8'}) #Seen in IOT - could be "already charging"
|
||||
assert_equals('charging', v.charge_status)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'ret': 'fail', 'errno': '5'}) #Seen in IOT - could be "busy with another command"
|
||||
assert_equals('idle', v.charge_status)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'ret': 'fail', 'errno': '3'}) #Seen in IOT - could be "Bot in stuck state, example dust bin out"
|
||||
assert_equals('idle', v.charge_status)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'a_type_not_supported_by_sucks'})
|
||||
assert_equals('a_type_not_supported_by_sucks', v.charge_status)
|
||||
|
||||
|
||||
def test_vacuum_states():
|
||||
# Vacuum state usually mirrors the latest charge or clean report, but there are some edge cases where it doesn't
|
||||
# work that way. This test ensures the edge cases are handled correctly.
|
||||
v = a_vacbot()
|
||||
assert_equals(None, v.vacuum_status)
|
||||
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'auto', 'speed': 'strong'})
|
||||
assert_equals('auto', v.vacuum_status)
|
||||
|
||||
# Ignore the "idle" charge state in most cases, as it can be reported during a cleaning (such as during initialization)
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'auto'})
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'idle'})
|
||||
assert_equals('auto', v.vacuum_status)
|
||||
|
||||
# However, we do honor the idle state when our current state is charging, as that can happen in some certain combination of events
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'slot_charging'})
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'idle'})
|
||||
assert_equals('idle', v.vacuum_status)
|
||||
|
||||
def test_handle_battery_info():
|
||||
v = a_vacbot()
|
||||
assert_equals(None, v.battery_status)
|
||||
|
||||
v._handle_ctl({'event': 'battery_info', 'power': '100'})
|
||||
assert_equals(1.0, v.battery_status)
|
||||
|
||||
v._handle_ctl({'event': 'battery_info', 'power': '095'})
|
||||
assert_equals(0.95, v.battery_status)
|
||||
|
||||
v._handle_ctl({'event': 'battery_info', 'power': '000'})
|
||||
assert_equals(0.0, v.battery_status)
|
||||
|
||||
|
||||
def test_lifespan_reports():
|
||||
v = a_vacbot()
|
||||
assert_equals({}, v.components)
|
||||
|
||||
# Note: The "total" values don't seem to have any meaning
|
||||
|
||||
v._handle_ctl({'event': 'life_span', 'type': 'side_brush', 'total': '100', 'val': '50'})
|
||||
assert_equals({'side_brush': 0.5}, v.components)
|
||||
|
||||
v._handle_ctl({'event': 'life_span', 'type': 'brush', 'total': '200', 'val': '1'})
|
||||
assert_equals({'side_brush': 0.5, 'main_brush': 0.01}, v.components)
|
||||
|
||||
v._handle_ctl({'event': 'life_span', 'type': 'side_brush', 'total': '100', 'val': '0'})
|
||||
assert_equals({'side_brush': 0, 'main_brush': 0.01}, v.components)
|
||||
|
||||
v._handle_ctl({'event': 'life_span', 'type': 'a_weird_component', 'total': '100', 'val': '87'})
|
||||
assert_equals({'side_brush': 0, 'main_brush': 0.01, 'a_weird_component': 0.87}, v.components)
|
||||
|
||||
v._handle_ctl({'event': 'life_span', 'type': 'side_brush', 'total': '100', 'left': '120'})
|
||||
assert_equals(2.0, v.components['side_brush']) #test left (2 hours / 120 mins) instead of val
|
||||
|
||||
|
||||
def test_is_cleaning():
|
||||
v = a_vacbot()
|
||||
|
||||
assert_false(v.is_cleaning)
|
||||
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'auto', 'speed': 'strong'})
|
||||
assert_true(v.is_cleaning)
|
||||
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'stop'})
|
||||
assert_false(v.is_cleaning)
|
||||
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'edge', 'speed': 'normal'})
|
||||
assert_true(v.is_cleaning)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'going'})
|
||||
assert_false(v.is_cleaning)
|
||||
|
||||
v = a_vacbot(iotmq=True)
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'spot_area', 'speed':'normal','st':'h'})
|
||||
assert_false(v.is_cleaning) #test iot and state paused
|
||||
|
||||
v = a_vacbot(iotmq=True)
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'spot_area', 'speed':'normal','st':'r'})
|
||||
assert_true(v.is_cleaning) #test iot and state running
|
||||
|
||||
def test_is_charging():
|
||||
v = a_vacbot()
|
||||
|
||||
assert_false(v.is_charging)
|
||||
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'auto', 'speed': 'strong'})
|
||||
assert_false(v.is_charging)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'going'})
|
||||
assert_false(v.is_charging)
|
||||
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'slot_charging'})
|
||||
assert_true(v.is_charging)
|
||||
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'edge', 'speed': 'normal'})
|
||||
assert_false(v.is_charging)
|
||||
|
||||
|
||||
|
||||
|
||||
def test_send_ping_no_monitor():
|
||||
#Test XMPP Ping
|
||||
v = a_vacbot()
|
||||
mock = v.xmpp.send_ping = Mock()
|
||||
v.send_ping()
|
||||
|
||||
# On four failed pings, vacuum state gets set to 'offline'
|
||||
mock.side_effect = XMPPError()
|
||||
v.send_ping()
|
||||
v.send_ping()
|
||||
v.send_ping()
|
||||
assert_equals(None, v.vacuum_status)
|
||||
v.send_ping()
|
||||
assert_equals('offline', v.vacuum_status)
|
||||
|
||||
# On a successful ping after the offline state, state gets reset to None, indicating that it is unknown
|
||||
mock.side_effect = None
|
||||
v.send_ping()
|
||||
assert_equals(None, v.vacuum_status)
|
||||
|
||||
#Test MQTT Ping
|
||||
v = a_vacbot(iotmq=True)
|
||||
mock = v.iotmq.send_ping = Mock()
|
||||
v.send_ping()
|
||||
|
||||
# On four failed pings, vacuum state gets set to 'offline'
|
||||
mock.return_value = False
|
||||
v.send_ping()
|
||||
v.send_ping()
|
||||
v.send_ping()
|
||||
assert_equals(None, v.vacuum_status)
|
||||
v.send_ping()
|
||||
assert_equals('offline', v.vacuum_status)
|
||||
|
||||
# On a successful ping after the offline state, state gets reset to None, indicating that it is unknown
|
||||
mock.return_value = True
|
||||
v.send_ping()
|
||||
assert_equals(None, v.vacuum_status)
|
||||
|
||||
|
||||
def test_send_ping_with_monitor():
|
||||
#Test XMPP Ping
|
||||
v = a_vacbot(monitor=True)
|
||||
|
||||
ping_mock = v.xmpp.send_ping = Mock()
|
||||
request_statuses_mock = v.request_all_statuses = Mock()
|
||||
|
||||
# First ping should try to fetch statuses
|
||||
v.send_ping()
|
||||
assert_equals(1, request_statuses_mock.call_count)
|
||||
|
||||
# Nothing blowing up is success
|
||||
|
||||
# On four failed pings, vacuum state gets set to 'offline'
|
||||
ping_mock.side_effect = XMPPError()
|
||||
v.send_ping()
|
||||
v.send_ping()
|
||||
v.send_ping()
|
||||
assert_equals(None, v.vacuum_status)
|
||||
v.send_ping()
|
||||
assert_equals('offline', v.vacuum_status)
|
||||
|
||||
# On a successful ping after the offline state, a request for initial statuses is made
|
||||
ping_mock.side_effect = None
|
||||
request_statuses_mock.reset_mock()
|
||||
v.send_ping()
|
||||
assert_equals(1, request_statuses_mock.call_count)
|
||||
|
||||
#Test MQTT Ping
|
||||
v = a_vacbot(iotmq=True, monitor=True)
|
||||
|
||||
ping_mock = v.iotmq.send_ping = Mock()
|
||||
request_statuses_mock = v.request_all_statuses = Mock()
|
||||
|
||||
# First ping should try to fetch statuses
|
||||
v.send_ping()
|
||||
assert_equals(1, request_statuses_mock.call_count)
|
||||
|
||||
# Nothing blowing up is success
|
||||
|
||||
# On four failed pings, vacuum state gets set to 'offline'
|
||||
ping_mock.return_value = False
|
||||
v.send_ping()
|
||||
v.send_ping()
|
||||
v.send_ping()
|
||||
assert_equals(None, v.vacuum_status)
|
||||
v.send_ping()
|
||||
assert_equals('offline', v.vacuum_status)
|
||||
|
||||
# On a successful ping after the offline state, a request for initial statuses is made
|
||||
ping_mock.return_value = True
|
||||
request_statuses_mock.reset_mock()
|
||||
v.send_ping()
|
||||
assert_equals(1, request_statuses_mock.call_count)
|
||||
|
||||
|
||||
def test_status_event_subscription():
|
||||
v = a_vacbot()
|
||||
|
||||
mock = Mock()
|
||||
v.statusEvents.subscribe(mock)
|
||||
v._handle_ctl({'event': 'clean_report', 'type': 'auto', 'speed': 'strong'})
|
||||
mock.assert_called_once_with('auto')
|
||||
|
||||
mock = Mock()
|
||||
v.statusEvents.subscribe(mock)
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'going'})
|
||||
mock.assert_called_once_with('returning')
|
||||
|
||||
# Test unsubscribe
|
||||
mock = Mock()
|
||||
subscription = v.statusEvents.subscribe(mock)
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'going'})
|
||||
assert_equals(1, mock.call_count)
|
||||
subscription.unsubscribe()
|
||||
v._handle_ctl({'event': 'charge_state', 'type': 'slot_charging'})
|
||||
assert_equals(1, mock.call_count)
|
||||
|
||||
def test_battery_event_subscription():
|
||||
v = a_vacbot()
|
||||
|
||||
mock = Mock()
|
||||
v.batteryEvents.subscribe(mock)
|
||||
v._handle_ctl({'event': 'battery_info', 'power': '095'})
|
||||
mock.assert_called_once_with(0.95)
|
||||
|
||||
# Test unsubscribe
|
||||
mock = Mock()
|
||||
subscription = v.batteryEvents.subscribe(mock)
|
||||
v._handle_ctl({'event': 'battery_info', 'power': '095'})
|
||||
assert_equals(1, mock.call_count)
|
||||
subscription.unsubscribe()
|
||||
v._handle_ctl({'event': 'battery_info', 'power': '090'})
|
||||
assert_equals(1, mock.call_count)
|
||||
|
||||
def test_lifespan_event_subscription():
|
||||
v = a_vacbot()
|
||||
|
||||
mock = Mock()
|
||||
v.lifespanEvents.subscribe(mock)
|
||||
v._handle_ctl({'event': 'life_span', 'type': 'side_brush', 'total': '100', 'val': '50'})
|
||||
mock.assert_called_once_with({'type': 'side_brush', 'lifespan': 0.5})
|
||||
|
||||
# Test unsubscribe
|
||||
mock = Mock()
|
||||
subscription = v.lifespanEvents.subscribe(mock)
|
||||
v._handle_ctl({'event': 'life_span', 'type': 'side_brush', 'total': '100', 'val': '50'})
|
||||
assert_equals(1, mock.call_count)
|
||||
subscription.unsubscribe()
|
||||
v._handle_ctl({'event': 'life_span', 'type': 'side_brush', 'total': '100', 'val': '25'})
|
||||
assert_equals(1, mock.call_count)
|
||||
|
||||
def test_error_event_subscription():
|
||||
v = a_vacbot()
|
||||
|
||||
mock = Mock()
|
||||
v.errorEvents.subscribe(mock)
|
||||
v._handle_ctl({'event': 'error', 'error': 'an_error_name'})
|
||||
v._handle_ctl({'event': 'error', 'errs': 'an_error_name2'}) #added for testing errs
|
||||
assert_equals(2, mock.call_count)
|
||||
#mock.assert_called_once_with('an_error_name')
|
||||
|
||||
|
||||
# Test unsubscribe
|
||||
mock = Mock()
|
||||
subscription = v.errorEvents.subscribe(mock)
|
||||
v._handle_ctl({'event': 'error', 'error': 'an_error_name'})
|
||||
assert_equals(1, mock.call_count)
|
||||
subscription.unsubscribe()
|
||||
v._handle_ctl({'event': 'error', 'error': 'an_error_name'})
|
||||
assert_equals(1, mock.call_count)
|
||||
|
||||
def test_handle_unknown_ctl():
|
||||
v = a_vacbot()
|
||||
v._handle_ctl({'event': 'weird_and_unknown_event', 'type': 'pretty_weird'})
|
||||
# as long as it doesn't blow up, that's fine
|
||||
|
||||
|
||||
# as-yet unhandled messages:
|
||||
#
|
||||
# <ctl td="LifeSpan" type="Brush" val="099" total="365"/>
|
||||
# <ctl td="LifeSpan" type="DustCaseHeap" val="098" total="365"/>
|
||||
# <ctl td="LifeSpan" type="SideBrush" val="098" total="365"/>
|
||||
# <ctl td="Sched2"/>
|
||||
# <ctl td="Sched2" id="30800321"/>
|
||||
#
|
||||
# plus errors!
|
||||
|
||||
def test_bot_address():
|
||||
v = a_vacbot(bot={"did": "E0000000001234567890", "class": "126", "nick": "bob", "iotmq":False})
|
||||
assert_equals('E0000000001234567890@126.ecorobot.net/atom', v._vacuum_address())
|
||||
|
||||
|
||||
def test_bot_address_iot():
|
||||
v = a_vacbot(bot={"did": "E0000000001234567890", "class": "126", "nick": "bob", "iotmq":True})
|
||||
assert_equals('E0000000001234567890', v._vacuum_address())
|
||||
|
||||
|
||||
def test_model_variation():
|
||||
v = a_vacbot(bot={"did": "E0000000001234567890", "class": "141", "nick": "bob","iotmq":False})
|
||||
assert_equals('E0000000001234567890@141.ecorobot.net/atom', v._vacuum_address())
|
||||
|
||||
|
||||
|
||||
def a_vacbot(bot=None, iotmq=False, monitor=False):
|
||||
if bot is None:
|
||||
bot = {"did": "E0000000001234567890", "class": "126", "nick": "bob", "iotmq": iotmq}
|
||||
return VacBot('20170101abcdefabcdefa', 'ecouser.net', 'abcdef12', 'A1b2C3d4efghijklmNOPQrstuvwxyz12',
|
||||
bot, 'na', monitor=monitor)
|
||||
|
||||
def test_str_to_bool():
|
||||
assert_raises(ValueError, str_to_bool_or_cert, None) #Value error if str_to_bool can't convert
|
||||
assert_equals(True, str_to_bool_or_cert("True"))
|
||||
assert_equals(False, str_to_bool_or_cert("False"))
|
||||
assert_equals(
|
||||
os.path.abspath(os.path.join(".", "tests", "test_vacbot.py")),
|
||||
str_to_bool_or_cert(os.path.abspath(os.path.join(".","tests","test_vacbot.py")))
|
||||
)
|
||||
assert_raises(ValueError, str_to_bool_or_cert ,(os.path.abspath(os.path.join(".","tests"))))
|
||||
|
||||
Reference in New Issue
Block a user