pyscinan 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyscinan/__init__.py ADDED
@@ -0,0 +1,32 @@
1
+ """Async client for Scinan / Saswell Wi-Fi thermostats."""
2
+
3
+ from .cloud import ScinanCloudClient
4
+ from .const import Code, DeviceMode, DeviceType
5
+ from .exceptions import (
6
+ ScinanAuthFailed,
7
+ ScinanConnectionError,
8
+ ScinanError,
9
+ ScinanInvalidTokenError,
10
+ ScinanProtocolError,
11
+ ScinanResponseError,
12
+ ScinanTimeoutError,
13
+ )
14
+ from .local import ScinanLocalClient
15
+ from .models import ScinanDevice, ScinanStatus
16
+
17
+ __all__ = [
18
+ "Code",
19
+ "DeviceMode",
20
+ "DeviceType",
21
+ "ScinanAuthFailed",
22
+ "ScinanCloudClient",
23
+ "ScinanConnectionError",
24
+ "ScinanDevice",
25
+ "ScinanError",
26
+ "ScinanInvalidTokenError",
27
+ "ScinanLocalClient",
28
+ "ScinanProtocolError",
29
+ "ScinanResponseError",
30
+ "ScinanStatus",
31
+ "ScinanTimeoutError",
32
+ ]
pyscinan/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
pyscinan/cli.py ADDED
@@ -0,0 +1,115 @@
1
+ """Command line tool: ``pyscinan <command> ...`` or ``python -m pyscinan``.
2
+
3
+ Local:
4
+ pyscinan listen HOST [--seconds N]
5
+ pyscinan status HOST
6
+ pyscinan settemp HOST 21.5
7
+ pyscinan power HOST on|off
8
+ pyscinan away HOST on|off
9
+ pyscinan program HOST on|off
10
+ pyscinan mode HOST 0|1|2
11
+ pyscinan raw HOST S05 -1,1 [--no-wait]
12
+ Cloud:
13
+ pyscinan cloud-list USERNAME (password from $SCINAN_PASSWORD or prompt)
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import asyncio
20
+ import getpass
21
+ import logging
22
+ import os
23
+ import sys
24
+ from dataclasses import asdict
25
+
26
+ from .cloud import ScinanCloudClient
27
+ from .exceptions import ScinanError
28
+ from .local import ScinanLocalClient
29
+ from .models import ScinanDevice
30
+
31
+
32
+ def _onoff(value: str) -> bool:
33
+ if value.lower() in ("1", "on", "true", "yes"):
34
+ return True
35
+ if value.lower() in ("0", "off", "false", "no"):
36
+ return False
37
+ raise argparse.ArgumentTypeError(f"expected on/off, got {value!r}")
38
+
39
+
40
+ def _print_device(dev: ScinanDevice | None) -> None:
41
+ if dev is None:
42
+ print("(no device)")
43
+ return
44
+ st = dev.status
45
+ print(f"device_id={dev.device_id} type={dev.type} name={dev.name} online={dev.online}")
46
+ if st:
47
+ fields = {k: v for k, v in asdict(st).items() if k not in ("raw", "extra")}
48
+ print(" " + " ".join(f"{k}={v}" for k, v in fields.items() if v is not None))
49
+ print(f" raw={st.raw}" + (f" extra={st.extra}" if st.extra else ""))
50
+
51
+
52
+ async def _run(args: argparse.Namespace) -> int:
53
+
54
+ if args.cmd == "cloud-list":
55
+ password = os.environ.get("SCINAN_PASSWORD") or getpass.getpass("Password: ")
56
+ async with ScinanCloudClient(args.host, password) as cloud:
57
+ devices = await cloud.update_devices()
58
+ for dev in devices.values():
59
+ _print_device(dev)
60
+ return 0
61
+
62
+ client = ScinanLocalClient(args.host, device_id=args.id, reconnect=args.cmd == "listen")
63
+ client.add_message_listener(lambda m: print("<<", m))
64
+ await client.connect()
65
+ try:
66
+ if args.cmd == "listen":
67
+ await asyncio.sleep(args.seconds or 10**9)
68
+ elif args.cmd == "status":
69
+ pass # connect() already fetched status
70
+ elif args.cmd == "settemp":
71
+ await client.set_temperature(float(args.args[0]))
72
+ elif args.cmd == "power":
73
+ await client.set_power(_onoff(args.args[0]))
74
+ elif args.cmd == "away":
75
+ await client.set_away(_onoff(args.args[0]))
76
+ elif args.cmd == "program":
77
+ await client.set_program(_onoff(args.args[0]))
78
+ elif args.cmd == "mode":
79
+ await client.set_mode(int(args.args[0]))
80
+ elif args.cmd == "raw":
81
+ payload = args.args[1] if len(args.args) > 1 else "-1"
82
+ await client.send_command(args.args[0], payload, wait_for_status=not args.no_wait)
83
+ if args.no_wait:
84
+ await asyncio.sleep(3)
85
+ _print_device(client.device)
86
+ finally:
87
+ await client.close()
88
+ return 0
89
+
90
+
91
+ def main(argv: list[str] | None = None) -> int:
92
+ ap = argparse.ArgumentParser(prog="pyscinan", description=__doc__,
93
+ formatter_class=argparse.RawDescriptionHelpFormatter)
94
+ ap.add_argument("cmd", choices=["listen", "status", "settemp", "power", "away",
95
+ "program", "mode", "raw", "cloud-list"])
96
+ ap.add_argument("host", help="thermostat IP (or cloud username)")
97
+ ap.add_argument("args", nargs="*")
98
+ ap.add_argument("--id", help="16-char device id (normally learned from the hello)")
99
+ ap.add_argument("--seconds", type=float, help="listen duration")
100
+ ap.add_argument("--no-wait", action="store_true", help="raw: don't wait for S00 reply")
101
+ ap.add_argument("-v", "--verbose", action="store_true")
102
+ args = ap.parse_args(argv)
103
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING,
104
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s")
105
+ try:
106
+ return asyncio.run(_run(args))
107
+ except KeyboardInterrupt:
108
+ return 130
109
+ except ScinanError as err:
110
+ print(f"error: {err}", file=sys.stderr)
111
+ return 1
112
+
113
+
114
+ if __name__ == "__main__":
115
+ sys.exit(main())
pyscinan/cloud.py ADDED
@@ -0,0 +1,271 @@
1
+ """Async client for the Scinan / Saswell cloud API.
2
+
3
+ Ported from hass-scinan-thermostat 1.1.3 (custom_components/scinan_thermostat/api).
4
+ Only the Saswell v2.0 API (http://api.saswell.com.cn, plain HTTP) is supported.
5
+ The old Scinan v1.0 API (api.scinan.com) no longer answers and was removed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import base64
12
+ import hashlib
13
+ import logging
14
+ import time
15
+ from typing import Any
16
+
17
+ import aiohttp
18
+
19
+ from .const import (
20
+ API_DOMAIN_SASWELL,
21
+ API_TIMEOUT_DEFAULT,
22
+ COMPANY_ID_THERMOSTAT,
23
+ Code,
24
+ DeviceMode,
25
+ DeviceType,
26
+ )
27
+ from .exceptions import (
28
+ ScinanAuthFailed,
29
+ ScinanConnectionError,
30
+ ScinanInvalidTokenError,
31
+ ScinanProtocolError,
32
+ ScinanResponseError,
33
+ )
34
+ from .models import ScinanDevice, ScinanStatus
35
+ from .protocol import format_bool, format_temperature
36
+
37
+ _LOGGER = logging.getLogger(__name__)
38
+
39
+
40
+ _URI_AUTH = "/v2.0/user/login"
41
+ _URI_DEVICE_LIST = "/v2.0/device/list"
42
+ _URI_DEVICE_CONTROL = "/v2.0/sensor/control"
43
+
44
+ _REQUEST_PARAMS = {
45
+ "app_key": "100027",
46
+ "company_id": COMPANY_ID_THERMOSTAT,
47
+ "imei": "357014732382494",
48
+ }
49
+ _APP_SECRET = base64.b64decode("RTE0OTkwQ0JGNUM3NDBEQjg1MzBBQTZCRTA0REQ5RjM=").decode()
50
+
51
+ CODE_WRONG_PASSWORD_BLOCKED = "1"
52
+ CODE_TOKEN_EXPECTED = "10002"
53
+ CODE_TOKEN_EXPIRED = "10003"
54
+ CODE_WRONG_PASSWORD = "20007"
55
+ CODE_USER_NOT_EXIST = "20014"
56
+
57
+ _SUPPORTED_TYPES = tuple(int(t) for t in DeviceType)
58
+ _RETRY_DELAY = 3
59
+
60
+
61
+ def md5_hex(value: str) -> str:
62
+ return hashlib.md5(value.encode()).hexdigest()
63
+
64
+
65
+ def sign_params(params: dict[str, str], secret: str = _APP_SECRET) -> str:
66
+ """MD5(secret + k1 + v1 + k2 + v2 ... + secret), keys sorted, uppercase hex."""
67
+ payload = secret + "".join(f"{k}{v}" for k, v in sorted(params.items())) + secret
68
+ return hashlib.md5(payload.encode()).hexdigest().upper()
69
+
70
+
71
+ def _timestamp() -> str:
72
+ return time.strftime("%Y-%m-%d %H:%M:%S")
73
+
74
+
75
+ class ScinanCloudClient:
76
+ """Cloud API client. One instance per account."""
77
+
78
+ def __init__(
79
+ self,
80
+ username: str,
81
+ password: str,
82
+ *,
83
+ token: str | None = None,
84
+ session: aiohttp.ClientSession | None = None,
85
+ api_domain: str = API_DOMAIN_SASWELL,
86
+ timeout: float = API_TIMEOUT_DEFAULT,
87
+ ) -> None:
88
+ self._username = username
89
+ self._password = password
90
+ self._token = token
91
+ self._domain = api_domain
92
+ self._timeout = timeout
93
+ self._session = session
94
+ self._own_session = session is None
95
+ self.devices: dict[str, ScinanDevice] = {}
96
+
97
+ @property
98
+ def token(self) -> str | None:
99
+ return self._token
100
+
101
+ @property
102
+ def api_domain(self) -> str:
103
+ return self._domain
104
+
105
+ async def __aenter__(self) -> ScinanCloudClient:
106
+ return self
107
+
108
+ async def __aexit__(self, *exc) -> None:
109
+ await self.close()
110
+
111
+ async def close(self) -> None:
112
+ if self._own_session and self._session is not None:
113
+ await self._session.close()
114
+ self._session = None
115
+
116
+ def _get_session(self) -> aiohttp.ClientSession:
117
+ if self._session is None:
118
+ self._session = aiohttp.ClientSession()
119
+ return self._session
120
+
121
+ # -------------------------------------------------------- authentication
122
+
123
+ async def authenticate(self, *, force: bool = True) -> str:
124
+ """Log in and return the token."""
125
+ if self._token and not force:
126
+ return self._token
127
+ _LOGGER.debug("Authenticating as %s", self._username)
128
+ data = await self._request(
129
+ _URI_AUTH,
130
+ {"account": self._username, "password": md5_hex(self._password)},
131
+ retry=False,
132
+ )
133
+ token = data.get("access_token") if isinstance(data, dict) else None
134
+ if not token:
135
+ raise ScinanAuthFailed("Token not found in response")
136
+ self._token = token
137
+ return token
138
+
139
+ # ------------------------------------------------------------- requests
140
+
141
+ def _prepare_params(self, params: dict[str, str]) -> dict[str, str]:
142
+ base = {**params, **_REQUEST_PARAMS, "timestamp": _timestamp(), "token": self._token}
143
+ base = {k: v for k, v in base.items() if v is not None}
144
+ base["sign"] = sign_params(base)
145
+ return base
146
+
147
+ async def _request(self, uri: str, params: dict[str, str], *, retry: bool = True) -> Any:
148
+ if self._token is None and uri != _URI_AUTH:
149
+ await self.authenticate()
150
+ try:
151
+ return await self._request_once(uri, params)
152
+ except ScinanInvalidTokenError:
153
+ if not retry:
154
+ raise
155
+ _LOGGER.debug("Token rejected, re-authenticating")
156
+ await asyncio.sleep(_RETRY_DELAY)
157
+ await self.authenticate()
158
+ except ScinanConnectionError as err:
159
+ if not retry:
160
+ raise
161
+ _LOGGER.debug("Request failed (%s), retrying once", err)
162
+ await asyncio.sleep(_RETRY_DELAY)
163
+ return await self._request_once(uri, params)
164
+
165
+ async def _request_once(self, uri: str, params: dict[str, str]) -> Any:
166
+ url = f"{self._domain}{uri}"
167
+ try:
168
+ async with asyncio.timeout(self._timeout):
169
+ resp = await self._get_session().post(url, params=self._prepare_params(params))
170
+ if resp.status != 200:
171
+ raise ScinanResponseError(f"{uri} returned HTTP {resp.status}")
172
+ data = await resp.json(content_type=None)
173
+ except (TimeoutError, aiohttp.ClientError) as err:
174
+ raise ScinanConnectionError(f"Request {uri} failed: {err}") from err
175
+ return self._handle_response(uri, data)
176
+
177
+ def _handle_response(self, uri: str, data: Any) -> Any:
178
+ if not isinstance(data, dict):
179
+ raise ScinanResponseError(f"{uri}: unexpected response {data!r}")
180
+ code = message = None
181
+ if str(data.get("result_code")) != "0":
182
+ code = str(data.get("result_code", "unknown"))
183
+ message = data.get("result_message")
184
+ if code is not None:
185
+ err = f"{message or 'API error'} ({code})"
186
+ _LOGGER.debug("%s: %s", uri, err)
187
+ if code in (CODE_WRONG_PASSWORD, CODE_USER_NOT_EXIST):
188
+ raise ScinanAuthFailed(err)
189
+ if code == CODE_WRONG_PASSWORD_BLOCKED:
190
+ raise ScinanAuthFailed(f"Incorrect password 5 times in a row ({code})")
191
+ if code in (CODE_TOKEN_EXPIRED, CODE_TOKEN_EXPECTED):
192
+ raise ScinanInvalidTokenError(err)
193
+ raise ScinanResponseError(err)
194
+ return data.get("result_data")
195
+
196
+ # -------------------------------------------------------------- devices
197
+
198
+ async def update_devices(self) -> dict[str, ScinanDevice]:
199
+ """Fetch the device list and status of every thermostat."""
200
+ data = await self._request(_URI_DEVICE_LIST, {})
201
+ for item in self._device_items(data):
202
+ device_id = item.get("id")
203
+ if not device_id or item.get("company_id") != COMPANY_ID_THERMOSTAT:
204
+ _LOGGER.debug("Skipping non-thermostat %s", device_id)
205
+ continue
206
+ device = self.devices.setdefault(device_id, ScinanDevice(device_id=device_id))
207
+ device.name = item.get("title")
208
+ device.type = _to_int(item.get("type"))
209
+ device.company_id = item.get("company_id")
210
+ device.online = str(item.get("online")) == "1"
211
+ raw = item.get("s00")
212
+ if raw:
213
+ try:
214
+ device.update_status(ScinanStatus.parse(raw, cloud=True))
215
+ except ScinanProtocolError as err:
216
+ _LOGGER.warning("Could not parse status of %s: %s", device_id, err)
217
+ return self.devices
218
+
219
+ def _device_items(self, data: Any) -> list[dict]:
220
+ if not isinstance(data, list):
221
+ raise ScinanResponseError("Invalid device list response")
222
+ items: list[dict] = []
223
+ for group in data:
224
+ if _to_int(group.get("type")) in _SUPPORTED_TYPES:
225
+ for dev in group.get("devices") or []:
226
+ dev.setdefault("type", group.get("type"))
227
+ items.append(dev)
228
+ return items
229
+
230
+ async def device_status(self, device_id: str) -> dict[str, Any]:
231
+ """`device/status`: works even for a device missing from `device/list`.
232
+
233
+ Returns e.g. {device_id, ip (public WAN IP), online, online_time, s00, timestamp, user_id}.
234
+ """
235
+ data = await self._request("/v2.0/device/status", {"device_id": device_id})
236
+ return data if isinstance(data, dict) else {}
237
+
238
+ async def control(self, device_id: str, code: Code, value: str) -> None:
239
+ """Send a sensor control command."""
240
+ await self._request(
241
+ _URI_DEVICE_CONTROL,
242
+ {
243
+ "device_id": device_id,
244
+ "sensor_id": code.sensor_id,
245
+ "control_data": '{"value": "' + value + '"}',
246
+ "sensor_type": "1",
247
+ },
248
+ )
249
+
250
+ async def set_temperature(self, device_id: str, temperature: float) -> None:
251
+ dev = self.devices.get(device_id)
252
+ value = format_temperature(
253
+ temperature, dev.min_temp if dev else 5.0, dev.max_temp if dev else 35.0
254
+ )
255
+ await self.control(device_id, Code.TARGET_TEMPERATURE, value)
256
+
257
+ async def set_power(self, device_id: str, on: bool) -> None:
258
+ await self.control(device_id, Code.POWER, format_bool(on))
259
+
260
+ async def set_away(self, device_id: str, away: bool) -> None:
261
+ await self.control(device_id, Code.AWAY, format_bool(away))
262
+
263
+ async def set_mode(self, device_id: str, mode: DeviceMode | int) -> None:
264
+ await self.control(device_id, Code.MODE, str(int(mode)))
265
+
266
+
267
+ def _to_int(value: Any) -> int | None:
268
+ try:
269
+ return int(value)
270
+ except (TypeError, ValueError):
271
+ return None
pyscinan/const.py ADDED
@@ -0,0 +1,60 @@
1
+ """Constants shared by the local and cloud clients."""
2
+
3
+ from enum import IntEnum, StrEnum
4
+
5
+ # Local (LAN / AP mode) protocol
6
+ LOCAL_TCP_PORT = 2000
7
+ LOCAL_AP_HOST = "10.10.100.254"
8
+ LOCAL_HEARTBEAT_INTERVAL = 8.0 # app sends SPOLL every ~8 s
9
+ LOCAL_IDLE_TIMEOUT = 30.0 # reconnect if nothing received for this long
10
+ LOCAL_SENSOR_TYPE = "1"
11
+
12
+ # Cloud API
13
+ API_DOMAIN_SASWELL = "http://api.saswell.com.cn"
14
+ API_TIMEOUT_DEFAULT = 30
15
+
16
+ COMPANY_ID_THERMOSTAT = "1038" # 1038 = thermostat, 1015 = gateway
17
+
18
+ DEVICE_TEMP_MIN = 5.0
19
+ DEVICE_TEMP_MAX = 35.0
20
+
21
+
22
+ class DeviceType(IntEnum):
23
+ """Known thermostat device types (the `type` value in hello / device list)."""
24
+
25
+ WHL = 6 # water floor heating, e.g. SAS922WHL-7W-S-WIFI
26
+ FHL = 9 # electric floor heating, e.g. SAS920FHL-7W-WIFI
27
+
28
+
29
+ class Code(StrEnum):
30
+ """Sensor / command codes (same numbering locally and in the cloud)."""
31
+
32
+ STATUS = "S00"
33
+ POWER = "S01"
34
+ TARGET_TEMPERATURE = "S02"
35
+ AWAY = "S03"
36
+ PROGRAM = "S07"
37
+ MODE = "S12"
38
+ WIFI = "S99"
39
+ POLL = "SPOLL"
40
+
41
+ @property
42
+ def sensor_id(self) -> str:
43
+ """Cloud API sensor id ('S02' -> '02')."""
44
+ return self.value[1:]
45
+
46
+
47
+ class DeviceMode(IntEnum):
48
+ """System mode (S12), status field `system_mode`.
49
+
50
+ Observed on type 9 (2026-11-23):
51
+ 0 COMFORT manual, holds the set target
52
+ 1 AUTO runs the built-in schedule; device sets program=1 and the
53
+ target jumps to the schedule value (e.g. 16.0)
54
+ 2 DAY_OR_NIGHT program=0, target unchanged
55
+ Other values (3) are ignored by the device.
56
+ """
57
+
58
+ COMFORT = 0
59
+ AUTO = 1
60
+ DAY_OR_NIGHT = 2
pyscinan/exceptions.py ADDED
@@ -0,0 +1,29 @@
1
+ """pyscinan exceptions."""
2
+
3
+
4
+ class ScinanError(Exception):
5
+ """Base class for all pyscinan errors."""
6
+
7
+
8
+ class ScinanConnectionError(ScinanError):
9
+ """Could not reach the device or API, or the connection dropped."""
10
+
11
+
12
+ class ScinanTimeoutError(ScinanConnectionError):
13
+ """The device or API did not answer in time."""
14
+
15
+
16
+ class ScinanProtocolError(ScinanError):
17
+ """Got data that could not be parsed."""
18
+
19
+
20
+ class ScinanAuthFailed(ScinanError):
21
+ """Cloud login failed (wrong credentials, blocked account, ...)."""
22
+
23
+
24
+ class ScinanInvalidTokenError(ScinanError):
25
+ """Cloud token missing or expired."""
26
+
27
+
28
+ class ScinanResponseError(ScinanError):
29
+ """Cloud API returned an error."""
pyscinan/local.py ADDED
@@ -0,0 +1,417 @@
1
+ """Async client for the local TCP protocol (port 2000).
2
+
3
+ One persistent connection per thermostat. The device pushes S00 status
4
+ lines on its own and answers every command with a fresh S00, so this client
5
+ is push based: register a listener and read ``client.device``.
6
+
7
+ client = ScinanLocalClient("192.168.1.50")
8
+ await client.connect() # raises ScinanConnectionError on failure
9
+ client.add_listener(lambda: print(client.device.target_temperature))
10
+ await client.set_temperature(21.5)
11
+ ...
12
+ await client.close()
13
+
14
+ After the first successful connect the client keeps the connection alive
15
+ (SPOLL heartbeat) and reconnects with backoff if it drops.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import contextlib
22
+ import logging
23
+ import re
24
+ from collections.abc import Callable
25
+
26
+ from .const import (
27
+ LOCAL_HEARTBEAT_INTERVAL,
28
+ LOCAL_IDLE_TIMEOUT,
29
+ LOCAL_TCP_PORT,
30
+ Code,
31
+ DeviceMode,
32
+ )
33
+ from .exceptions import (
34
+ ScinanConnectionError,
35
+ ScinanProtocolError,
36
+ ScinanTimeoutError,
37
+ )
38
+ from .models import ScinanDevice, ScinanStatus
39
+ from .protocol import Message, build_line, format_bool, format_temperature, parse_line
40
+
41
+ _LOGGER = logging.getLogger(__name__)
42
+
43
+ _LINE_SPLIT_RE = re.compile(rb"[\r\n]+")
44
+ _FLUSH_PARTIAL_AFTER = 0.5 # treat an unterminated line as complete after this long
45
+ _RECONNECT_BACKOFF = (1, 2, 5, 10, 30, 60)
46
+
47
+ Listener = Callable[[], None]
48
+ MessageListener = Callable[[Message], None]
49
+
50
+
51
+ class ScinanLocalClient:
52
+ """Persistent local connection to one thermostat."""
53
+
54
+ def __init__(
55
+ self,
56
+ host: str,
57
+ *,
58
+ device_id: str | None = None,
59
+ port: int = LOCAL_TCP_PORT,
60
+ connect_timeout: float = 5.0,
61
+ command_timeout: float = 5.0,
62
+ heartbeat_interval: float = LOCAL_HEARTBEAT_INTERVAL,
63
+ idle_timeout: float = LOCAL_IDLE_TIMEOUT,
64
+ reconnect: bool = True,
65
+ ) -> None:
66
+ self.host = host
67
+ self.port = port
68
+ self._device_id = device_id
69
+ self._connect_timeout = connect_timeout
70
+ self._command_timeout = command_timeout
71
+ self._heartbeat_interval = heartbeat_interval
72
+ self._idle_timeout = idle_timeout
73
+ self._reconnect = reconnect
74
+
75
+ self.device: ScinanDevice | None = (
76
+ ScinanDevice(device_id=device_id) if device_id else None
77
+ )
78
+ self._reader: asyncio.StreamReader | None = None
79
+ self._writer: asyncio.StreamWriter | None = None
80
+ self._write_lock = asyncio.Lock()
81
+ self._connected = False
82
+ self._closing = False
83
+ self._session_tasks: list[asyncio.Task] = []
84
+ self._supervisor: asyncio.Task | None = None
85
+ self._hello: asyncio.Future[str] | None = None
86
+ self._status_waiters: list[asyncio.Future[ScinanStatus]] = []
87
+ self._listeners: list[Listener] = []
88
+ self._message_listeners: list[MessageListener] = []
89
+
90
+ # ------------------------------------------------------------------ API
91
+
92
+ @property
93
+ def device_id(self) -> str | None:
94
+ return self._device_id
95
+
96
+ @property
97
+ def connected(self) -> bool:
98
+ return self._connected
99
+
100
+ async def __aenter__(self) -> ScinanLocalClient:
101
+ await self.connect()
102
+ return self
103
+
104
+ async def __aexit__(self, *exc) -> None:
105
+ await self.close()
106
+
107
+ async def connect(self) -> ScinanDevice:
108
+ """Connect, learn the device id/type, fetch status, start keep-alive."""
109
+ if self._supervisor is not None:
110
+ raise RuntimeError("Already connected")
111
+ self._closing = False
112
+ await self._open_session()
113
+ self._supervisor = asyncio.create_task(self._supervise(), name=f"scinan-{self.host}")
114
+ assert self.device is not None
115
+ return self.device
116
+
117
+ async def close(self) -> None:
118
+ """Close the connection and stop reconnecting."""
119
+ self._closing = True
120
+ if self._supervisor is not None:
121
+ self._supervisor.cancel()
122
+ with contextlib.suppress(asyncio.CancelledError):
123
+ await self._supervisor
124
+ self._supervisor = None
125
+ await self._close_session()
126
+
127
+ def add_listener(self, listener: Listener) -> Callable[[], None]:
128
+ """Call `listener()` on every status or connection change. Returns remover."""
129
+ self._listeners.append(listener)
130
+ return lambda: _discard(self._listeners, listener)
131
+
132
+ def add_message_listener(self, listener: MessageListener) -> Callable[[], None]:
133
+ """Call `listener(message)` for every received line. Returns remover."""
134
+ self._message_listeners.append(listener)
135
+ return lambda: _discard(self._message_listeners, listener)
136
+
137
+ async def request_status(self) -> ScinanStatus:
138
+ """Ask for a full status (S00)."""
139
+ status = await self.send_command(Code.STATUS, "-1")
140
+ assert status is not None
141
+ return status
142
+
143
+ async def set_temperature(self, temperature: float) -> ScinanStatus:
144
+ """Set target temperature (rounded to 0.5, clamped to device limits)."""
145
+ dev = self.device
146
+ data = format_temperature(
147
+ temperature,
148
+ dev.min_temp if dev else 5.0,
149
+ dev.max_temp if dev else 35.0,
150
+ )
151
+ return await self._command(Code.TARGET_TEMPERATURE, data)
152
+
153
+ async def set_power(self, on: bool) -> ScinanStatus:
154
+ return await self._command(Code.POWER, format_bool(on))
155
+
156
+ async def set_away(self, away: bool) -> ScinanStatus:
157
+ return await self._command(Code.AWAY, format_bool(away))
158
+
159
+ async def set_program(self, enabled: bool) -> ScinanStatus:
160
+ return await self._command(Code.PROGRAM, format_bool(enabled))
161
+
162
+ async def set_mode(self, mode: DeviceMode | int) -> ScinanStatus:
163
+ return await self._command(Code.MODE, str(int(mode)))
164
+
165
+ async def send_command(
166
+ self, code: Code | str, data: str, *, wait_for_status: bool = True
167
+ ) -> ScinanStatus | None:
168
+ """Send any command. By default wait for the S00 the device answers with.
169
+
170
+ If no S00 arrives within the timeout, an explicit S00 request is sent
171
+ as a fallback before giving up.
172
+ """
173
+ if not wait_for_status:
174
+ await self._send(code, data)
175
+ return None
176
+ waiter = self._new_status_waiter()
177
+ await self._send(code, data)
178
+ try:
179
+ return await self._wait(waiter)
180
+ except ScinanTimeoutError:
181
+ if str(code) == Code.STATUS:
182
+ raise
183
+ _LOGGER.debug("%s: no status after %s, requesting S00", self.host, code)
184
+ waiter = self._new_status_waiter()
185
+ await self._send(Code.STATUS, "-1")
186
+ return await self._wait(waiter)
187
+
188
+ async def send_poll(self) -> None:
189
+ await self._send(Code.POLL, "1")
190
+
191
+ # ------------------------------------------------------------ internals
192
+
193
+ async def _command(self, code: Code, data: str) -> ScinanStatus:
194
+ status = await self.send_command(code, data)
195
+ assert status is not None
196
+ return status
197
+
198
+ async def _send(self, code: Code | str, data: str) -> None:
199
+ if not self._connected or self._writer is None:
200
+ raise ScinanConnectionError(f"Not connected to {self.host}")
201
+ if not self._device_id:
202
+ raise ScinanConnectionError(f"Device id for {self.host} not known yet")
203
+ line = build_line(self._device_id, code, data)
204
+ _LOGGER.debug("%s >> %s", self.host, line.decode().strip())
205
+ async with self._write_lock:
206
+ try:
207
+ self._writer.write(line)
208
+ await self._writer.drain()
209
+ except (OSError, ConnectionError) as err:
210
+ raise ScinanConnectionError(f"Write to {self.host} failed: {err}") from err
211
+
212
+ def _new_status_waiter(self) -> asyncio.Future[ScinanStatus]:
213
+ fut: asyncio.Future[ScinanStatus] = asyncio.get_running_loop().create_future()
214
+ self._status_waiters.append(fut)
215
+ return fut
216
+
217
+ async def _wait(self, fut: asyncio.Future[ScinanStatus]) -> ScinanStatus:
218
+ try:
219
+ async with asyncio.timeout(self._command_timeout):
220
+ return await fut
221
+ except TimeoutError as err:
222
+ raise ScinanTimeoutError(f"No status from {self.host}") from err
223
+ finally:
224
+ if fut in self._status_waiters:
225
+ self._status_waiters.remove(fut)
226
+
227
+ async def _open_session(self) -> None:
228
+ """Open TCP, wait for hello (if id unknown), fetch first status."""
229
+ try:
230
+ async with asyncio.timeout(self._connect_timeout):
231
+ reader, writer = await asyncio.open_connection(self.host, self.port)
232
+ except (TimeoutError, OSError) as err:
233
+ reason = str(err) or type(err).__name__ # TimeoutError has an empty str()
234
+ raise ScinanConnectionError(
235
+ f"Cannot connect to {self.host}:{self.port}: {reason}"
236
+ ) from err
237
+ _LOGGER.debug("%s: TCP connected", self.host)
238
+ self._reader, self._writer = reader, writer
239
+ self._connected = True
240
+ self._hello = asyncio.get_running_loop().create_future()
241
+ self._session_tasks = [asyncio.create_task(self._read_loop(reader))]
242
+ try:
243
+ if not self._device_id:
244
+ try:
245
+ async with asyncio.timeout(self._connect_timeout):
246
+ await self._hello
247
+ except TimeoutError as err:
248
+ raise ScinanTimeoutError(
249
+ f"{self.host} sent no hello; pass device_id explicitly"
250
+ ) from err
251
+ await self.request_status()
252
+ except BaseException:
253
+ await self._close_session()
254
+ raise
255
+ self._session_tasks.append(asyncio.create_task(self._heartbeat_loop()))
256
+ if self.device:
257
+ self.device.online = True
258
+ self._notify()
259
+
260
+ async def _close_session(self) -> None:
261
+ was_connected = self._connected
262
+ self._connected = False
263
+ tasks, self._session_tasks = self._session_tasks, []
264
+ current = asyncio.current_task()
265
+ for task in tasks:
266
+ if task is not current:
267
+ task.cancel()
268
+ for task in tasks:
269
+ if task is not current:
270
+ with contextlib.suppress(asyncio.CancelledError, Exception):
271
+ await task
272
+ if self._writer is not None:
273
+ self._writer.close()
274
+ with contextlib.suppress(Exception):
275
+ await self._writer.wait_closed()
276
+ self._reader = self._writer = None
277
+ for fut in self._status_waiters:
278
+ if not fut.done():
279
+ fut.set_exception(ScinanConnectionError(f"Connection to {self.host} closed"))
280
+ self._status_waiters.clear()
281
+ if self.device:
282
+ self.device.online = False
283
+ if was_connected:
284
+ _LOGGER.debug("%s: disconnected", self.host)
285
+ self._notify()
286
+
287
+ async def _supervise(self) -> None:
288
+ """Wait for the session to die, then reconnect with backoff."""
289
+ attempt = 0
290
+ while not self._closing:
291
+ if self._connected and self._session_tasks:
292
+ # Wait for the reader to end (EOF, idle timeout or error).
293
+ with contextlib.suppress(Exception):
294
+ await self._session_tasks[0]
295
+ await self._close_session()
296
+ attempt = 0
297
+ if not self._reconnect:
298
+ return
299
+ _LOGGER.info("%s: connection lost, reconnecting", self.host)
300
+ if attempt:
301
+ await asyncio.sleep(self._backoff(attempt))
302
+ attempt += 1
303
+ try:
304
+ await self._open_session()
305
+ _LOGGER.info("%s: reconnected", self.host)
306
+ except ScinanConnectionError as err:
307
+ _LOGGER.debug(
308
+ "%s: reconnect failed (%s), retry in %ss",
309
+ self.host, err, self._backoff(attempt),
310
+ )
311
+
312
+ @staticmethod
313
+ def _backoff(attempt: int) -> float:
314
+ """Delay before reconnect attempt number `attempt + 1` (attempt >= 1)."""
315
+ return _RECONNECT_BACKOFF[min(attempt - 1, len(_RECONNECT_BACKOFF) - 1)]
316
+
317
+ async def _heartbeat_loop(self) -> None:
318
+ while True:
319
+ await asyncio.sleep(self._heartbeat_interval)
320
+ try:
321
+ await self.send_poll()
322
+ except ScinanConnectionError:
323
+ return
324
+
325
+ async def _read_loop(self, reader: asyncio.StreamReader) -> None:
326
+ buf = b""
327
+ loop = asyncio.get_running_loop()
328
+ last_data = loop.time()
329
+ while True:
330
+ timeout = _FLUSH_PARTIAL_AFTER if buf else self._idle_timeout
331
+ try:
332
+ async with asyncio.timeout(timeout):
333
+ chunk = await reader.read(4096)
334
+ except TimeoutError:
335
+ if buf:
336
+ # Unterminated line (some firmwares omit CRLF on the hello).
337
+ self._handle_raw(buf)
338
+ buf = b""
339
+ continue
340
+ if loop.time() - last_data >= self._idle_timeout:
341
+ _LOGGER.debug("%s: idle for %ss", self.host, self._idle_timeout)
342
+ return
343
+ continue
344
+ if not chunk:
345
+ if buf:
346
+ self._handle_raw(buf)
347
+ _LOGGER.debug("%s: EOF", self.host)
348
+ return
349
+ last_data = loop.time()
350
+ buf += chunk
351
+ *lines, buf = _LINE_SPLIT_RE.split(buf)
352
+ for raw in lines:
353
+ if raw:
354
+ self._handle_raw(raw)
355
+
356
+ def _handle_raw(self, raw: bytes) -> None:
357
+ line = raw.decode(errors="replace").strip()
358
+ if not line:
359
+ return
360
+ _LOGGER.debug("%s << %s", self.host, line)
361
+ try:
362
+ msg = parse_line(line)
363
+ except ScinanProtocolError:
364
+ _LOGGER.debug("%s: ignoring line %r", self.host, line)
365
+ return
366
+ self._handle_message(msg)
367
+
368
+ def _handle_message(self, msg: Message) -> None:
369
+ if self._device_id is None:
370
+ self._device_id = msg.device_id
371
+ elif msg.device_id != self._device_id:
372
+ _LOGGER.warning(
373
+ "%s: message for %s, expected %s", self.host, msg.device_id, self._device_id
374
+ )
375
+ return
376
+ if self.device is None:
377
+ self.device = ScinanDevice(device_id=msg.device_id)
378
+
379
+ for listener in list(self._message_listeners):
380
+ try:
381
+ listener(msg)
382
+ except Exception: # noqa: BLE001
383
+ _LOGGER.exception("Message listener failed")
384
+
385
+ if msg.is_hello:
386
+ with contextlib.suppress(ValueError):
387
+ self.device.type = int(msg.data)
388
+ if self._hello and not self._hello.done():
389
+ self._hello.set_result(msg.data)
390
+ return
391
+
392
+ if msg.code == Code.STATUS:
393
+ try:
394
+ status = ScinanStatus.parse(msg.data)
395
+ except ScinanProtocolError as err:
396
+ _LOGGER.debug("%s: bad status: %s", self.host, err)
397
+ return
398
+ self.device.update_status(status)
399
+ self.device.online = True
400
+ waiters, self._status_waiters = self._status_waiters, []
401
+ for fut in waiters:
402
+ if not fut.done():
403
+ fut.set_result(status)
404
+ self._notify()
405
+
406
+ def _notify(self) -> None:
407
+ for listener in list(self._listeners):
408
+ try:
409
+ listener()
410
+ except Exception: # noqa: BLE001
411
+ _LOGGER.exception("Listener failed")
412
+
413
+
414
+ def _discard(items: list, item: object) -> None:
415
+ """Remove item if present (listener removers may be called more than once)."""
416
+ with contextlib.suppress(ValueError):
417
+ items.remove(item)
pyscinan/models.py ADDED
@@ -0,0 +1,158 @@
1
+ """Device model shared by the local and cloud clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import UTC, datetime
7
+
8
+ from .const import DEVICE_TEMP_MAX, DEVICE_TEMP_MIN, DeviceMode
9
+ from .exceptions import ScinanProtocolError
10
+
11
+
12
+ def _int(values: list[str], idx: int) -> int | None:
13
+ try:
14
+ return int(float(values[idx]))
15
+ except (IndexError, ValueError):
16
+ return None
17
+
18
+
19
+ def _float(values: list[str], idx: int) -> float | None:
20
+ try:
21
+ return float(values[idx])
22
+ except (IndexError, ValueError):
23
+ return None
24
+
25
+
26
+ def _bool(values: list[str], idx: int) -> bool | None:
27
+ val = _int(values, idx)
28
+ return None if val is None else val == 1
29
+
30
+
31
+ @dataclass(slots=True)
32
+ class ScinanStatus:
33
+ """A parsed S00 status string.
34
+
35
+ Field order (local / direct mode):
36
+ power, current_temp, target_temp, unit, away, program,
37
+ fan_mode, run_mode, system_mode[, min_temp, max_temp, system_mode_type]
38
+
39
+ The cloud status string has one extra leading field (timestamp in ms).
40
+ """
41
+
42
+ raw: str
43
+ power: bool | None = None
44
+ current_temperature: float | None = None
45
+ target_temperature: float | None = None
46
+ unit: int | None = None # 0 = Celsius
47
+ away: bool | None = None
48
+ program: bool | None = None
49
+ fan_mode: int | None = None
50
+ run_mode: int | None = None
51
+ system_mode: int | None = None
52
+ min_temp: float | None = None
53
+ max_temp: float | None = None
54
+ system_mode_type: int | None = None
55
+ extra: list[str] = field(default_factory=list)
56
+ timestamp: datetime | None = None # only from cloud
57
+
58
+ @classmethod
59
+ def parse(cls, data: str, *, cloud: bool = False) -> ScinanStatus:
60
+ """Parse the comma separated status payload."""
61
+ values = [v.strip() for v in data.strip().split(",")]
62
+ timestamp = None
63
+ if cloud:
64
+ if not values:
65
+ raise ScinanProtocolError(f"Empty cloud status: {data!r}")
66
+ try:
67
+ timestamp = datetime.fromtimestamp(int(values[0]) / 1000, tz=UTC)
68
+ except ValueError:
69
+ timestamp = None
70
+ values = values[1:]
71
+ if len(values) < 3:
72
+ raise ScinanProtocolError(f"Status too short: {data!r}")
73
+ status = cls(
74
+ raw=data,
75
+ power=_bool(values, 0),
76
+ current_temperature=_float(values, 1),
77
+ target_temperature=_float(values, 2),
78
+ unit=_int(values, 3),
79
+ away=_bool(values, 4),
80
+ program=_bool(values, 5),
81
+ fan_mode=_int(values, 6),
82
+ run_mode=_int(values, 7),
83
+ system_mode=_int(values, 8),
84
+ min_temp=_float(values, 9),
85
+ max_temp=_float(values, 10),
86
+ system_mode_type=_int(values, 11),
87
+ extra=values[12:],
88
+ timestamp=timestamp,
89
+ )
90
+ if status.current_temperature is None or status.target_temperature is None:
91
+ raise ScinanProtocolError(f"Status without temperatures: {data!r}")
92
+ return status
93
+
94
+
95
+ @dataclass(slots=True)
96
+ class ScinanDevice:
97
+ """A thermostat, as seen by either client."""
98
+
99
+ device_id: str
100
+ name: str | None = None
101
+ type: int | None = None
102
+ company_id: str | None = None
103
+ online: bool = False
104
+ status: ScinanStatus | None = None
105
+ last_updated: datetime | None = None
106
+
107
+ def update_status(self, status: ScinanStatus) -> None:
108
+ """Store a new status."""
109
+ self.status = status
110
+ self.last_updated = status.timestamp or datetime.now(UTC)
111
+
112
+ # Convenience accessors -------------------------------------------------
113
+
114
+ @property
115
+ def is_on(self) -> bool | None:
116
+ return self.status.power if self.status else None
117
+
118
+ @property
119
+ def away(self) -> bool | None:
120
+ return self.status.away if self.status else None
121
+
122
+ @property
123
+ def current_temperature(self) -> float | None:
124
+ return self.status.current_temperature if self.status else None
125
+
126
+ @property
127
+ def target_temperature(self) -> float | None:
128
+ return self.status.target_temperature if self.status else None
129
+
130
+ @property
131
+ def min_temp(self) -> float:
132
+ return (self.status.min_temp if self.status else None) or DEVICE_TEMP_MIN
133
+
134
+ @property
135
+ def max_temp(self) -> float:
136
+ return (self.status.max_temp if self.status else None) or DEVICE_TEMP_MAX
137
+
138
+ @property
139
+ def mode(self) -> DeviceMode | None:
140
+ """System mode as enum, None if unknown."""
141
+ if not self.status or self.status.system_mode is None:
142
+ return None
143
+ try:
144
+ return DeviceMode(self.status.system_mode)
145
+ except ValueError:
146
+ return None
147
+
148
+ @property
149
+ def is_heating(self) -> bool:
150
+ """Best guess: the protocol has no confirmed 'relay on' field yet."""
151
+ return bool(
152
+ self.online
153
+ and self.is_on
154
+ and not self.away
155
+ and self.current_temperature is not None
156
+ and self.target_temperature is not None
157
+ and self.current_temperature < self.target_temperature
158
+ )
pyscinan/protocol.py ADDED
@@ -0,0 +1,64 @@
1
+ """The plain-text line protocol spoken on TCP port 2000.
2
+
3
+ Every line is ``/<DEVICE_ID>/<CODE>/<SENSOR_TYPE>/<DATA>`` terminated by CRLF.
4
+ On connect the device sends a hello: ``/<DEVICE_ID>/type/1/<device type>``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass
11
+
12
+ from .const import DEVICE_TEMP_MAX, DEVICE_TEMP_MIN, LOCAL_SENSOR_TYPE, Code
13
+ from .exceptions import ScinanProtocolError
14
+
15
+ DEVICE_ID_RE = re.compile(r"^[0-9A-Za-z]{16}$")
16
+ HELLO_CODE = "type"
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class Message:
21
+ """One protocol line."""
22
+
23
+ device_id: str
24
+ code: str
25
+ sensor_type: str
26
+ data: str
27
+
28
+ @property
29
+ def is_hello(self) -> bool:
30
+ return self.code == HELLO_CODE
31
+
32
+ def __str__(self) -> str:
33
+ return f"/{self.device_id}/{self.code}/{self.sensor_type}/{self.data}"
34
+
35
+
36
+ def parse_line(line: str) -> Message:
37
+ """Parse one received line."""
38
+ line = line.strip()
39
+ parts = line.split("/", 4)
40
+ if len(parts) != 5 or parts[0] != "" or not DEVICE_ID_RE.match(parts[1]):
41
+ raise ScinanProtocolError(f"Unrecognised line: {line!r}")
42
+ return Message(device_id=parts[1], code=parts[2], sensor_type=parts[3], data=parts[4])
43
+
44
+
45
+ def build_line(device_id: str, code: str | Code, data: str) -> bytes:
46
+ """Build one line to send."""
47
+ if not DEVICE_ID_RE.match(device_id):
48
+ raise ValueError(f"Invalid device id: {device_id!r}")
49
+ code = str(code)
50
+ if not code.upper().startswith("S"):
51
+ code = f"S{code}"
52
+ return f"/{device_id}/{code}/{LOCAL_SENSOR_TYPE}/{data}\r\n".encode()
53
+
54
+
55
+ def format_temperature(value: float, minimum: float = DEVICE_TEMP_MIN,
56
+ maximum: float = DEVICE_TEMP_MAX) -> str:
57
+ """Clamp to limits and round to 0.5 (what the app sends, e.g. '21.5', '05.0')."""
58
+ value = min(max(float(value), minimum), maximum)
59
+ value = round(value * 2) / 2
60
+ return f"{value:04.1f}"
61
+
62
+
63
+ def format_bool(value: bool) -> str:
64
+ return "1" if value else "0"
pyscinan/py.typed ADDED
File without changes
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyscinan
3
+ Version: 0.1.0
4
+ Summary: Async client for Saswell / Scinan Wi-Fi thermostats (local TCP and cloud API)
5
+ Project-URL: Homepage, https://github.com/skarbo/pyscinan
6
+ Project-URL: Issues, https://github.com/skarbo/pyscinan/issues
7
+ Project-URL: Changelog, https://github.com/skarbo/pyscinan/blob/main/CHANGELOG.md
8
+ Author: Kris Skarbo
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: asyncio,home-assistant,saswell,scinan,thermostat
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Home Automation
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Requires-Dist: aiohttp>=3.9
24
+ Description-Content-Type: text/markdown
25
+
26
+ # pyscinan
27
+
28
+ Async Python library for Saswell (Scinan platform) Wi-Fi thermostats.
29
+
30
+ - **Local**: talks directly to the thermostat over your network (TCP port 2000). No cloud, instant push
31
+ updates, heartbeat and automatic reconnect.
32
+ - **Cloud**: the Saswell v2.0 API used by the Saswell "Thermostat" app.
33
+
34
+ Both clients fill the same `ScinanDevice` model. Used by the
35
+ [Scinan Saswell Thermostat](https://github.com/skarbo/hass-scinan-thermostat) Home Assistant integration.
36
+
37
+ Tested with the Saswell SAS920FHL-7W-WIFI (electric floor heating). Other thermostats using a Saswell
38
+ Thermostat app (for example SAS922WHL-7W-S-WIFI and Prosmart PST50W) are known to work with the cloud API.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install pyscinan
44
+ ```
45
+
46
+ Requires Python 3.12 or newer.
47
+
48
+ ## Local
49
+
50
+ The thermostat must already be on your Wi-Fi (set it up with the Thermostat app). Give it a fixed IP address;
51
+ it can't be discovered automatically.
52
+
53
+ ```python
54
+ import asyncio
55
+ from pyscinan import DeviceMode, ScinanLocalClient
56
+
57
+ async def main():
58
+ async with ScinanLocalClient("192.168.1.50") as client:
59
+ dev = client.device
60
+ print(dev.device_id, dev.current_temperature, dev.target_temperature, dev.mode)
61
+
62
+ client.add_listener(lambda: print("update:", dev.current_temperature, dev.target_temperature))
63
+
64
+ await client.set_temperature(21.5)
65
+ await client.set_mode(DeviceMode.COMFORT)
66
+ await client.set_away(True) # "off" on floor heating thermostats
67
+ await asyncio.sleep(60) # pushes arrive every 15 s and on every change
68
+
69
+ asyncio.run(main())
70
+ ```
71
+
72
+ Every command returns the status the thermostat answers with. A command the thermostat ignores (for example
73
+ power on the SAS920FHL) returns the unchanged status, so compare it with what you asked for.
74
+
75
+ ## Cloud
76
+
77
+ ```python
78
+ from pyscinan import ScinanCloudClient
79
+
80
+ async with ScinanCloudClient("email@example.com", "password") as cloud:
81
+ devices = await cloud.update_devices()
82
+ for dev in devices.values():
83
+ print(dev.device_id, dev.name, dev.online, dev.target_temperature)
84
+ await cloud.set_temperature(dev.device_id, 21.5)
85
+ ```
86
+
87
+ Pass `session=` to reuse an `aiohttp.ClientSession`. Note that the Saswell cloud only supports plain HTTP.
88
+
89
+ ## Command line
90
+
91
+ ```bash
92
+ pyscinan status 192.168.1.50
93
+ pyscinan listen 192.168.1.50 --seconds 60
94
+ pyscinan settemp 192.168.1.50 21.5
95
+ pyscinan away 192.168.1.50 on
96
+ pyscinan mode 192.168.1.50 1 # 0 Comfort, 1 Auto (schedule), 2 Day or night
97
+ pyscinan cloud-list email@example.com # password from $SCINAN_PASSWORD or a prompt
98
+ pyscinan --help
99
+ ```
100
+
101
+ ## Protocol
102
+
103
+ See [PROTOCOL.md](PROTOCOL.md) for everything known about the local protocol and the cloud API.
104
+
105
+ ## Development
106
+
107
+ ```bash
108
+ uv sync
109
+ uv run pytest
110
+ uv run ruff check .
111
+ ```
112
+
113
+ The tests use a fake thermostat (TCP) and a fake cloud server, so no hardware or account is needed.
114
+ `scripts/hw_settings_test.py` runs against a real thermostat and changes its settings (then restores them).
115
+
116
+ ## Disclaimer
117
+
118
+ Not affiliated with Saswell or Scinan. Use at your own risk.
@@ -0,0 +1,15 @@
1
+ pyscinan/__init__.py,sha256=fVz-e268A_7kCgZXxLSKm3LQGc6dNfmAJkHby9G9JKI,762
2
+ pyscinan/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ pyscinan/cli.py,sha256=OqPy4SSUlGV6FkNBXjlysBnm4rQJvOTRQGuyZoEzbSw,4247
4
+ pyscinan/cloud.py,sha256=XtQHWlP0dIuC_kQ_orf47tQF1qHdoIGyAurTCoCom40,9897
5
+ pyscinan/const.py,sha256=wNXvq-R6JiP944kbHzHQa1TTrL1aOvByhbAmadRJWLM,1638
6
+ pyscinan/exceptions.py,sha256=hvvKY3WXd9mY5dhF7qOwHpvZp3TerxWQgKg3R33Fiq0,691
7
+ pyscinan/local.py,sha256=VTip9GSASdtE0lAz-m2qXQ21LPFzH1OV5kClpI0bXBA,15929
8
+ pyscinan/models.py,sha256=g8GvEi20l3w-i4von5wJX40uxOODwXcfuKoVMnOa8FI,5118
9
+ pyscinan/protocol.py,sha256=KnDWQwFHnq_IpZs-WJuBDjas4Y5nujfT3A4U2pNAHPY,1983
10
+ pyscinan/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ pyscinan-0.1.0.dist-info/METADATA,sha256=ADYAdLJnULbS_KVnBB-MB8NUjiksFfz19PboKjG2dLA,4037
12
+ pyscinan-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ pyscinan-0.1.0.dist-info/entry_points.txt,sha256=yMD5J_qRdxl29ad8BYcW-Sba_OMtf21GWfUXtwp1WXg,47
14
+ pyscinan-0.1.0.dist-info/licenses/LICENSE,sha256=0fdnvww4OY8NTzD5qgadYynJdisRO-s_f1NReEWddro,1068
15
+ pyscinan-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pyscinan = pyscinan.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kris Skarbo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.