Code#
Python Package for controlling Sengled Wifi devices. SPDX-License-Identifier: Apache-2.0.
Classes#
- class SengledLogin#
Handle login connection to Sengled.
- _email#
Sengled login account
- Type:
string
- _password#
Password for Sengled login account
- Type:
string
- _outputpath#
os.path.join function pointing to the folder to save a session cookie
- Type:
function
- _urls#
points to the constant SENGLED_ENDPOINTS which is an initial list of Sengled endpoints
- Type:
dict[str, str]
- _session#
initializes an empty aiohttp.ClientSession to store the cookie information
- Type:
aiohttp.ClientSession
- _ssl#
used during the authentication
- Type:
ssl
- _headers#
based on USER_AGENT constant
- Type:
dict[str, str]
- status#
track if the connection is still valid
- Type:
dict[str, str | bool]
- stats#
track number of api calls done
- Type:
dict[str, str | bool]
- _cookiefile#
in combination with _outputpath, provides the path to save the cookie
- Type:
str
- _customer_id#
to store the customer id provided by the authentication api
- Type:
str
- _data#
body for the authentication api
- Type:
dict[str,str]
- hass_domain = 'sengledwifi'#
class attribute; from constant HA_DOMAIN
- __init__(email: str, password: str, outputpath: Callable[[str], str] = None, uuid: str = None) None #
Initialization of SengledLogin class. Calls _create_session to initialize a aiohttp.ClientSession.
- Parameters:
email (string) – Sengled login account
password (string) – Password for Sengled login account
outputpath (function) – Local path with write access for storing files
uuid – (string): Unique 32 char hex to serve as app serial number for registration
- property urls: str#
SENGLED_ENDPOINTS plus the endpoints provided by _get_server_info.
- property email: str#
Email account for this Login.
- property customer_id: str | None#
customer_id for this Login.
- property session: ClientSession | None#
Session for this Login.
- _create_session() None #
Create an aiohttp session. Called during the initialization.
- async valid_login() bool #
Function that will test the connection is logged in.
- Parameters:
None –
- Returns:
Bool. True if the session is still valid, because the cookies has been created recently. False if for some reason the cookie no longer exists or there was an error with the validSession endpoint.
- async login(SkipTest: bool = False) None #
Login to Sengled.
- Parameters:
SkipTest (bool) – login without validation (in case there is a cookie in storage)
- Returns:
None
- async save_cookiefile() None #
Save login session cookie to file.
- async _print_session_cookies() str #
Prints the value of the cookies in aiohttp session.
- async _static_request(method: str, url: str, data: dict[str, str] = None, query: dict[str, str] = None) ClientResponse #
Call an API.
- Parameters:
login (SengledLogin) – needs a valid login
uri (str) – will use the appserver endpoint with this uri
data (dict[str, str]) – payload
query (dict[str, str]) – query parameters
- Returns:
None or aiohttp ClientResponse
- async _get_server_info() None #
Call to serverDetails endpoint to get Mqtt related endpoints. Called from Login.
- async close() None #
Close connection for login.
- async reset() None #
Remove data related to existing login.
- async delete_cookie() None #
Deletes the session cookie.
- class SengledWifiMQTT#
Connect to Sengled MQTT broker, subscribe to topics and publish updates. Uses paho-mqtt package.
- _login#
SengledLogin object
- Type:
- _jsession_id#
value of cookie JSESSIONID saved in SengledLogin session
- Type:
SengledLogin session JSESSIONID
- mqtt_server#
url is obtained during the login and fetched from SengledLogin object
- Type:
URL
- mqtt_client#
initialization of paho.mqtt client with same headers used in Android app
- Type:
paho.mqtt.client
- _status#
to indicate if mqtt connection is active
- Type:
bool
- devices#
list of Sengled devices, used to create the topic strings and subscribe, during the initialization is set to None
- Type:
list[dict[str, str]]
- open_callback#
an async function to call within the on_connect callback
- Type:
Callable
- msg_callback#
an async function to call within the on_message callback
- Type:
Callable
- close_callback#
an async function to call within the on_disconnect callback
- Type:
Callable
- error_callback#
an async function to call within the on_error callback
- Type:
Callable
- _loop#
used for callbacks
- Type:
asyncio.AbstractEventLoop
- __init__(login: SengledLogin, msg_callback: Callable[[], Coroutine[Any, Any, None]] = None, open_callback: Callable[[], Coroutine[Any, Any, None]] = None, close_callback: Callable[[], Coroutine[Any, Any, None]] = None, error_callback: Callable[[], Coroutine[Any, Any, None]] = None, loop: asyncio.AbstractEventLoop = None) None #
Initialization of SengledWifiMQTT class, requires a valid SengledLogin object.
- Parameters:
login (SengledLogin) – Defines if instance exhibits this preference.
msg_callback (Callable) – callback function when new messages arrive.
open_callback (Callable) – callback function when connection is opened.
close_callback (Callable) – callback function when when the connection is closed.
error_callback (Callable) – callback function when there is an error.
loop – (asyncio.AbstractEventLoop).
- async async_connect(devices: dict = None) None #
Initialize MQTT connection async.
- Parameters:
devices – list of Sengled devices, used to create the topic strings and subscribe
- Returns:
None
- on_connect(mqttc, userdata, flags, rc, properties) None #
Callback. Called when the broker responds to our connection request.
Calls the async function open_callback defined. Uses devices input argument to subscribe if connection is successful.
- Parameters:
mqttc (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
flags (ConnectFlags) – the flags for this connection
rc (ReasonCode) – the connection reason code received from the broken. In MQTT v5.0 it is the reason code defined by the standard.
properties (Properties) – the MQTT v5.0 properties received from the broker.
- Returns:
None
- on_message(mqttc, userdata, msg) None #
Callback. Called when a message has been received from mqtt broker.
Parses the message and then calls the async function msg_callback defined.
- Parameters:
mqttc (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
msg (MQTTMessage) – the received message. This is a class with members topic, payload, qos, retain.
- Returns:
None
- on_subscribe(mqttc, userdata, mid, rc_list, properties)#
Callback. Called when the broker responds to a subscription request.
- Parameters:
mqttc (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
mid (int) – matches the mid variable returned from the corresponding subscribe() call.
rc_list (list[ReasonCode]) – reason codes received from the broker for each subscription. In MQTT v5.0 it is the reason code defined by the standard.
properties (Properties) – the MQTT v5.0 properties received from the broker.
- Returns:
None
- on_log(mqttc, userdata, level, buf)#
Callback. Called when the client has log information. Only used when the logger is set to debug.
- Parameters:
mqttc (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
level (int) – gives the severity of the message and will be one of MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR, and MQTT_LOG_DEBUG.
buf (str) – the message itself
- Returns:
None
- on_disconnect(mqttc, userdata, flags, rc, properties)#
Callback. Called when there is an issue with the connection to the mqtt broker.
- Parameters:
mqttc (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
flags (ConnectFlags) – the flags for this connection
rc (ReasonCode) – the connection reason code received from the broken. In MQTT v5.0 it’s the reason code defined by the standard.
properties (Properties) – the MQTT v5.0 properties received from the broker.
- Returns:
None
- sync_connect() None #
An alternative connection method to connect without asyncio.
- publish_mqtt(topic: str, payload: str) bool #
Publish an MQTT message.
- Parameters:
topic (str) – topic to publish the message on
payload (str) – message to send as string in json format
- Returns:
True if publish was successful or False if there was an issue
- subscribe_mqtt(topic: tuple[str, str] | list[tuple[str, str]], callback: Callable[[]] = None) bool #
Subscribe to an MQTT topic.
- Parameters:
topic (str) – topic to subscribe to
in (callback -- callback to call when a message comes) –
- Returns:
bool
- class SengledWifiAPI#
Uses SengledWifiMqtt and SengledLogin to get information of the devices and set their state.
- login#
SengledLogin object
- Type:
- devices: dict[str, Any] = {}#
Class attribute. Saves the devices registered in the related Sengled account.
- __init__(login: SengledLogin) None #
Initialize Sengled Wifi device.
- async static _static_request(method: str, login: SengledLogin, uri: str, data: dict[str, str] = None, query: dict[str, str] = None) ClientResponse #
Call an API.
- Parameters:
login (SengledLogin) – needs a valid login
uri (str) – will use the appserver endpoint with this uri
data (dict[str, str]) – payload
query (dict[str, str]) – query parameters
- Returns:
None or aiohttp ClientResponse
- async static get_devices(login: SengledLogin, entity_ids: list[str] = None) dict[str, str | int | bool] #
Retrieve all Sengled Wifi Devices or the specified ones via entity_ids arg.
- Parameters:
login (SengledLogin) – Successfully logged in SengledLogin
entity_ids (List[str]) – The list of entities you want information about. Optional if all devices information is required. (replaces get_entity_state)
- Returns:
Json. Device information.
- async static set_device_state(mqttc: SengledWifiMQTT, entity_id: str, power_on: bool = None, brightness: int = None, color: str = None, color_temperature: int = None) bool #
Set state of a device.
- Parameters:
mqttc (SengledWifiMQTT) – MQTT client
entity_id (str) – Entity ID of The light.
power_on (bool) – Should the light be on or off.
brightness (Optional[int]) – 0-255 (translated to 0-100) or None to leave as is
color (Optional[str]) – red(0-255):green(0-255):blue(0-255) or None to leave as is
color_temperature (Optional[int]) – in kelvin 2500-6500 (translated to 0-100, color ‘255:45:41’) or None to leave as is
- Returns:
Bool. True if the publish was successful, False otherwise.
Helpers#
Python Package for controlling Sengled Wifi devices. SPDX-License-Identifier: Apache-2.0.
- hide_email(email: str) str #
Obfuscate email.
- hide_password(value: str) str #
Obfuscate password.
- hide_serial(item: dict | str | list) dict | str | list #
Obfuscate serial.
- obfuscate(item)#
Obfuscate email, password, and other known sensitive keys.
- catch_all_exceptions(func)#
- valid_login_required(func)#
- async valid_response(response) None #
Response validation for aiohttp request.
- Parameters:
response (ClientResponse) – response from aiohttp request
- Returns:
None
Constants#
Python Package for controlling Sengled Wifi devices. SPDX-License-Identifier: Apache-2.0.
- HA_DOMAIN = 'sengledwifi'#
For Home Assistant integration.
- APP_NAME = 'Sengled Wifi'#
For Home Assistant integration.
- EXCEPTION_TEMPLATE = 'An exception of type {0} occurred. Arguments:\n{1!r}'#
Useful for unexpected errors.
- USER_AGENT = 'okhttp/4.9.2'#
Needed for Login.
- SENGLED_ENDPOINTS = {'login': 'https://ucenter.cloud.sengled.com/user/app/customer/v3/AuthenCross.json', 'serverDetails': 'https://life2.cloud.sengled.com/life2/server/getServerInfo.json', 'validSession': 'https://ucenter.cloud.sengled.com/user/app/customer/v2/isSessionTimeout.json'}#
Needed for Login.
Errors#
Python Package for controlling Sengled Wifi devices. SPDX-License-Identifier: Apache-2.0.
- exception SengledWifipyError#
Define a base error.
- exception SengledWifipyConnectionError#
Define an error related to invalid requests.
- exception SengledWifipyLoginError#
Define an error related to no longer being logged in.
- exception SengledWifipyTooManyRequestsError#
Define an error related to too many requests.
- exception SengledWifipyLoginCloseRequested#
Define an error related to requesting access to API after requested close.