diff --git a/CHANGELOG.md b/CHANGELOG.md index 01e353f..ae6a430 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 0.4.16 + +- Optional local control: `EphEmber(..., local_broker={...})` sends commands + and receives live updates through an MQTT broker on your network that the + gateway connects to, instead of the Ember cloud. The cloud is still used to + log in and list the zones. See README and docs/local-broker.md. + ## 0.4.15 - A failed user lookup (`user/selectUser`) after a successful login now diff --git a/README.md b/README.md index 925971a..df1cda4 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,26 @@ zones and calls back for each report (from a background thread): >>> e.start_listening(changed) >>> e.stop_listening() +Local control (optional) +------------------------ + +The gateway talks to the Ember cloud over plain MQTT, to +`eu-base-mqtt.topband-cloud.com` on port 11883. If you point that name at an +MQTT broker on your own network (for the gateway only), commands and live +updates can go through that broker instead of the cloud; a change then reaches +the gateway in well under a second: + + >>> e = EphEmber('my@username.com', 'mypassword', local_broker={ + ... 'host': '192.168.1.20', # your broker + ... 'port': 11883, # default + ... 'username': 'me', 'password': 'secret', # your broker's login + ... }) + +The cloud is still used to log in and to list the homes and zones. Setting up +the broker and the redirect is up to you, and the Ember app only keeps working +if the broker also bridges to the cloud. See [local broker](docs/local-broker.md). +This is unofficial: EPH could change how the gateway connects at any time. + API --- diff --git a/docs/local-broker.md b/docs/local-broker.md new file mode 100644 index 0000000..c828857 --- /dev/null +++ b/docs/local-broker.md @@ -0,0 +1,102 @@ +# Local broker + +The Ember gateway (EMBER-PS) keeps an MQTT connection to the EPH cloud. It is +plain MQTT 3.1.1, not TLS, to `eu-base-mqtt.topband-cloud.com` port **11883**. +The Ember app and this library use the same host name on port 18883 (TLS). + +The cloud is just a broker. The gateway publishes its reports and subscribes to +its commands, all under `//`: + +| Direction | Topics | +|---|---| +| gateway → | `upload/pointdata`, `upload/programme`, `upload/thermostat`, `upload/zoneType`, `upload/commdata`, `gettime` | +| → gateway | `download/pointdata` (commands), `download/programme`, `download/reply`, `download/update`, `downtime` | + +`productId` and `uid` are in every zone returned by `get_zones()`. + +If the gateway connects to a broker on your network instead, this library can +publish the same commands there (`local_broker=...`) and get the reports from +there. + +## 1. Run a broker on port 11883 + +Any MQTT broker works. Mosquitto example, **local only** (the Ember app stops +working while the gateway is redirected): + +``` +listener 11883 +# the gateway logs in with its own username/password; accept it +allow_anonymous true +``` + +Keep port 11883 reachable from your LAN only. To limit what other clients can +do, add a `password_file` and `acl_file` (then the gateway's own login has to be +in the password file, see below). + +## 2. Keep the Ember app working (optional): bridge to the cloud + +To keep the app working, the broker has to forward the gateway's traffic to the +cloud **as the gateway**, using the gateway's own MQTT login: + +- client id: the gateway's `uid` +- username: `device//` (the WiFi ID is on the gateway's label) +- password: the one the gateway sends. The only way to find it is to log the + gateway's MQTT CONNECT packet once, while it is redirected to you. + +``` +connection eph-cloud +address eu-base-mqtt.topband-cloud.com:11883 +bridge_protocol_version mqttv311 +try_private false +notifications false +cleansession true +remote_clientid +remote_username device// +remote_password +topic //upload/# out 1 +topic //gettime out 0 +topic //downtime in 0 +topic //download/pointdata in 1 +topic //download/programme in 1 +topic //download/reply in 1 +topic //download/update in 1 +``` + +Map only these topics. The cloud refuses wildcards such as `#`. + +**Only start the bridge once the gateway is redirected.** The bridge uses the +gateway's client id, so while the real gateway is still connected to the cloud +the two keep disconnecting each other. + +## 3. Redirect the gateway + +Make `eu-base-mqtt.topband-cloud.com` resolve to your broker **for the gateway +only**. Redirecting it for the whole network would also send the Ember app to +your broker, on port 18883. For example, with AdGuard Home as your DHCP and DNS +server, give the gateway a fixed address and add a custom filtering rule: + +``` +||eu-base-mqtt.topband-cloud.com^$dnsrewrite=,client= +``` + +The gateway has to get its DNS server from your DHCP server, so renew its lease +or power-cycle it. After a broker restart it can take a few minutes to +reconnect. + +## 4. Use it + +```python +from pyephember2.pyephember2 import EphEmber + +e = EphEmber(user, password, local_broker={ + "host": "192.168.1.20", "port": 11883, + "username": "me", "password": "secret", # omit if anonymous +}) +``` + +Commands (`set_zone_target_temperature`, `set_zone_mode`, ...) and +`start_listening` then use the local broker. Logging in and reading the zones +still use the cloud. + +To undo all this, remove the DNS rule and power-cycle the gateway. It goes back +to the cloud. diff --git a/pyephember2/pyephember2.py b/pyephember2/pyephember2.py index b9a3567..7ca0cf0 100644 --- a/pyephember2/pyephember2.py +++ b/pyephember2/pyephember2.py @@ -699,21 +699,35 @@ def start(self, callbacks=None, loop_start=False, connect_async=False): With connect_async=True the connection is made by the network loop, which keeps retrying until the broker can be reached. """ - credentials = self.parent.messenging_credentials() - self.user_id = credentials['user_id'] - self.client_id = '{}_{}'.format( - credentials['user_id'], str(int(1000*time.time())) - ) - token = credentials['token'] + local = self.parent.local_broker + if local: + # The gateway's own broker on the LAN: fixed login, no cloud + self.user_id = self.parent.cached_user_id() + self.client_id = 'pyephember2_{}'.format(int(1000*time.time())) + host, port = local['host'], local['port'] + else: + credentials = self.parent.messenging_credentials() + self.user_id = credentials['user_id'] + self.client_id = '{}_{}'.format( + credentials['user_id'], str(int(1000*time.time())) + ) + host, port = self.api_url, self.api_port mclient = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, self.client_id) - mclient.tls_set() self.client = mclient self._connect_result = None self._user_on_connect = None - user_name = "app/{}".format(token) - mclient.username_pw_set(user_name, token) + if local: + if local.get('tls'): + mclient.tls_set() + if local.get('username') is not None: + mclient.username_pw_set(local['username'], + local.get('password')) + else: + mclient.tls_set() + token = credentials['token'] + mclient.username_pw_set("app/{}".format(token), token) if callbacks is not None: callbacks = dict(callbacks) @@ -724,9 +738,9 @@ def start(self, callbacks=None, loop_start=False, connect_async=False): try: if connect_async: - mclient.connect_async(self.api_url, self.api_port) + mclient.connect_async(host, port) else: - mclient.connect(self.api_url, self.api_port) + mclient.connect(host, port) except (OSError, ValueError) as err: raise EphEmberError( "Cannot connect to Ember MQTT broker: {}".format(err) @@ -1028,6 +1042,18 @@ def _set_zone_mode(self, zone, mode_num, index): # Public interface + def cached_user_id(self): + """ + The Ember user ID for MQTT messages, without failing: a local broker + must keep working while the cloud is down. + """ + try: + if self._do_auth(): + return self._get_user_id() + except (EphEmberError, RuntimeError, OSError) as err: + _LOGGER.debug("Cannot get Ember user ID: %s", err) + return self._user['user_id'] + def messenging_credentials(self): """ Credentials required by EphMessenger @@ -1396,6 +1422,8 @@ def on_disconnect(client, userdata, flags, reason_code, state['connected'] = False _LOGGER.debug("Ember live updates disconnected: %s", reason_code) + if self.local_broker: + return # fixed login; paho reconnects by itself # the token may have expired; reconnect with a fresh one try: credentials = self.messenging_credentials() @@ -1468,10 +1496,17 @@ def reset_login(self): self._login_data = None # Ctor - def __init__(self, username, password, cache_home=False, tz=None): + def __init__(self, username, password, cache_home=False, tz=None, + local_broker=None): """ Performs login and save session cookie. + local_broker sends commands and receives live updates through an + MQTT broker on the local network that the gateway is connected to, + instead of the Ember cloud: a dict with 'host' and optionally + 'port' (default 11883), 'username', 'password' and 'tls'. The + cloud is still used to log in and to list the homes and zones. + tz is the home's time zone (a datetime.tzinfo such as zoneinfo.ZoneInfo("Europe/Dublin")), used to work out which schedule slot is running. If None, this computer's local time @@ -1506,6 +1541,11 @@ def __init__(self, username, password, cache_home=False, tz=None): self.http_api_base = 'https://eu-https.topband-cloud.com/ember-back/' + self.local_broker = None + if local_broker: + self.local_broker = dict(local_broker) + self.local_broker.setdefault('port', 11883) + self.messenger = EphMessenger(self) if not self._login(): diff --git a/setup.py b/setup.py index 3cf4820..83d6daf 100755 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ setup( name='pyephember2', - version='0.4.15', + version='0.4.16', description='Python library to work with ember from EPH Controls', keywords='ephember', author='Robert Young', diff --git a/tests/test_pyephember2.py b/tests/test_pyephember2.py index 97b434c..f30ffa8 100644 --- a/tests/test_pyephember2.py +++ b/tests/test_pyephember2.py @@ -397,16 +397,16 @@ def __init__(self, *args, refuse=False, **kwargs): FakeMqttClient.instances.append(self) def tls_set(self): - pass + self.tls = True def username_pw_set(self, user, password): self.credentials = (user, password) def connect(self, host, port): - pass + self.target = (host, port) def connect_async(self, host, port): - pass + self.target = (host, port) def reconnect_delay_set(self, min_delay, max_delay): self.reconnect_delay = (min_delay, max_delay) @@ -604,6 +604,69 @@ def test_stop_listening(monkeypatch): client.on_disconnect(client, None, None, FakeReason(False), None) +# --- local broker ------------------------------------------------------------- + +LOCAL = {"host": "192.168.1.20", "username": "me", "password": "pw"} + + +def test_local_broker_command(monkeypatch): + ember = make_ember(monkeypatch, load_fixture()) + monkeypatch.setattr(ember, "_get_user_id", lambda force=False: "42") + ember.local_broker = dict(LOCAL, port=11883) + FakeMqttClient.instances.clear() + monkeypatch.setattr(pe.mqtt, "Client", FakeMqttClient) + monkeypatch.setattr(ember, "messenging_credentials", + lambda: pytest.fail("no cloud MQTT login")) + zone = zones_by_name(ember)["Radiators"] + + assert ember.set_zone_target_temperature(zone["zoneid"], 21) + client = FakeMqttClient.instances[-1] + assert client.target == ("192.168.1.20", 11883) + assert client.credentials == ("me", "pw") + assert not getattr(client, "tls", False) + topic, msg, qos = client.published[0] + assert topic.endswith("/download/pointdata") + assert msg["common"]["userId"] == "42" + + +def test_local_broker_default_port(monkeypatch): + monkeypatch.setattr(EphEmber, "_login", lambda self: True) + ember = EphEmber("u", "p", local_broker={"host": "h"}) + assert ember.local_broker == {"host": "h", "port": 11883} + + +def test_local_broker_works_while_cloud_is_down(monkeypatch): + ember = make_ember(monkeypatch, load_fixture()) + ember._user["user_id"] = "42" + ember.local_broker = dict(LOCAL, port=11883) + + def cloud_down(*args, **kwargs): + raise requests.ConnectionError("cloud down") + + monkeypatch.setattr(ember, "_do_auth", cloud_down) + assert ember.cached_user_id() == "42" + + +def test_local_broker_listener_does_not_refresh_token(monkeypatch): + data = load_fixture() + for number, zone in enumerate(data["data"]): + zone["mac"] = "mac{}".format(number) + zone["productId"], zone["uid"] = "P", "U" + ember = make_ember(monkeypatch, data) + monkeypatch.setattr(ember, "_get_user_id", lambda force=False: "42") + ember.local_broker = dict(LOCAL, port=11883) + FakeMqttClient.instances.clear() + monkeypatch.setattr(pe.mqtt, "Client", FakeMqttClient) + ember.start_listening(lambda zone: None) + client = FakeMqttClient.instances[-1] + assert client.target == ("192.168.1.20", 11883) + assert client.subscribed == [("P/U/upload/pointdata", 1)] + monkeypatch.setattr(ember, "messenging_credentials", + lambda: pytest.fail("should not refresh")) + client.on_disconnect(client, None, None, FakeReason(True), None) + assert client.credentials == ("me", "pw") + + def test_user_id_failure_is_a_connection_error(monkeypatch): """A failed user lookup after a good login isn't a rejected password.""" ember = make_ember(monkeypatch, load_fixture())