diff --git a/CHANGELOG.md b/CHANGELOG.md index f917102f7..9360f38bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,50 @@ # Changelog +## 0.9.0 - API change for stick + +- Improvement: Debounce relay state +- Improvement: Prioritize request so requests like switching a relay get send out before power measurement requests. +- Improvement: Dynamically change the refresh interval based on the actual discovered nodes with power measurement capabilities +- Added: New property attributes for USB-stick. + The old methods are still available but will give a deprecate warning + - Stick + - `devices` (dict) - All discovered and supported plugwise devices with the MAC address as their key + - `joined_nodes` (integer) - Total number of registered nodes at Plugwise Circle+ + - `mac` (string) - The MAC address of the USB-Stick + - `network_state` (boolean) - The state (on-line/off-line) of the Plugwise network. + - `network_id` (integer) - The ID of the Plugwise network. + - `port` (string) - The port connection string + - All plugwise devices + - `available` (boolean) - The current network availability state of the device + - `battery_powered` (boolean) - Indicates if device is battery powered + - `features` (tuple) - List of supported attribute IDs + - `firmware_version` (string) - Firmware version device is running + - `hardware_model` (string) - Hardware model name + - `hardware_version` (string) - Hardware version of device + - `last_update` (datetime) - Date/time stamp of last received update from device + - `mac` (string) - MAC address of device + - `measures_power` (boolean) - Indicates if device supports power measurement + - `name` (string) - Name of device based om hardware model and MAC address + - `ping` (integer) - Network roundtrip time in milliseconds + - `rssi_in` (integer) - Inbound RSSI level in DBm + - `rssi_out` (integer) - Outbound RSSI level based on the received inbound RSSI level of the neighbor node in DBm + - Scan devices + - `motion` (boolean) - Current detection state of motion. + - Sense devices + - `humidity` (integer) - Last reported humidity value. + - `temperature` (integer) - Last reported temperature value. + - Circle/Circle+/Stealth devices + - `current_power_usage` (float) - Current power usage (Watts) during the last second + - `current_power_usage_8_sec` (float) - Current power usage (Watts) during the last 8 seconds + - `power_consumption_current_hour` (float) - Total power consumption (kWh) this running hour + - `power_consumption_previous_hour` (float) - Total power consumption (kWh) during the previous hour + - `power_consumption_today` (float) - Total power consumption (kWh) of today + - `power_consumption_yesterday` (float) - Total power consumption (kWh) during yesterday + - `power_production_current_hour` (float) - Total power production (kWh) this hour + - `relay_state` (boolean) - State of the output power relay. Setting this property will operate the relay + - Switch devices + - `switch` (boolean) - Last reported state of switch + ## 0.8.6 - Code quality improvements for stick - Bug-fix: Power history was not reported (0 value) during last week of the month @@ -17,9 +62,10 @@ - Improvement: Resolves all flake8 comments ## 0.8.5 - Fix sensor scaling - - Fix for via HA Core issue #44349 - - Fix other value scaling bugs - - Remove aiohttp-workaround - issue solved in aiohttp 3.7.1 + +- Fix for via HA Core issue #44349 +- Fix other value scaling bugs +- Remove aiohttp-workaround - issue solved in aiohttp 3.7.1 (## 0.8.4 - Not released: Fix "Gas Consumed Interval stays 0" ) diff --git a/plugwise/__init__.py b/plugwise/__init__.py index 6b5b41b0e..ed816abf9 100644 --- a/plugwise/__init__.py +++ b/plugwise/__init__.py @@ -1,6 +1,6 @@ """Plugwise module.""" -__version__ = "0.8.6" +__version__ = "0.9.0" from plugwise.smile import Smile from plugwise.stick import stick diff --git a/plugwise/constants.py b/plugwise/constants.py index 5ac609f0b..fd066a136 100644 --- a/plugwise/constants.py +++ b/plugwise/constants.py @@ -136,6 +136,11 @@ # Default sleep between sending messages SLEEP_TIME = 150 / 1000 +# Message priority levels +PRIORITY_HIGH = 1 +PRIORITY_LOW = 3 +PRIORITY_MEDIUM = 2 + # Max seconds the internal clock of plugwise nodes # are allowed to drift in seconds MAX_TIME_DRIFT = 30 @@ -220,120 +225,112 @@ CB_NEW_NODE = "NEW_NODE" CB_JOIN_REQUEST = "JOIN_REQUEST" -# Sensors -SENSOR_AVAILABLE = { +# Stick device features +FEATURE_AVAILABLE = { "id": "available", "name": "Available", - "state": "get_available", + "state": "available", "unit": "state", } -SENSOR_HUMIDITY = { +FEATURE_HUMIDITY = { "id": "humidity", "name": "Humidity", - "state": "get_humidity", + "state": "humidity", "unit": "%", } -SENSOR_MOTION = { +FEATURE_MOTION = { "id": "motion", "name": "Motion", - "state": "get_motion", + "state": "motion", "unit": "state", } -SENSOR_PING = { +FEATURE_PING = { "id": "ping", "name": "Ping roundtrip", - "state": "get_ping", + "state": "ping", "unit": TIME_MILLISECONDS, } -SENSOR_POWER_USE = { +FEATURE_POWER_USE = { "id": "power_1s", "name": "Power usage", - "state": "get_power_usage", + "state": "current_power_usage", "unit": POWER_WATT, } -SENSOR_POWER_USE_LAST_8_SEC = { +FEATURE_POWER_USE_LAST_8_SEC = { "id": "power_8s", "name": "Power usage 8 seconds", - "state": "get_power_usage_8_sec", + "state": "current_power_usage_8_sec", "unit": POWER_WATT, } -SENSOR_POWER_CONSUMPTION_CURRENT_HOUR = { +FEATURE_POWER_CONSUMPTION_CURRENT_HOUR = { "id": "power_con_cur_hour", "name": "Power consumption current hour", - "state": "get_power_consumption_current_hour", + "state": "power_consumption_current_hour", "unit": ENERGY_KILO_WATT_HOUR, } -SENSOR_POWER_CONSUMPTION_PREVIOUS_HOUR = { +FEATURE_POWER_CONSUMPTION_PREVIOUS_HOUR = { "id": "power_con_prev_hour", "name": "Power consumption previous hour", - "state": "get_power_consumption_previous_hour", + "state": "power_consumption_previous_hour", "unit": ENERGY_KILO_WATT_HOUR, } -SENSOR_POWER_CONSUMPTION_TODAY = { +FEATURE_POWER_CONSUMPTION_TODAY = { "id": "power_con_today", "name": "Power consumption today", - "state": "get_power_consumption_today", + "state": "power_consumption_today", "unit": ENERGY_KILO_WATT_HOUR, } -SENSOR_POWER_CONSUMPTION_YESTERDAY = { +FEATURE_POWER_CONSUMPTION_YESTERDAY = { "id": "power_con_yesterday", "name": "Power consumption yesterday", - "state": "get_power_consumption_yesterday", + "state": "power_consumption_yesterday", "unit": ENERGY_KILO_WATT_HOUR, } -SENSOR_POWER_PRODUCTION_CURRENT_HOUR = { +FEATURE_POWER_PRODUCTION_CURRENT_HOUR = { "id": "power_prod_cur_hour", "name": "Power production current hour", - "state": "get_power_production_current_hour", + "state": "power_production_current_hour", "unit": ENERGY_KILO_WATT_HOUR, } -SENSOR_POWER_PRODUCTION_PREVIOUS_HOUR = { +FEATURE_POWER_PRODUCTION_PREVIOUS_HOUR = { "id": "power_prod_prev_hour", "name": "Power production previous hour", - "state": "get_power_production_previous_hour", + "state": "power_production_previous_hour", "unit": ENERGY_KILO_WATT_HOUR, } -SENSOR_SWITCH = { +FEATURE_RELAY = { + "id": "relay", + "name": "Relay state", + "state": "relay_state", + "unit": "state", +} +FEATURE_SWITCH = { "id": "switch", - "name": "switch", - "state": "get_switch_state", + "name": "Switch state", + "state": "switch_state", "unit": "state", } -SENSOR_TEMPERATURE = { +FEATURE_TEMPERATURE = { "id": "temperature", "name": "Temperature", - "state": "get_temperature", + "state": "temperature", "unit": TEMP_CELSIUS, } # TODO: Need to validate RSSI sensors -SENSOR_RSSI_IN = { +FEATURE_RSSI_IN = { "id": "RSSI_in", "name": "RSSI in", - "state": "get_rssi_in", + "state": "rssi_in", "unit": "Unknown", } -SENSOR_RSSI_OUT = { +FEATURE_RSSI_OUT = { "id": "RSSI_out", "name": "RSSI out", - "state": "get_rssi_out", + "state": "rssi_out", "unit": "Unknown", } -# Switches -SWITCH_RELAY = { - "id": "relay", - "name": "Relay state", - "state": "get_relay_state", - "switch": "set_relay_state", -} - -# Home Assistant entities -HA_SWITCH = "switch" -HA_SENSOR = "sensor" -HA_BINARY_SENSOR = "binary_sensor" - - ### Smile constants ### APPLIANCES = "/core/appliances" diff --git a/plugwise/controller.py b/plugwise/controller.py index 94bb6ef5b..c4282a0b9 100644 --- a/plugwise/controller.py +++ b/plugwise/controller.py @@ -5,7 +5,7 @@ - handle the connection (connect/disconnect) to the USB-Stick - take care for message acknowledgements based on sequence id's - resend message requests when timeouts occurs -- holds a sending queue (fifo) +- holds a sending queue and submit messages based on the message priority (high, medium, low) - passes received messages back to message processor (stick.py) - execution of callbacks after processing the response message @@ -13,7 +13,7 @@ from datetime import datetime, timedelta import logging -import queue +from queue import Empty, PriorityQueue import threading import time @@ -22,6 +22,7 @@ from .constants import ( MESSAGE_RETRY, MESSAGE_TIME_OUT, + PRIORITY_MEDIUM, REQUEST_FAILED, REQUEST_SUCCESS, SLEEP_TIME, @@ -62,7 +63,7 @@ def connect_to_stick(self, callback=None) -> bool: """ Connect to USB-Stick and startup all worker threads - Return: True when if successfully. + Return: True when connection is successful. """ self.init_callback = callback # Open connection to USB Stick @@ -77,7 +78,7 @@ def connect_to_stick(self, callback=None) -> bool: if self.connection.connect(): _LOGGER.debug("Starting message controller threads...") # send daemon - self._send_message_queue = queue.Queue() + self._send_message_queue = PriorityQueue() self._run_send_message_thread = True self._send_message_thread = threading.Thread( None, self._send_message_loop, "send_messages_thread", (), {} @@ -96,20 +97,32 @@ def connect_to_stick(self, callback=None) -> bool: _LOGGER.warning("Failed to connect to USB stick") return self.connection.is_connected() - def send(self, request: NodeRequest, callback=None, retry_counter=0): + def send( + self, + request: NodeRequest, + callback=None, + retry_counter=0, + priority=PRIORITY_MEDIUM, + ): """Queue request message to be sent into Plugwise Zigbee network.""" _LOGGER.debug( - "Queue %s to be send with retry counter %s", + "Queue %s to be send with retry counter %s and priority %s", request.__class__.__name__, str(retry_counter), + str(priority), ) self._send_message_queue.put( - [ - request, - callback, + ( + priority, retry_counter, - None, - ] + datetime.now(), + [ + request, + callback, + retry_counter, + None, + ], + ) ) def resend(self, seq_id): @@ -142,7 +155,7 @@ def resend(self, seq_id): if self.expected_responses[seq_id][1]: self.expected_responses[seq_id][1]() else: - _LOGGER.warning( + _LOGGER.info( "Resend %s for %s, retry %s of %s", _request, _mac, @@ -180,8 +193,10 @@ def _send_message_loop(self): """Daemon to send messages waiting in queue.""" while self._run_send_message_thread: try: - request_set = self._send_message_queue.get(block=True, timeout=1) - except queue.Empty: + _prio, _retry, _dt, request_set = self._send_message_queue.get( + block=True, timeout=1 + ) + except Empty: time.sleep(SLEEP_TIME) else: # Calc next seq_id based last received ack message diff --git a/plugwise/messages/responses.py b/plugwise/messages/responses.py index 48fe6593b..29fb1ca7f 100644 --- a/plugwise/messages/responses.py +++ b/plugwise/messages/responses.py @@ -495,7 +495,7 @@ class NodeFeaturesResponse(NodeResponse): def __init__(self): super().__init__() - self.features = Int(0, 16) + self.features = String(None, length=16) self.params += [self.features] diff --git a/plugwise/nodes/__init__.py b/plugwise/nodes/__init__.py index 91efbc218..40dba17ff 100644 --- a/plugwise/nodes/__init__.py +++ b/plugwise/nodes/__init__.py @@ -3,11 +3,12 @@ import logging from ..constants import ( - SENSOR_AVAILABLE, - SENSOR_PING, - SENSOR_RSSI_IN, - SENSOR_RSSI_OUT, - SWITCH_RELAY, + FEATURE_AVAILABLE, + FEATURE_PING, + FEATURE_RELAY, + FEATURE_RSSI_IN, + FEATURE_RSSI_OUT, + PRIORITY_LOW, UTF8_DECODE, ) from ..messages.requests import NodeFeaturesRequest, NodeInfoRequest, NodePingRequest @@ -33,153 +34,162 @@ def __init__(self, mac, address, message_sender): "MAC address is in unexpected format: %s", str(mac), ) - self.mac = bytes(mac, encoding=UTF8_DECODE) + self._mac = bytes(mac, encoding=UTF8_DECODE) self.message_sender = message_sender - self.categories = () - self.sensors = () - self.switches = () + self._features = () self._address = address self._callbacks = {} - self.last_update = None + self._last_update = None self._available = False - self.in_RSSI = None - self.out_RSSI = None - self.ping_ms = None + self._battery_powered = False + self._measures_power = False + self._RSSI_in = None + self._RSSI_out = None + self._ping = None self._node_type = None self._hardware_version = None self._firmware_version = None self._relay_state = False self._last_log_address = None self.last_info_message = None - self._features = None + self._device_features = None - def get_node_type(self) -> str: - """Return hardware model.""" - if self._hardware_version: - return version_to_model(self._hardware_version) - return None - - def is_sed(self) -> bool: - """Return True if node SED (battery powered).""" - return False - - def measure_power(self) -> bool: - """Return True if node can measure power usage.""" - return False - - def get_categories(self) -> tuple: - """Return Home Assistant categories supported by plugwise node.""" - return self.categories - - def get_sensors(self) -> tuple: - """Return sensors supported by plugwise node.""" - return self.sensors - - def get_switches(self) -> tuple: - """Return switches supported by plugwise node.""" - return self.switches - - def get_available(self) -> bool: - """Return current network state of plugwise node.""" + @property + def available(self) -> bool: + """Current network state of plugwise node.""" return self._available - def set_available(self, state, request_info=False): + @available.setter + def available(self, state: bool): """Set current network availability state of plugwise node.""" if state: if not self._available: self._available = True _LOGGER.debug( "Mark node %s available", - self.get_mac(), + self.mac, ) - self.do_callback(SENSOR_AVAILABLE["id"]) - if request_info: - self.request_info() + self.do_callback(FEATURE_AVAILABLE["id"]) else: if self._available: self._available = False _LOGGER.debug( "Mark node %s unavailable", - self.get_mac(), + self.mac, ) - self.do_callback(SENSOR_AVAILABLE["id"]) + self.do_callback(FEATURE_AVAILABLE["id"]) - def get_mac(self) -> str: - """Return mac address.""" - return self.mac.decode(UTF8_DECODE) + @property + def battery_powered(self) -> bool: + """Return True if node is a SED (battery powered) device.""" + return self._battery_powered - def get_name(self) -> str: - """Return unique name.""" - return self.get_node_type() + " (" + str(self._address) + ")" + @property + def hardware_model(self) -> str: + """Return hardware model.""" + if self._hardware_version: + return version_to_model(self._hardware_version) + return None - def get_hardware_version(self) -> str: + @property + def hardware_version(self) -> str: """Return hardware version.""" if self._hardware_version is not None: return self._hardware_version return "Unknown" - def get_firmware_version(self) -> str: + @property + def features(self) -> tuple: + """Return the abstracted features supported by this plugwise device.""" + return self._features + + @property + def firmware_version(self) -> str: """Return firmware version.""" if self._firmware_version is not None: return str(self._firmware_version) return "Unknown" - def get_last_update(self) -> datetime: - """Return version.""" - return self.last_update + @property + def last_update(self) -> datetime: + """Return datetime of last received update.""" + return self._last_update - def get_in_RSSI(self) -> int: - """Return inbound RSSI level.""" - if self.in_RSSI is not None: - return self.in_RSSI + @property + def mac(self) -> str: + """Return the MAC address in string.""" + return self._mac.decode(UTF8_DECODE) + + @property + def measures_power(self) -> bool: + """Return True if node can measure power usage.""" + return self._measures_power + + @property + def name(self) -> str: + """Return unique name.""" + return self.hardware_model + " (" + str(self._address) + ")" + + @property + def ping(self) -> int: + """Return ping roundtrip in ms.""" + if self._ping is not None: + return self._ping return 0 - def get_out_RSSI(self) -> int: - """Return outbound RSSI level.""" - if self.out_RSSI is not None: - return self.out_RSSI + @property + def rssi_in(self) -> int: + """Return inbound RSSI level.""" + if self._RSSI_in is not None: + return self._RSSI_in return 0 - def get_ping(self) -> int: - """Return ping roundtrip.""" - if self.ping_ms is not None: - return self.ping_ms + @property + def rssi_out(self) -> int: + """Return outbound RSSI level, based on inbound RSSI level of neighbor node.""" + if self._RSSI_out is not None: + return self._RSSI_out return 0 - def request_info(self, callback=None): + def _request_info(self, callback=None): """Request info from node.""" self.message_sender( - NodeInfoRequest(self.mac), + NodeInfoRequest(self._mac), callback, + 0, + PRIORITY_LOW, ) def _request_features(self, callback=None): """Request supported features for this node.""" self.message_sender( - NodeFeaturesRequest(self.mac), + NodeFeaturesRequest(self._mac), callback, ) - def ping(self, callback=None, sensor=True): + def _request_ping(self, callback=None, ignore_sensor=True): """Ping node.""" - if sensor or SENSOR_PING["id"] in self._callbacks: + if ignore_sensor or FEATURE_PING["id"] in self._callbacks: self.message_sender( - NodePingRequest(self.mac), + NodePingRequest(self._mac), callback, ) def message_for_node(self, message): """Process received message.""" assert isinstance(message, NodeResponse) - if message.mac == self.mac: + if message.mac == self._mac: if message.timestamp is not None: _LOGGER.debug( - "Last update %s of node %s, last message %s", - str(self.last_update), - self.get_mac(), + "Previous update %s of node %s, last message %s", + str(self._last_update), + self.mac, str(message.timestamp), ) - self.last_update = message.timestamp + self._last_update = message.timestamp + if not self._available: + self.available = True + self._request_info() if isinstance(message, NodePingResponse): self._process_ping_response(message) elif isinstance(message, NodeInfoResponse): @@ -187,7 +197,7 @@ def message_for_node(self, message): elif isinstance(message, NodeFeaturesResponse): self._process_features_response(message) elif isinstance(message, NodeJoinAckResponse): - self.set_available(True, True) + self._process_join_ack_response(message) else: self.message_for_circle(message) self.message_for_sed(message) @@ -195,7 +205,7 @@ def message_for_node(self, message): _LOGGER.debug( "Skip message, mac of node (%s) != mac at message (%s)", message.mac.decode(UTF8_DECODE), - self.get_mac(), + self.mac, ) def message_for_circle(self, message): @@ -208,7 +218,7 @@ def message_for_sed(self, message): def subscribe_callback(self, callback, sensor) -> bool: """Subscribe callback to execute when state change happens.""" - if sensor in self.sensors: + if sensor in self._features: if sensor not in self._callbacks: self._callbacks[sensor] = [] self._callbacks[sensor].append(callback) @@ -232,38 +242,43 @@ def do_callback(self, sensor): e, ) + def _process_join_ack_response(self, message): + """Process join acknowledge response message""" + _LOGGER.info( + "Node %s has (re)joined plugwise network", + self.mac, + ) + def _process_ping_response(self, message): """Process ping response message.""" - self.set_available(True, True) - if self.in_RSSI != message.in_RSSI.value: - self.in_RSSI = message.in_RSSI.value - self.do_callback(SENSOR_RSSI_IN["id"]) - if self.out_RSSI != message.out_RSSI.value: - self.out_RSSI = message.out_RSSI.value - self.do_callback(SENSOR_RSSI_OUT["id"]) - if self.ping_ms != message.ping_ms.value: - self.ping_ms = message.ping_ms.value - self.do_callback(SENSOR_PING["id"]) + if self._RSSI_in != message.in_RSSI.value: + self._RSSI_in = message.in_RSSI.value + self.do_callback(FEATURE_RSSI_IN["id"]) + if self._RSSI_out != message.out_RSSI.value: + self._RSSI_out = message.out_RSSI.value + self.do_callback(FEATURE_RSSI_OUT["id"]) + if self._ping != message.ping_ms.value: + self._ping = message.ping_ms.value + self.do_callback(FEATURE_PING["id"]) def _process_info_response(self, message): """Process info response message.""" - _LOGGER.debug("Response info message for node %s", self.get_mac()) - self.set_available(True) + _LOGGER.debug("Response info message for node %s", self.mac) if message.relay_state.serialize() == b"01": if not self._relay_state: self._relay_state = True - self.do_callback(SWITCH_RELAY["id"]) + self.do_callback(FEATURE_RELAY["id"]) else: if self._relay_state: self._relay_state = False - self.do_callback(SWITCH_RELAY["id"]) + self.do_callback(FEATURE_RELAY["id"]) self._hardware_version = message.hw_ver.value.decode(UTF8_DECODE) self._firmware_version = message.fw_ver.value self._node_type = message.node_type.value self.last_info_message = message.timestamp if self._last_log_address != message.last_logaddr.value: self._last_log_address = message.last_logaddr.value - _LOGGER.debug("Node type = %s", self.get_node_type()) + _LOGGER.debug("Node type = %s", self.hardware_model) if not self.is_sed: _LOGGER.debug("Relay state = %s", str(self._relay_state)) _LOGGER.debug("Hardware version = %s", str(self._hardware_version)) @@ -271,7 +286,132 @@ def _process_info_response(self, message): def _process_features_response(self, message): """Process features message.""" - _LOGGER.info( - "Node %s supports features %s", self.get_mac(), str(message.features.value) + _LOGGER.warning( + "Node %s supports features %s", self.mac, str(message.features.value) + ) + self._device_features = message.features.value + + ## TODO: All functions below can be removed when HA component is changed to use the property values ## + def get_node_type(self) -> str: + """Return hardware model.""" + _LOGGER.warning( + "Function 'get_node_type' will be removed in future, use the 'hardware_model' property instead !", + ) + if self._hardware_version: + return version_to_model(self._hardware_version) + return None + + def is_sed(self) -> bool: + """Return True if node SED (battery powered).""" + _LOGGER.warning( + "Function 'is_sed' will be removed in future, use the 'battery_powered' property instead !", ) - self._features = message.features.value + return False + + def measure_power(self) -> bool: + """Return True if node can measure power usage.""" + _LOGGER.warning( + "Function 'measure_power' will be removed in future, use the 'measures_power' property instead !", + ) + return self._measures_power + + def get_categories(self) -> tuple: + """Return Home Assistant categories supported by plugwise node.""" + _LOGGER.warning( + "Function 'get_categories' will be removed in future, use the 'categories' property instead !", + ) + return self._categories + + def get_sensors(self) -> tuple: + """Return sensors supported by plugwise node.""" + _LOGGER.warning( + "Function 'get_sensors' will be removed in future, use the 'sensors' property instead !", + ) + return self._sensors + + def get_switches(self) -> tuple: + """Return switches supported by plugwise node.""" + _LOGGER.warning( + "Function 'get_switches' will be removed in future, use the 'switches' property instead !", + ) + return self._switches + + def get_available(self) -> bool: + """Return current network state of plugwise node.""" + _LOGGER.warning( + "Function 'get_available' will be removed in future, use the 'available' property instead !", + ) + return self.available + + def set_available(self, state, request_info=False): + """Set current network availability state of plugwise node.""" + _LOGGER.warning( + "Function 'set_available' will be removed in future, use the 'available' property instead !", + ) + self.available = state + + def get_mac(self) -> str: + """Return mac address.""" + _LOGGER.warning( + "Function 'get_mac' will be removed in future, use the 'mac' property instead !", + ) + return self._mac.decode(UTF8_DECODE) + + def get_name(self) -> str: + """Return unique name.""" + _LOGGER.warning( + "Function 'get_name' will be removed in future, use the 'name' property instead !", + ) + return self.self.hardware_model + " (" + str(self._address) + ")" + + def get_hardware_version(self) -> str: + """Return hardware version.""" + _LOGGER.warning( + "Function 'get_hardware_version' will be removed in future, use the 'hardware_version' property instead !", + ) + if self._hardware_version is not None: + return self._hardware_version + return "Unknown" + + def get_firmware_version(self) -> str: + """Return firmware version.""" + _LOGGER.warning( + "Function 'get_firmware_version' will be removed in future, use the 'firmware_version' property instead !", + ) + if self._firmware_version is not None: + return str(self._firmware_version) + return "Unknown" + + def get_last_update(self) -> datetime: + """Return version.""" + _LOGGER.warning( + "Function 'get_last_update' will be removed in future, use the 'last_update' property instead !", + ) + return self._last_update + + def get_in_RSSI(self) -> int: + """Return inbound RSSI level.""" + _LOGGER.warning( + "Function 'get_in_RSSI' will be removed in future, use the 'rssi_in' property instead !", + ) + if self._RSSI_in is not None: + return self._RSSI_in + return 0 + + def get_out_RSSI(self) -> int: + """Return outbound RSSI level.""" + _LOGGER.warning( + "Function 'get_out_RSSI' will be removed in future, use the 'rssi_out' property instead !", + ) + if self._RSSI_out is not None: + return self._RSSI_out + return 0 + + def get_ping(self) -> int: + """Return ping roundtrip.""" + _LOGGER.warning( + "Function 'get_ping' will be removed in future, use the 'ping' property instead !", + ) + if self._ping is not None: + return self._ping + return 0 diff --git a/plugwise/nodes/circle.py b/plugwise/nodes/circle.py index f003c1863..5777ec3a6 100644 --- a/plugwise/nodes/circle.py +++ b/plugwise/nodes/circle.py @@ -3,24 +3,24 @@ import logging from ..constants import ( - HA_SENSOR, - HA_SWITCH, + FEATURE_PING, + FEATURE_POWER_CONSUMPTION_CURRENT_HOUR, + FEATURE_POWER_CONSUMPTION_PREVIOUS_HOUR, + FEATURE_POWER_CONSUMPTION_TODAY, + FEATURE_POWER_CONSUMPTION_YESTERDAY, + FEATURE_POWER_PRODUCTION_CURRENT_HOUR, + FEATURE_POWER_USE, + FEATURE_POWER_USE_LAST_8_SEC, + FEATURE_RELAY, + FEATURE_RSSI_IN, + FEATURE_RSSI_OUT, MAX_TIME_DRIFT, + MESSAGE_TIME_OUT, + PRIORITY_HIGH, + PRIORITY_LOW, PULSES_PER_KW_SECOND, RELAY_SWITCHED_OFF, RELAY_SWITCHED_ON, - SENSOR_AVAILABLE, - SENSOR_PING, - SENSOR_POWER_CONSUMPTION_CURRENT_HOUR, - SENSOR_POWER_CONSUMPTION_PREVIOUS_HOUR, - SENSOR_POWER_CONSUMPTION_TODAY, - SENSOR_POWER_CONSUMPTION_YESTERDAY, - SENSOR_POWER_PRODUCTION_CURRENT_HOUR, - SENSOR_POWER_USE, - SENSOR_POWER_USE_LAST_8_SEC, - SENSOR_RSSI_IN, - SENSOR_RSSI_OUT, - SWITCH_RELAY, ) from ..messages.requests import ( CircleCalibrationRequest, @@ -47,35 +47,36 @@ class PlugwiseCircle(PlugwiseNode): def __init__(self, mac, address, message_sender): super().__init__(mac, address, message_sender) - self.categories = (HA_SWITCH, HA_SENSOR) - self.sensors = ( - SENSOR_AVAILABLE["id"], - SENSOR_PING["id"], - SENSOR_POWER_USE["id"], - SENSOR_POWER_USE_LAST_8_SEC["id"], - SENSOR_POWER_CONSUMPTION_CURRENT_HOUR["id"], - SENSOR_POWER_CONSUMPTION_PREVIOUS_HOUR["id"], - SENSOR_POWER_CONSUMPTION_TODAY["id"], - SENSOR_POWER_CONSUMPTION_YESTERDAY["id"], - SENSOR_POWER_PRODUCTION_CURRENT_HOUR["id"], - # SENSOR_POWER_PRODUCTION_PREVIOUS_HOUR["id"], - SENSOR_RSSI_IN["id"], - SENSOR_RSSI_OUT["id"], + self._features = ( + FEATURE_PING["id"], + FEATURE_POWER_USE["id"], + FEATURE_POWER_USE_LAST_8_SEC["id"], + FEATURE_POWER_CONSUMPTION_CURRENT_HOUR["id"], + FEATURE_POWER_CONSUMPTION_PREVIOUS_HOUR["id"], + FEATURE_POWER_CONSUMPTION_TODAY["id"], + FEATURE_POWER_CONSUMPTION_YESTERDAY["id"], + FEATURE_POWER_PRODUCTION_CURRENT_HOUR["id"], + # FEATURE_POWER_PRODUCTION_PREVIOUS_HOUR["id"], + FEATURE_RSSI_IN["id"], + FEATURE_RSSI_OUT["id"], + FEATURE_RELAY["id"], ) - self.switches = (SWITCH_RELAY["id"],) - self.pulses_1s = None - self.pulses_8s = None - self.pulses_consumed_1h = None - self.pulses_produced_1h = None + self._new_relay_state = False + self._new_relay_stamp = datetime.now() - timedelta(seconds=MESSAGE_TIME_OUT) + self._pulses_1s = None + self._pulses_8s = None + self._pulses_consumed_1h = None + self._pulses_produced_1h = None self.calibration = False self._gain_a = None self._gain_b = None self._off_noise = None self._off_tot = None + self._measures_power = True self.power_history = {} - self.power_consumption_prev_hour = None - self.power_consumption_today = None - self.power_consumption_yesterday = None + self._power_consumption_prev_hour = None + self._power_consumption_today = None + self._power_consumption_yesterday = None self.last_log_collected = False self.timezone_delta = datetime.now().replace( minute=0, second=0, microsecond=0 @@ -84,29 +85,103 @@ def __init__(self, mac, address, message_sender): self.get_clock(self.sync_clock) self._request_calibration() - def measure_power(self) -> bool: - """Return True if node can measure power usage.""" - return True + @property + def current_power_usage(self): + """ + Returns power usage during the last second in Watts + Based on last received power usage information + """ + if self._pulses_1s is not None: + return self.pulses_to_kWs(self._pulses_1s) * 1000 + return None + + @property + def current_power_usage_8_sec(self): + """ + Returns power usage during the last 8 second in Watts + Based on last received power usage information + """ + if self._pulses_8s is not None: + return self.pulses_to_kWs(self._pulses_8s, 8) * 1000 + return None + + @property + def power_consumption_current_hour(self): + """ + Returns the power usage during this running hour in kWh + Based on last received power usage information + """ + if self._pulses_consumed_1h is not None: + return self.pulses_to_kWs(self._pulses_consumed_1h, 3600) + return None + + @property + def power_consumption_previous_hour(self): + """Returns power consumption during the previous hour in kWh""" + return self._power_consumption_prev_hour + + @property + def power_consumption_today(self): + """Total power consumption during today in kWh""" + return self._power_consumption_today + + @property + def power_consumption_yesterday(self): + """Total power consumption of yesterday in kWh""" + return self._power_consumption_yesterday + + @property + def power_production_current_hour(self): + """ + Returns the power production during this running hour in kWh + Based on last received power usage information + """ + if self._pulses_produced_1h is not None: + return self.pulses_to_kWs(self._pulses_produced_1h, 3600) + return None + + @property + def relay_state(self) -> bool: + """ + Return last known relay state or the new switch state by anticipating + the acknowledge for new state is getting in before message timeout. + """ + if self._new_relay_stamp + timedelta(seconds=MESSAGE_TIME_OUT) > datetime.now(): + return self._new_relay_state + return self._relay_state + + @relay_state.setter + def relay_state(self, state): + """Request the relay to switch state.""" + self._request_switch(state) + self._new_relay_state = state + self._new_relay_stamp = datetime.now() + if state != self._relay_state: + self.do_callback(FEATURE_RELAY["id"]) def _request_calibration(self, callback=None): """Request calibration info""" self.message_sender( - CircleCalibrationRequest(self.mac), + CircleCalibrationRequest(self._mac), callback, + 0, + PRIORITY_HIGH, ) def _request_switch(self, state, callback=None): """Request to switch relay state and request state info""" self.message_sender( - CircleSwitchRelayRequest(self.mac, state), + CircleSwitchRelayRequest(self._mac, state), callback, + 0, + PRIORITY_HIGH, ) - def update_power_usage(self, callback=None): + def _request_power_update(self, callback=None): """Request power usage and power logs of last hour""" - if self.get_available(): + if self._available: self.message_sender( - CirclePowerUsageRequest(self.mac), + CirclePowerUsageRequest(self._mac), callback, ) # Refresh node info once an hour and request last hour power use afterwards @@ -117,7 +192,7 @@ def update_power_usage(self, callback=None): microsecond=0, ) ): - self.request_info(self.request_power_buffer) + self._request_info(self.request_power_buffer) if not self.last_log_collected: self.request_power_buffer() @@ -130,15 +205,15 @@ def message_for_circle(self, message): self._response_power_usage(message) _LOGGER.debug( "Power update for %s, last update %s", - self.get_mac(), - str(self.last_update), + self.mac, + str(self._last_update), ) else: _LOGGER.info( "Received power update for %s before calibration information is known", - self.get_mac(), + self.mac, ) - self._request_calibration(self.update_power_usage) + self._request_calibration(self._request_power_update) elif isinstance(message, NodeAckLargeResponse): self._node_ack_response(message) elif isinstance(message, CircleCalibrationResponse): @@ -149,7 +224,7 @@ def message_for_circle(self, message): else: _LOGGER.debug( "Received power buffer log for %s before calibration information is known", - self.get_mac(), + self.mac, ) self._request_calibration(self.request_power_buffer) elif isinstance(message, CircleClockResponse): @@ -161,85 +236,29 @@ def message_for_circle_plus(self, message): """Pass messages to PlugwiseCirclePlus class""" pass - def get_relay_state(self) -> bool: - """Return last known relay state.""" - return self._relay_state - - def set_relay_state(self, state: bool, callback=None): - """Switch relay.""" - self._request_switch(state, callback) - - def get_power_usage(self): - """ - Returns power usage during the last second in Watts - Based on last received power usage information - """ - if self.pulses_1s is not None: - return self.pulses_to_kWs(self.pulses_1s) * 1000 - return None - - def get_power_usage_8_sec(self): - """ - Returns power usage during the last 8 second in Watts - Based on last received power usage information - """ - if self.pulses_8s is not None: - return self.pulses_to_kWs(self.pulses_8s, 8) * 1000 - return None - - def get_power_consumption_current_hour(self): - """ - Returns the power usage during this running hour in kWh - Based on last received power usage information - """ - if self.pulses_consumed_1h is not None: - return self.pulses_to_kWs(self.pulses_consumed_1h, 3600) - return None - - def get_power_production_current_hour(self): - """ - Returns the power production during this running hour in kWh - Based on last received power usage information - """ - if self.pulses_produced_1h is not None: - return self.pulses_to_kWs(self.pulses_produced_1h, 3600) - return None - - def get_power_consumption_prev_hour(self): - """Returns power consumption during the previous hour in kWh""" - return self.power_consumption_prev_hour - - def get_power_consumption_today(self): - """Total power consumption during today in kWh""" - return self.power_consumption_today - - def get_power_consumption_yesterday(self): - """Total power consumption of yesterday in kWh""" - return self.power_consumption_yesterday - def _node_ack_response(self, message): """Process switch response message""" if message.ack_id == RELAY_SWITCHED_ON: if not self._relay_state: _LOGGER.debug( "Switch relay on for %s", - self.get_mac(), + self.mac, ) self._relay_state = True - self.do_callback(SWITCH_RELAY["id"]) + self.do_callback(FEATURE_RELAY["id"]) elif message.ack_id == RELAY_SWITCHED_OFF: if self._relay_state: _LOGGER.debug( "Switch relay off for %s", - self.get_mac(), + self.mac, ) self._relay_state = False - self.do_callback(SWITCH_RELAY["id"]) + self.do_callback(FEATURE_RELAY["id"]) else: _LOGGER.debug( "Unmanaged _node_ack_response %s received for %s", str(message.ack_id), - self.get_mac(), + self.mac, ) def _response_power_usage(self, message): @@ -253,9 +272,9 @@ def _response_power_usage(self, message): message.pulse_1s.value = 0 _LOGGER.debug( "1 sec power pulse counter for node %s has value of -1, corrected to 0", - self.get_mac(), + self.mac, ) - self.pulses_1s = message.pulse_1s.value + self._pulses_1s = message.pulse_1s.value if message.pulse_1s.value != 0: if message.nanosecond_offset.value != 0: pulses_1s = ( @@ -264,16 +283,16 @@ def _response_power_usage(self, message): ) / 1000000000 else: pulses_1s = message.pulse_1s.value - self.pulses_1s = pulses_1s + self._pulses_1s = pulses_1s else: - self.pulses_1s = 0 - self.do_callback(SENSOR_POWER_USE["id"]) + self._pulses_1s = 0 + self.do_callback(FEATURE_POWER_USE["id"]) # Power consumption last 8 seconds if message.pulse_8s.value == -1: message.pulse_8s.value = 0 _LOGGER.debug( "8 sec power pulse counter for node %s has value of -1, corrected to 0", - self.get_mac(), + self.mac, ) if message.pulse_8s.value != 0: if message.nanosecond_offset.value != 0: @@ -283,30 +302,30 @@ def _response_power_usage(self, message): ) / 1000000000 else: pulses_8s = message.pulse_8s.value - self.pulses_8s = pulses_8s + self._pulses_8s = pulses_8s else: - self.pulses_8s = 0 - self.do_callback(SENSOR_POWER_USE_LAST_8_SEC["id"]) + self._pulses_8s = 0 + self.do_callback(FEATURE_POWER_USE_LAST_8_SEC["id"]) # Power consumption current hour if message.pulse_hour_consumed.value == -1: message.pulse_hour_consumed.value = 0 _LOGGER.debug( "1 hour consumption power pulse counter for node %s has value of -1, corrected to 0", - self.get_mac(), + self.mac, ) - if self.pulses_consumed_1h != message.pulse_hour_consumed.value: - self.pulses_consumed_1h = message.pulse_hour_consumed.value - self.do_callback(SENSOR_POWER_CONSUMPTION_CURRENT_HOUR["id"]) + if self._pulses_consumed_1h != message.pulse_hour_consumed.value: + self._pulses_consumed_1h = message.pulse_hour_consumed.value + self.do_callback(FEATURE_POWER_CONSUMPTION_CURRENT_HOUR["id"]) # Power produced current hour if message.pulse_hour_produced.value == -1: message.pulse_hour_produced.value = 0 _LOGGER.debug( "1 hour power production pulse counter for node %s has value of -1, corrected to 0", - self.get_mac(), + self.mac, ) - if self.pulses_produced_1h != message.pulse_hour_produced.value: - self.pulses_produced_1h = message.pulse_hour_produced.value - self.do_callback(SENSOR_POWER_PRODUCTION_CURRENT_HOUR["id"]) + if self._pulses_produced_1h != message.pulse_hour_produced.value: + self._pulses_produced_1h = message.pulse_hour_produced.value + self.do_callback(FEATURE_POWER_PRODUCTION_CURRENT_HOUR["id"]) def _response_calibration(self, message): """Store calibration properties""" @@ -343,22 +362,32 @@ def request_power_buffer(self, log_address=None, callback=None): if bool(self.power_history): # Only request last 2 power buffer logs self.message_sender( - CirclePowerBufferRequest(self.mac, log_address - 1), + CirclePowerBufferRequest(self._mac, log_address - 1), + None, + 0, + PRIORITY_LOW, ) self.message_sender( - CirclePowerBufferRequest(self.mac, log_address), + CirclePowerBufferRequest(self._mac, log_address), callback, + 0, + PRIORITY_LOW, ) else: # Collect power history info of today and yesterday # Each request contains 4 hours except last request for req_log_address in range(log_address - 13, log_address): self.message_sender( - CirclePowerBufferRequest(self.mac, req_log_address), + CirclePowerBufferRequest(self._mac, req_log_address), + None, + 0, + PRIORITY_LOW, ) self.message_sender( - CirclePowerBufferRequest(self.mac, log_address), + CirclePowerBufferRequest(self._mac, log_address), callback, + 0, + PRIORITY_LOW, ) def _response_power_buffer(self, message): @@ -401,15 +430,15 @@ def _response_power_buffer(self, message): datetime.now().today().date() - timedelta(days=1) ): yesterday_power += self.power_history[dt] - if self.power_consumption_prev_hour != last_hour_usage: - self.power_consumption_prev_hour = last_hour_usage - self.do_callback(SENSOR_POWER_CONSUMPTION_PREVIOUS_HOUR["id"]) - if self.power_consumption_today != today_power: - self.power_consumption_today = today_power - self.do_callback(SENSOR_POWER_CONSUMPTION_TODAY["id"]) - if self.power_consumption_yesterday != yesterday_power: - self.power_consumption_yesterday = yesterday_power - self.do_callback(SENSOR_POWER_CONSUMPTION_YESTERDAY["id"]) + if self._power_consumption_prev_hour != last_hour_usage: + self._power_consumption_prev_hour = last_hour_usage + self.do_callback(FEATURE_POWER_CONSUMPTION_PREVIOUS_HOUR["id"]) + if self._power_consumption_today != today_power: + self._power_consumption_today = today_power + self.do_callback(FEATURE_POWER_CONSUMPTION_TODAY["id"]) + if self._power_consumption_yesterday != yesterday_power: + self._power_consumption_yesterday = yesterday_power + self.do_callback(FEATURE_POWER_CONSUMPTION_YESTERDAY["id"]) def _response_clock(self, message): dt = datetime( @@ -429,21 +458,23 @@ def _response_clock(self, message): self._clock_offset = clock_offset.seconds _LOGGER.debug( "Clock of node %s has drifted %s sec", - self.get_mac(), + self.mac, str(self._clock_offset), ) def get_clock(self, callback=None): """get current datetime of internal clock of Circle.""" self.message_sender( - CircleClockGetRequest(self.mac), + CircleClockGetRequest(self._mac), callback, + 0, + PRIORITY_LOW, ) def set_clock(self, callback=None): """set internal clock of CirclePlus.""" self.message_sender( - CircleClockSetRequest(self.mac, datetime.utcnow()), + CircleClockSetRequest(self._mac, datetime.utcnow()), callback, ) @@ -455,7 +486,91 @@ def sync_clock(self, max_drift=0): if (self._clock_offset > max_drift) or (self._clock_offset < -(max_drift)): _LOGGER.info( "Reset clock of node %s because time has drifted %s sec", - self.get_mac(), + self.mac, str(self._clock_offset), ) self.set_clock() + + ## TODO: All functions below can be removed when HA component is changed to use the property values ## + def get_relay_state(self) -> bool: + """Return last known relay state.""" + _LOGGER.warning( + "Function 'get_relay_state' will be removed in future, use the 'relay_state' property instead !", + ) + return self._relay_state + + def set_relay_state(self, state: bool, callback=None): + """Switch relay.""" + _LOGGER.warning( + "Function 'set_relay_state' will be removed in future, use the 'relay_state' property instead !", + ) + self._request_switch(state, callback) + + def get_power_usage(self): + """ + Returns power usage during the last second in Watts + Based on last received power usage information + """ + _LOGGER.warning( + "Function 'get_power_usage' will be removed in future, use the 'current_power_usage' property instead !", + ) + if self._pulses_1s is not None: + return self.pulses_to_kWs(self._pulses_1s) * 1000 + return None + + def get_power_usage_8_sec(self): + """ + Returns power usage during the last 8 second in Watts + Based on last received power usage information + """ + _LOGGER.warning( + "Function 'get_power_usage_8_sec' will be removed in future, use the 'current_power_usage_8_sec' property instead !", + ) + if self._pulses_8s is not None: + return self.pulses_to_kWs(self._pulses_8s, 8) * 1000 + return None + + def get_power_consumption_current_hour(self): + """ + Returns the power usage during this running hour in kWh + Based on last received power usage information + """ + _LOGGER.warning( + "Function 'get_power_consumption_current_hour' will be removed in future, use the 'power_consumption_current_hour' property instead !", + ) + if self._pulses_consumed_1h is not None: + return self.pulses_to_kWs(self._pulses_consumed_1h, 3600) + return None + + def get_power_production_current_hour(self): + """ + Returns the power production during this running hour in kWh + Based on last received power usage information + """ + _LOGGER.warning( + "Function 'get_power_production_current_hour' will be removed in future, use the 'power_production_current_hour' property instead !", + ) + if self._pulses_produced_1h is not None: + return self.pulses_to_kWs(self._pulses_produced_1h, 3600) + return None + + def get_power_consumption_prev_hour(self): + """Returns power consumption during the previous hour in kWh""" + _LOGGER.warning( + "Function 'get_power_consumption_prev_hour' will be removed in future, use the 'power_consumption_previous_hour' property instead !", + ) + return self._power_consumption_prev_hour + + def get_power_consumption_today(self): + """Total power consumption during today in kWh""" + _LOGGER.warning( + "Function 'get_power_consumption_today' will be removed in future, use the 'power_consumption_today' property instead !", + ) + return self._power_consumption_today + + def get_power_consumption_yesterday(self): + """Total power consumption of yesterday in kWh""" + _LOGGER.warning( + "Function 'get_power_consumption_yesterday' will be removed in future, use the 'power_consumption_yesterday' property instead !", + ) + return self._power_consumption_yesterday diff --git a/plugwise/nodes/circle_plus.py b/plugwise/nodes/circle_plus.py index 74b657c18..344ba1fa9 100644 --- a/plugwise/nodes/circle_plus.py +++ b/plugwise/nodes/circle_plus.py @@ -2,7 +2,7 @@ from datetime import datetime import logging -from ..constants import MAX_TIME_DRIFT, UTF8_DECODE +from ..constants import MAX_TIME_DRIFT, PRIORITY_LOW, UTF8_DECODE from ..messages.requests import ( CirclePlusRealTimeClockGetRequest, CirclePlusRealTimeClockSetRequest, @@ -37,14 +37,14 @@ def message_for_circle_plus(self, message): _LOGGER.waning( "Unsupported message type '%s' received from circle with mac %s", str(message.__class__.__name__), - self.get_mac(), + self.mac, ) def scan_for_nodes(self, callback=None): """Scan for registered nodes.""" self._scan_for_nodes_callback = callback for node_address in range(0, 64): - self.message_sender(CirclePlusScanRequest(self.mac, node_address)) + self.message_sender(CirclePlusScanRequest(self._mac, node_address)) self._scan_response[node_address] = False def _process_scan_response(self, message): @@ -77,7 +77,7 @@ def _process_scan_response(self, message): str(node_address), ) self.message_sender( - CirclePlusScanRequest(self.mac, node_address) + CirclePlusScanRequest(self._mac, node_address) ) break if node_address == 63: @@ -90,8 +90,10 @@ def _process_scan_response(self, message): def get_real_time_clock(self, callback=None): """get current datetime of internal clock of CirclePlus.""" self.message_sender( - CirclePlusRealTimeClockGetRequest(self.mac), + CirclePlusRealTimeClockGetRequest(self._mac), callback, + 0, + PRIORITY_LOW, ) def _response_realtime_clock(self, message): @@ -112,14 +114,14 @@ def _response_realtime_clock(self, message): self._realtime_clock_offset = realtime_clock_offset.seconds _LOGGER.debug( "Realtime clock of node %s has drifted %s sec", - self.get_mac(), + self.mac, str(self._clock_offset), ) def set_real_time_clock(self, callback=None): """set internal clock of CirclePlus.""" self.message_sender( - CirclePlusRealTimeClockSetRequest(self.mac, datetime.utcnow()), + CirclePlusRealTimeClockSetRequest(self._mac, datetime.utcnow()), callback, ) @@ -133,7 +135,7 @@ def sync_realtime_clock(self, max_drift=0): ): _LOGGER.info( "Reset realtime clock of node %s because time has drifted %s sec", - self.get_mac(), + self.mac, str(self._clock_offset), ) self.set_real_time_clock() diff --git a/plugwise/nodes/scan.py b/plugwise/nodes/scan.py index d8583f970..83ef4d3dd 100644 --- a/plugwise/nodes/scan.py +++ b/plugwise/nodes/scan.py @@ -2,19 +2,17 @@ import logging from ..constants import ( - HA_BINARY_SENSOR, - HA_SENSOR, + FEATURE_AVAILABLE, + FEATURE_MOTION, + FEATURE_PING, + FEATURE_RSSI_IN, + FEATURE_RSSI_OUT, SCAN_CONFIGURE_ACCEPTED, SCAN_DAYLIGHT_MODE, SCAN_MOTION_RESET_TIMER, SCAN_SENSITIVITY_HIGH, SCAN_SENSITIVITY_MEDIUM, SCAN_SENSITIVITY_OFF, - SENSOR_AVAILABLE, - SENSOR_MOTION, - SENSOR_PING, - SENSOR_RSSI_IN, - SENSOR_RSSI_OUT, ) from ..messages.requests import ScanConfigureRequest, ScanLightCalibrateRequest from ..messages.responses import NodeAckResponse, NodeSwitchGroupResponse @@ -28,13 +26,11 @@ class PlugwiseScan(NodeSED): def __init__(self, mac, address, message_sender): super().__init__(mac, address, message_sender) - self.categories = (HA_SENSOR, HA_BINARY_SENSOR) - self.sensors = ( - SENSOR_AVAILABLE["id"], - SENSOR_PING["id"], - SENSOR_MOTION["id"], - SENSOR_RSSI_IN["id"], - SENSOR_RSSI_OUT["id"], + self._features = ( + FEATURE_MOTION["id"], + FEATURE_PING["id"], + FEATURE_RSSI_IN["id"], + FEATURE_RSSI_OUT["id"], ) self._motion_state = False self._motion_reset_timer = None @@ -44,8 +40,9 @@ def __init__(self, mac, address, message_sender): self._new_daylight_mode = None self._new_sensitivity = None - def get_motion(self) -> bool: - """Return motion state""" + @property + def motion(self) -> bool: + """Return the last known motion state""" return self._motion_state def message_for_scan(self, message): @@ -57,7 +54,7 @@ def message_for_scan(self, message): "Switch group %s to state %s received from %s", str(message.group.value), str(message.power_state.value), - self.get_mac(), + self.mac, ) self._process_switch_group(message) elif isinstance(message, NodeAckResponse): @@ -66,7 +63,7 @@ def message_for_scan(self, message): _LOGGER.info( "Unsupported message %s received from %s", message.__class__.__name__, - self.get_mac(), + self.mac, ) def _process_ack_message(self, message): @@ -79,7 +76,7 @@ def _process_ack_message(self, message): _LOGGER.info( "Unsupported ack message %s received for %s", str(message.ack_id), - self.get_mac(), + self.mac, ) def _process_switch_group(self, message): @@ -88,22 +85,22 @@ def _process_switch_group(self, message): # turn off => clear motion if self._motion_state: self._motion_state = False - self.do_callback(SENSOR_MOTION["id"]) + self.do_callback(FEATURE_MOTION["id"]) elif message.power_state.value == 1: # turn on => motion if not self._motion_state: self._motion_state = True - self.do_callback(SENSOR_MOTION["id"]) + self.do_callback(FEATURE_MOTION["id"]) else: _LOGGER.warning( "Unknown power_state (%s) received from %s", str(message.power_state.value), - self.get_mac(), + self.mac, ) def CalibrateLight(self, callback=None): """Queue request to calibration light sensitivity""" - self._queue_request(ScanLightCalibrateRequest(self.mac), callback) + self._queue_request(ScanLightCalibrateRequest(self._mac), callback) def Configure_scan( self, @@ -125,7 +122,7 @@ def Configure_scan( self._new_sensitivity = sensitivity_level self._queue_request( ScanConfigureRequest( - self.mac, motion_reset_timer, sensitivity_value, daylight_mode + self._mac, motion_reset_timer, sensitivity_value, daylight_mode ), callback, ) @@ -134,4 +131,13 @@ def SetMotionAction(self, callback=None): """Queue Configure Scan to signal motion""" # TODO: - # self._queue_request(NodeSwitchGroupRequest(self.mac), callback) + # self._queue_request(NodeSwitchGroupRequest(self._mac), callback) + + ## TODO: All functions below can be removed when HA component is changed to use the property values ## + def get_motion(self) -> bool: + """Return motion state""" + # TODO: Can be removed when HA component is changed to use property + _LOGGER.warning( + "Function 'get_motion' will be removed in future, use the 'motion' property instead !", + ) + return self._motion_state diff --git a/plugwise/nodes/sed.py b/plugwise/nodes/sed.py index 3c1be34c3..570443a7b 100644 --- a/plugwise/nodes/sed.py +++ b/plugwise/nodes/sed.py @@ -7,6 +7,10 @@ import logging from ..constants import ( + FEATURE_PING, + FEATURE_RSSI_IN, + FEATURE_RSSI_OUT, + PRIORITY_HIGH, SED_AWAKE_BUTTON, SED_AWAKE_FIRST, SED_AWAKE_MAINTENANCE, @@ -17,9 +21,6 @@ SED_MAINTENANCE_INTERVAL, SED_SLEEP_FOR, SED_STAY_ACTIVE, - SENSOR_PING, - SENSOR_RSSI_IN, - SENSOR_RSSI_OUT, SLEEP_SET, ) from ..messages.requests import NodeInfoRequest, NodePingRequest, NodeSleepConfigRequest @@ -38,10 +39,7 @@ def __init__(self, mac, address, message_sender): self.maintenance_interval = SED_MAINTENANCE_INTERVAL self._new_maintenance_interval = None self._wake_up_interval = None - - def is_sed(self) -> bool: - """Return if True if node SED (battery powered)""" - return True + self._battery_powered = True def message_for_sed(self, message): """ @@ -78,7 +76,7 @@ def _process_awake_response(self, message): _LOGGER.debug( "Awake message type '%s' received from %s", str(message.awake_type.value), - self.get_mac(), + self.mac, ) if ( message.awake_type.value == SED_AWAKE_MAINTENANCE @@ -91,18 +89,18 @@ def _process_awake_response(self, message): _LOGGER.info( "Send queued %s message to SED node %s", request_message.__class__.__name__, - self.get_mac(), + self.mac, ) - self.message_sender(request_message, callback, -1) + self.message_sender(request_message, callback, -1, PRIORITY_HIGH) self._SED_requests = {} else: if message.awake_type.value == SED_AWAKE_STATE: - _LOGGER.debug("Node %s awake for state change", self.get_mac()) + _LOGGER.debug("Node %s awake for state change", self.mac) else: _LOGGER.info( "Unknown awake message type (%s) received for node %s", str(message.awake_type.value), - self.get_mac(), + self.mac, ) def _queue_request(self, request_message, callback=None): @@ -112,29 +110,29 @@ def _queue_request(self, request_message, callback=None): callback, ) - def request_info(self, callback=None): + def _request_info(self, callback=None): """Request info from node""" self._queue_request( - NodeInfoRequest(self.mac), + NodeInfoRequest(self._mac), callback, ) - def ping(self, callback=None, sensor=True): + def _request_ping(self, callback=None, sensor=True): """Ping node""" if ( sensor - or self._callbacks.get(SENSOR_PING["id"]) - or self._callbacks.get(SENSOR_RSSI_IN["id"]) - or self._callbacks.get(SENSOR_RSSI_OUT["id"]) + or self._callbacks.get(FEATURE_PING["id"]) + or self._callbacks.get(FEATURE_RSSI_IN["id"]) + or self._callbacks.get(FEATURE_RSSI_OUT["id"]) ): self._queue_request( - NodePingRequest(self.mac), + NodePingRequest(self._mac), callback, ) else: _LOGGER.debug( "Drop ping request for SED %s because no callback is registered", - self.get_mac(), + self.mac, ) def _wake_up_interval_accepted(self): @@ -151,7 +149,7 @@ def Configure_SED( ): """Reconfigure the sleep/awake settings for a SED send at next awake of SED""" message = NodeSleepConfigRequest( - self.mac, + self._mac, stay_active, maintenance_interval, sleep_for, @@ -163,5 +161,5 @@ def Configure_SED( _LOGGER.info( "Queue %s message to be send at next awake of SED node %s", message.__class__.__name__, - self.get_mac(), + self.mac, ) diff --git a/plugwise/nodes/sense.py b/plugwise/nodes/sense.py index 45e356757..5cbe998c7 100644 --- a/plugwise/nodes/sense.py +++ b/plugwise/nodes/sense.py @@ -2,17 +2,15 @@ import logging from ..constants import ( - HA_BINARY_SENSOR, - HA_SENSOR, + FEATURE_HUMIDITY, + FEATURE_PING, + FEATURE_RSSI_IN, + FEATURE_RSSI_OUT, + FEATURE_TEMPERATURE, SENSE_HUMIDITY_MULTIPLIER, SENSE_HUMIDITY_OFFSET, SENSE_TEMPERATURE_MULTIPLIER, SENSE_TEMPERATURE_OFFSET, - SENSOR_AVAILABLE, - SENSOR_HUMIDITY, - SENSOR_RSSI_IN, - SENSOR_RSSI_OUT, - SENSOR_TEMPERATURE, ) from ..messages.responses import SenseReportResponse from ..nodes.sed import NodeSED @@ -25,25 +23,26 @@ class PlugwiseSense(NodeSED): def __init__(self, mac, address, message_sender): super().__init__(mac, address, message_sender) - self.categories = (HA_SENSOR, HA_BINARY_SENSOR) - self.sensors = ( - SENSOR_AVAILABLE["id"], - SENSOR_TEMPERATURE["id"], - SENSOR_HUMIDITY["id"], - SENSOR_RSSI_IN["id"], - SENSOR_RSSI_OUT["id"], + self._features = ( + FEATURE_HUMIDITY["id"], + FEATURE_PING["id"], + FEATURE_RSSI_IN["id"], + FEATURE_RSSI_OUT["id"], + FEATURE_TEMPERATURE["id"], ) self._temperature = None self._humidity = None - def get_temperature(self) -> int: - """Return the current temperature.""" - return self._temperature - - def get_humidity(self) -> int: + @property + def humidity(self) -> int: """Return the current humidity.""" return self._humidity + @property + def temperature(self) -> int: + """Return the current temperature.""" + return self._temperature + def message_for_sense(self, message): """ Process received message @@ -54,7 +53,7 @@ def message_for_sense(self, message): _LOGGER.info( "Unsupported message %s received from %s", message.__class__.__name__, - self.get_mac(), + self.mac, ) def _process_sense_report(self, message): @@ -68,10 +67,10 @@ def _process_sense_report(self, message): self._temperature = new_temperature _LOGGER.debug( "Sense report received from %s with new temperature level of %s", - self.get_mac(), + self.mac, str(self._temperature), ) - self.do_callback(SENSOR_TEMPERATURE["id"]) + self.do_callback(FEATURE_TEMPERATURE["id"]) if message.humidity.value != 65535: new_humidity = int( SENSE_HUMIDITY_MULTIPLIER * (message.humidity.value / 65536) @@ -81,7 +80,22 @@ def _process_sense_report(self, message): self._humidity = new_humidity _LOGGER.debug( "Sense report received from %s with new humidity level of %s", - self.get_mac(), + self.mac, str(self._humidity), ) - self.do_callback(SENSOR_HUMIDITY["id"]) + self.do_callback(FEATURE_HUMIDITY["id"]) + + ## TODO: All functions below can be removed when HA component is changed to use the property values ## + def get_temperature(self) -> int: + """Return the current temperature.""" + _LOGGER.warning( + "Function 'get_temperature' will be removed in future, use the 'temperature' property instead !", + ) + return self._temperature + + def get_humidity(self) -> int: + """Return the current humidity.""" + _LOGGER.warning( + "Function 'get_humidity' will be removed in future, use the 'humidity' property instead !", + ) + return self._humidity diff --git a/plugwise/nodes/switch.py b/plugwise/nodes/switch.py index 57cbc8f0f..4b9978460 100644 --- a/plugwise/nodes/switch.py +++ b/plugwise/nodes/switch.py @@ -1,7 +1,7 @@ """Plugwise switch node object.""" import logging -from ..constants import HA_BINARY_SENSOR, HA_SENSOR, SENSOR_SWITCH +from ..constants import FEATURE_PING, FEATURE_RSSI_IN, FEATURE_RSSI_OUT, FEATURE_SWITCH from ..messages.responses import NodeSwitchGroupResponse from ..nodes.sed import NodeSED @@ -13,11 +13,17 @@ class PlugwiseSwitch(NodeSED): def __init__(self, mac, address, message_sender): super().__init__(mac, address, message_sender) - self.categories = (HA_SENSOR, HA_BINARY_SENSOR) + self._features = ( + FEATURE_PING["id"], + FEATURE_RSSI_IN["id"], + FEATURE_RSSI_OUT["id"], + FEATURE_SWITCH["id"], + ) self._switch_state = False - def get_switch_state(self): - """Return state of switch""" + @property + def switch(self) -> bool: + """Return the last known switch state""" return self._switch_state def message_for_switch(self, message): @@ -28,7 +34,7 @@ def message_for_switch(self, message): _LOGGER.debug( "Switch group request %s received from %s for group id %s", str(message.power_state), - self.get_mac(), + self.mac, str(message.group), ) self._process_switch_group(message) @@ -39,15 +45,23 @@ def _process_switch_group(self, message): # turn off => clear motion if self._switch_state: self._switch_state = False - self.do_callback(SENSOR_SWITCH["id"]) + self.do_callback(FEATURE_SWITCH["id"]) elif message.power_state == 1: # turn on => motion if not self._switch_state: self._switch_state = True - self.do_callback(SENSOR_SWITCH["id"]) + self.do_callback(FEATURE_SWITCH["id"]) else: _LOGGER.debug( "Unknown power_state (%s) received from %s", str(message.power_state), - self.get_mac(), + self.mac, ) + + ## TODO: All functions below can be removed when HA component is changed to use the property values ## + def get_switch_state(self): + """Return state of switch""" + _LOGGER.warning( + "Function 'get_switch_state' will be removed in future, use the 'switch' property instead !", + ) + return self._switch_state diff --git a/plugwise/smile.py b/plugwise/smile.py index a5471fac0..45cee712d 100644 --- a/plugwise/smile.py +++ b/plugwise/smile.py @@ -224,22 +224,21 @@ async def request( resp = None url = f"{self._endpoint}{command}" - if headers is None: - headers = {"Content-type": "text/xml"} - try: with async_timeout.timeout(self._timeout): if method == "get": - resp = await self.websession.get(url, auth=self._auth) + # Work-around for Stretchv2, should not hurt the other smiles + headers = {"Accept-Encoding": "gzip"} + resp = await self.websession.get( + url, auth=self._auth, headers=headers + ) if method == "put": + headers = {"Content-type": "text/xml"} resp = await self.websession.put( url, data=data, headers=headers, auth=self._auth ) if method == "delete": resp = await self.websession.delete(url, auth=self._auth) - if resp.status == 401: - raise InvalidAuthentication - except asyncio.TimeoutError: if retry < 1: _LOGGER.error("Timed out sending command to Plugwise: %s", command) @@ -253,6 +252,9 @@ async def request( if method == "put" and resp.status == 200: return + if resp.status == 401: + raise InvalidAuthentication + result = await resp.text() if not result or "" in result: _LOGGER.error("Smile response empty or error in %s", result) diff --git a/plugwise/stick.py b/plugwise/stick.py index f2f6f3a30..68a3d24f2 100644 --- a/plugwise/stick.py +++ b/plugwise/stick.py @@ -13,7 +13,6 @@ ACCEPT_JOIN_REQUESTS, CB_JOIN_REQUEST, CB_NEW_NODE, - MESSAGE_RETRY, MESSAGE_TIME_OUT, NODE_TYPE_CELSIUS_NR, NODE_TYPE_CELSIUS_SED, @@ -23,6 +22,7 @@ NODE_TYPE_SENSE, NODE_TYPE_STEALTH, NODE_TYPE_SWITCH, + PRIORITY_LOW, STATE_ACTIONS, UTF8_DECODE, WATCHDOG_DEAMON, @@ -67,16 +67,16 @@ class stick: """Plugwise connection stick.""" def __init__(self, port, callback=None): - self.port = port + self._port = port self._mac_stick = None - self.network_online = False + self._network_online = False self.circle_plus_mac = None self._circle_plus_discovered = False self._circle_plus_retries = 0 self.scan_callback = None - self.network_id = None - self._plugwise_nodes = {} - self._nodes_registered = 0 + self._network_id = None + self._device_nodes = {} + self._joined_nodes = 0 self._nodes_to_discover = {} self._nodes_not_discovered = {} self._nodes_off_line = 0 @@ -86,6 +86,7 @@ def __init__(self, port, callback=None): self._stick_callbacks = {} self._run_update_thread = False self._auto_update_timer = 0 + self._auto_update_manually = False self._nodes_discovered = None self._run_watchdog = None self._update_thread = None @@ -95,11 +96,50 @@ def __init__(self, port, callback=None): if callback: self.auto_initialize(callback) + @property + def devices(self) -> dict: + """All discovered and supported plugwise devices with the MAC address as their key""" + return self._device_nodes + + @property + def joined_nodes(self) -> int: + """Return total number of nodes registered to Circle+ including Circle+ itself.""" + return self._joined_nodes + 1 + + @property + def mac(self) -> str: + """Return the MAC address of the USB-Stick.""" + if self._mac_stick: + return self._mac_stick.decode(UTF8_DECODE) + return None + + @property + def network_state(self) -> bool: + """Return the state of the Plugwise network.""" + return self._network_online + + @property + def network_id(self) -> int: + """Return the id of the Plugwise network.""" + return self._network_id + + @property + def port(self) -> str: + """Return currently configured port to USB-Stick.""" + return self._port + + @port.setter + def port(self, port: str): + """Set port to USB-Stick.""" + if self.msg_controller: + self.disconnect() + self._port = port + def auto_initialize(self, callback=None): """Automatic initialization of USB-stick and discovery of all registered nodes.""" def init_finished(): - if not self.network_online: + if not self._network_online: _LOGGER.Error("plugwise Zigbee network down") else: self.scan(callback) @@ -149,7 +189,7 @@ def initialize_stick(self, callback=None, timeout=MESSAGE_TIME_OUT): time.sleep(0.1) if not self._stick_initialized: raise StickInitError - if not self.network_online: + if not self._network_online: raise NetworkDown def initialize_circle_plus(self, callback=None, timeout=MESSAGE_TIME_OUT): @@ -175,6 +215,7 @@ def disconnect(self): self._run_update_thread = False self._auto_update_timer = 0 self.msg_controller.disconnect_from_stick() + self.msg_controller = None def subscribe_stick_callback(self, callback, callback_type): """Subscribe callback to execute.""" @@ -205,18 +246,16 @@ def scan(self, callback=None): def scan_circle_plus(self): """Scan the Circle+ memory for registered nodes.""" - if self._plugwise_nodes.get(self.circle_plus_mac): + if self._device_nodes.get(self.circle_plus_mac): _LOGGER.debug("Scan Circle+ for linked nodes...") - self._plugwise_nodes[self.circle_plus_mac].scan_for_nodes( - self.discover_nodes - ) + self._device_nodes[self.circle_plus_mac].scan_for_nodes(self.discover_nodes) else: _LOGGER.error("Circle+ is not discovered yet") def scan_for_registered_nodes(self): """Discover Circle+ and all registered nodes at Circle+.""" if self.circle_plus_mac: - if self._plugwise_nodes.get(self.circle_plus_mac): + if self._device_nodes.get(self.circle_plus_mac): self.scan_circle_plus() else: _LOGGER.debug("Discover Circle+ at %s", self.circle_plus_mac) @@ -231,12 +270,10 @@ def discover_nodes(self, nodes_to_discover): _LOGGER.debug("Scan plugwise network finished") self._nodes_discovered = 0 self._nodes_to_discover = nodes_to_discover - self._nodes_registered = len(nodes_to_discover) + self._joined_nodes = len(nodes_to_discover) # setup timeout for node discovery - discover_timeout = ( - 10 + (len(nodes_to_discover) * 2) + (MESSAGE_TIME_OUT * MESSAGE_RETRY) - ) + discover_timeout = 10 + (len(nodes_to_discover) * 2) + (MESSAGE_TIME_OUT) threading.Timer(discover_timeout, self.scan_timeout_expired).start() _LOGGER.debug("Start discovery of linked node types...") for mac in nodes_to_discover: @@ -249,11 +286,11 @@ def node_discovered_by_scan(self, nodes_off_line=False): self._nodes_discovered += 1 _LOGGER.debug( "Discovered Plugwise node %s (%s off-line) of %s", - str(len(self._plugwise_nodes)), + str(len(self._device_nodes)), str(self._nodes_off_line), str(len(self._nodes_to_discover)), ) - if (len(self._plugwise_nodes) - 1 + self._nodes_off_line) >= len( + if (len(self._device_nodes) - 1 + self._nodes_off_line) >= len( self._nodes_to_discover ): if self._nodes_off_line == 0: @@ -261,7 +298,7 @@ def node_discovered_by_scan(self, nodes_off_line=False): self._nodes_not_discovered = {} else: for mac in self._nodes_to_discover: - if mac not in self._plugwise_nodes.keys(): + if not self._device_nodes.get(mac): _LOGGER.info( "Failed to discover node type for registered MAC '%s'. This is expected for battery powered nodes, they will be discovered at their first awake", str(mac), @@ -277,7 +314,7 @@ def scan_timeout_expired(self): """Timeout for initial scan.""" if not self.msg_controller.discovery_finished: for mac in self._nodes_to_discover: - if mac not in self._plugwise_nodes.keys(): + if mac not in self._device_nodes.keys(): _LOGGER.info( "Failed to discover node type for registered MAC '%s'. This is expected for battery powered nodes, they will be discovered at their first awake", str(mac), @@ -288,12 +325,6 @@ def scan_timeout_expired(self): if self.scan_callback: self.scan_callback() - def get_mac_stick(self) -> str: - """Return mac address of USB-Stick""" - if self._mac_stick: - return self._mac_stick.decode(UTF8_DECODE) - return None - def _append_node(self, mac, address, node_type): """Add node to list of controllable nodes""" _LOGGER.debug( @@ -302,34 +333,34 @@ def _append_node(self, mac, address, node_type): mac, ) if node_type == NODE_TYPE_CIRCLE_PLUS: - self._plugwise_nodes[mac] = PlugwiseCirclePlus( + self._device_nodes[mac] = PlugwiseCirclePlus( mac, address, self.msg_controller.send ) elif node_type == NODE_TYPE_CIRCLE: - self._plugwise_nodes[mac] = PlugwiseCircle( + self._device_nodes[mac] = PlugwiseCircle( mac, address, self.msg_controller.send ) elif node_type == NODE_TYPE_SWITCH: - self._plugwise_nodes[mac] = None + self._device_nodes[mac] = None elif node_type == NODE_TYPE_SENSE: - self._plugwise_nodes[mac] = PlugwiseSense( + self._device_nodes[mac] = PlugwiseSense( mac, address, self.msg_controller.send ) elif node_type == NODE_TYPE_SCAN: - self._plugwise_nodes[mac] = PlugwiseScan( + self._device_nodes[mac] = PlugwiseScan( mac, address, self.msg_controller.send ) elif node_type == NODE_TYPE_CELSIUS_SED: - self._plugwise_nodes[mac] = None + self._device_nodes[mac] = None elif node_type == NODE_TYPE_CELSIUS_NR: - self._plugwise_nodes[mac] = None + self._device_nodes[mac] = None elif node_type == NODE_TYPE_STEALTH: - self._plugwise_nodes[mac] = PlugwiseStealth( + self._device_nodes[mac] = PlugwiseStealth( mac, address, self.msg_controller.send ) else: _LOGGER.warning("Unsupported node type '%s'", str(node_type)) - self._plugwise_nodes[mac] = None + self._device_nodes[mac] = None # process previous missed messages msg_to_process = self._messages_for_undiscovered_nodes[:] @@ -337,27 +368,11 @@ def _append_node(self, mac, address, node_type): for msg in msg_to_process: self.message_processor(msg) - def registered_nodes(self) -> int: - """Return total number of nodes registered to Circle+ including Circle+ itself""" - return self._nodes_registered + 1 - - def nodes(self) -> list: - """Return list of mac addresses of discovered and supported plugwise nodes.""" - return list( - dict( - filter(lambda item: item[1] is not None, self._plugwise_nodes.items()) - ).keys() - ) - - def node(self, mac: str) -> PlugwiseNode: - """Return a specific node object""" - return self._plugwise_nodes.get(mac) - def node_state_updates(self, mac, state: bool): """Update availability state of a node""" - if mac in self._plugwise_nodes: - if not self._plugwise_nodes[mac].is_sed(): - self._plugwise_nodes[mac].set_available(state) + if self._device_nodes.get(mac): + if not self._device_nodes[mac].battery_powered: + self._device_nodes[mac].available = state def node_join(self, mac: str, callback=None) -> bool: """Accept node to join Plugwise network by register mac in Circle+ memory""" @@ -385,8 +400,10 @@ def node_unjoin(self, mac: str, callback=None) -> bool: def _remove_node(self, mac): """Remove node from list of controllable nodes.""" - if mac in self._plugwise_nodes: - del self._plugwise_nodes[mac] + if self._device_nodes.get(mac): + del self._device_nodes[mac] + else: + _LOGGER.warning("Node %s does not exists, unable to remove node.", mac) def message_processor(self, message: NodeResponse): """Received message from Plugwise network.""" @@ -409,14 +426,14 @@ def _process_stick_init_response(self, stick_init_response: StickInitResponse): """Process StickInitResponse message.""" self._mac_stick = stick_init_response.mac if stick_init_response.network_is_online.value == 1: - self.network_online = True + self._network_online = True else: - self.network_online = False + self._network_online = False # Replace first 2 characters by 00 for mac of circle+ node self.circle_plus_mac = "00" + stick_init_response.circle_plus_mac.value[ 2: ].decode(UTF8_DECODE) - self.network_id = stick_init_response.network_id.value + self._network_id = stick_init_response.network_id.value self._stick_initialized = True if not self._run_watchdog: self._run_watchdog = True @@ -457,7 +474,12 @@ def _process_node_join_request(self, node_join_request, mac): Process NodeJoinAvailableResponse message from a node that is not part of a plugwise network yet and wants to join """ - if not self._plugwise_nodes.get(mac): + if self._device_nodes.get(mac): + _LOGGER.debug( + "Received node available message for node %s which is already joined.", + mac, + ) + else: if self._accept_join_requests: # Send accept join request _LOGGER.info( @@ -472,11 +494,6 @@ def _process_node_join_request(self, node_join_request, mac): mac, ) self.do_callback(CB_JOIN_REQUEST, mac) - else: - _LOGGER.debug( - "Received node available message for node %s which is already joined.", - mac, - ) def _process_node_remove(self, node_remove_response): """ @@ -485,8 +502,8 @@ def _process_node_remove(self, node_remove_response): """ unjoined_mac = node_remove_response.node_mac_id.value if node_remove_response.status.value == 1: - if self._plugwise_nodes.get(unjoined_mac): - del self._plugwise_nodes[unjoined_mac] + if self._device_nodes.get(unjoined_mac): + del self._device_nodes[unjoined_mac] _LOGGER.info( "Received NodeRemoveResponse from node %s it has been unjoined from Plugwise network", unjoined_mac, @@ -508,8 +525,8 @@ def _pass_message_to_node(self, message, mac, discover=True): Returns True if message has passed onto existing known node """ - if self._plugwise_nodes.get(mac): - self._plugwise_nodes[mac].message_for_node(message) + if self._device_nodes.get(mac): + self._device_nodes[mac].message_for_node(message) return True if discover: _LOGGER.info( @@ -605,20 +622,22 @@ def _update_loop(self): day_of_month = datetime.now().day try: while self._run_update_thread: - for mac in self._plugwise_nodes: - if self._plugwise_nodes[mac]: - # Do ping request for all nodes if listener is registered for sensor - self._plugwise_nodes[mac].ping(None, True) - # Check availability state of SED's - if self._plugwise_nodes[mac].is_sed(): + for mac in self._device_nodes: + if self._device_nodes[mac]: + if self._device_nodes[mac].battery_powered: + # Check availability state of SED's self._check_availability_of_seds(mac) - # Request current power usage for all nodes supporting power measurement - if self._plugwise_nodes[mac].measure_power(): - self._plugwise_nodes[mac].update_power_usage() + else: + # Do ping request for all non SED's + self._device_nodes[mac]._request_ping(None, True) + + if self._device_nodes[mac].measures_power: + # Request current power usage + self._device_nodes[mac]._request_power_update() # Sync internal clock of power measure nodes once a day if datetime.now().day != day_of_month: day_of_month = datetime.now().day - self._plugwise_nodes[mac].sync_clock() + self._device_nodes[mac].sync_clock() # Do a single ping for undiscovered nodes once per 10 update cycles if _discover_counter == 10: @@ -627,6 +646,7 @@ def _update_loop(self): NodePingRequest(bytes(mac, UTF8_DECODE)), None, -1, + PRIORITY_LOW, ) _discover_counter = 0 else: @@ -650,12 +670,22 @@ def auto_update(self, timer=None): """Configure auto update polling daemon for power usage and availability state.""" if timer: self._auto_update_timer = timer + self._auto_update_manually = True elif timer == 0: self._auto_update_timer = 0 self._run_update_thread = False else: - # Timer based on number of nodes and 3 seconds per node - self._auto_update_timer = len(self._plugwise_nodes) * 3 + # Timer based on a minimum of 5 seconds + 1 second for each node supporting power measurement + if not self._auto_update_manually: + count_nodes = 0 + for mac in self._device_nodes: + if self._device_nodes[mac].measures_power: + count_nodes += 1 + self._auto_update_timer = 5 + (count_nodes * 1) + _LOGGER.info( + "Update interval is (re)set to %s seconds", + str(self._auto_update_timer), + ) if not self._run_update_thread: self._update_thread.start() @@ -674,63 +704,96 @@ def do_callback(self, callback_type, callback_arg=None): def _check_availability_of_seds(self, mac): """Helper to check if SED device is still sending its hartbeat.""" - if self._plugwise_nodes[mac].get_available(): - if self._plugwise_nodes[mac].last_update < ( + if self._device_nodes[mac].available: + if self._device_nodes[mac].last_update < ( datetime.now() - - timedelta( - minutes=(self._plugwise_nodes[mac].maintenance_interval + 1) - ) + - timedelta(minutes=(self._device_nodes[mac].maintenance_interval + 1)) ): _LOGGER.info( "No messages received within (%s minutes) of expected maintenance interval from node %s, mark as unavailable [%s > %s]", - str(self._plugwise_nodes[mac].maintenance_interval), + str(self._device_nodes[mac].maintenance_interval), mac, - str(self._plugwise_nodes[mac].last_update), + str(self._device_nodes[mac].last_update), str( datetime.now() - timedelta( - minutes=(self._plugwise_nodes[mac].maintenance_interval + 1) + minutes=(self._device_nodes[mac].maintenance_interval + 1) ) ), ) - self._plugwise_nodes[mac].set_available(False) + self._device_nodes[mac].available = False def _discover_after_scan(self): """Helper to do callback for new node.""" node_discovered = None for mac in self._nodes_not_discovered: - if self._plugwise_nodes.get(mac): + if self._device_nodes.get(mac): node_discovered = mac break if node_discovered: del self._nodes_not_discovered[node_discovered] self.do_callback(CB_NEW_NODE, node_discovered) + self.auto_update() - def discover_node(self, mac: str, callback=None, force_discover=False) -> bool: + def discover_node(self, mac: str, callback=None, force_discover=False): """Helper to try to discovery the node (type) based on mac.""" - if validate_mac(mac): - if not self._plugwise_nodes.get(mac): - if mac not in self._nodes_not_discovered: - self._nodes_not_discovered[mac] = ( - None, - None, - ) - self.msg_controller.send( - NodeInfoRequest(bytes(mac, UTF8_DECODE)), - callback, - ) - else: - (firstrequest, lastrequest) = self._nodes_not_discovered[mac] - if not (firstrequest and lastrequest): - self.msg_controller.send( - NodeInfoRequest(bytes(mac, UTF8_DECODE)), - callback, - ) - elif force_discover: - self.msg_controller.send( - NodeInfoRequest(bytes(mac, UTF8_DECODE)), - callback, - ) - return True - return False - return False + if not validate_mac(mac) or self._device_nodes.get(mac): + return + if mac not in self._nodes_not_discovered: + self._nodes_not_discovered[mac] = ( + None, + None, + ) + self.msg_controller.send( + NodeInfoRequest(bytes(mac, UTF8_DECODE)), + callback, + ) + else: + (firstrequest, lastrequest) = self._nodes_not_discovered[mac] + if not (firstrequest and lastrequest): + self.msg_controller.send( + NodeInfoRequest(bytes(mac, UTF8_DECODE)), + callback, + 0, + PRIORITY_LOW, + ) + elif force_discover: + self.msg_controller.send( + NodeInfoRequest(bytes(mac, UTF8_DECODE)), + callback, + ) + + ## TODO: All functions below can be removed when HA component is changed to use the property values ## + def get_mac_stick(self) -> str: + """Return mac address of USB-Stick""" + _LOGGER.warning( + "Function 'get_mac_stick' will be removed in future, use the 'mac' property instead !", + ) + if self._mac_stick: + return self._mac_stick.decode(UTF8_DECODE) + return None + + def registered_nodes(self) -> int: + """Return total number of nodes registered to Circle+ including Circle+ itself""" + _LOGGER.warning( + "Function 'registered_nodes' will be removed in future, use the 'joined_nodes' property instead !", + ) + return self._joined_nodes + 1 + + def nodes(self) -> list: + """Return list of mac addresses of discovered and supported plugwise nodes.""" + _LOGGER.warning( + "Function 'nodes' will be removed in future, use the 'devices' (dict) property instead !", + ) + return list( + dict( + filter(lambda item: item[1] is not None, self._device_nodes.items()) + ).keys() + ) + + def node(self, mac: str) -> PlugwiseNode: + """Return a specific node object""" + _LOGGER.warning( + "Function 'node' will be removed in future, use the 'devices' property (dict) instead !", + ) + return self._device_nodes.get(mac) diff --git a/plugwise/util.py b/plugwise/util.py index 3ad88531f..2c46ac3a5 100644 --- a/plugwise/util.py +++ b/plugwise/util.py @@ -241,22 +241,12 @@ def __init__(self, year=0, month=1, minutes=0): def deserialize(self, val): CompositeType.deserialize(self, val) - minutes = self.minutes.value - if minutes == 0: - self.value = datetime.datetime(PLUGWISE_EPOCH, 1, 1, 0, 0) - elif minutes == 65535: + if self.minutes.value == 65535: self.value = None else: - hours = minutes // 60 - days = hours // 24 - hours -= days * 24 - minutes -= (days * 24 * 60) + (hours * 60) - try: - self.value = datetime.datetime( - self.year.value, self.month.value, days + 1, hours, minutes - ) - except datetime.datetime.ValueError: - self.value = None + self.value = datetime.datetime( + year=self.year.value, month=self.month.value, day=1 + ) + datetime.timedelta(minutes=self.minutes.value) class Time(CompositeType):