aiorefoss 1.0.3__tar.gz
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.
- aiorefoss-1.0.3/LICENSE +21 -0
- aiorefoss-1.0.3/PKG-INFO +87 -0
- aiorefoss-1.0.3/README.md +57 -0
- aiorefoss-1.0.3/aiorefoss/__init__.py +36 -0
- aiorefoss-1.0.3/aiorefoss/common.py +150 -0
- aiorefoss-1.0.3/aiorefoss/const.py +37 -0
- aiorefoss-1.0.3/aiorefoss/exceptions.py +53 -0
- aiorefoss-1.0.3/aiorefoss/json.py +56 -0
- aiorefoss-1.0.3/aiorefoss/rpc_device/__init__.py +5 -0
- aiorefoss-1.0.3/aiorefoss/rpc_device/device.py +427 -0
- aiorefoss-1.0.3/aiorefoss/rpc_device/wsrpc.py +598 -0
- aiorefoss-1.0.3/aiorefoss.egg-info/PKG-INFO +87 -0
- aiorefoss-1.0.3/aiorefoss.egg-info/SOURCES.txt +17 -0
- aiorefoss-1.0.3/aiorefoss.egg-info/dependency_links.txt +1 -0
- aiorefoss-1.0.3/aiorefoss.egg-info/requires.txt +5 -0
- aiorefoss-1.0.3/aiorefoss.egg-info/top_level.txt +3 -0
- aiorefoss-1.0.3/pyproject.toml +40 -0
- aiorefoss-1.0.3/setup.cfg +4 -0
- aiorefoss-1.0.3/setup.py +17 -0
aiorefoss-1.0.3/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Refoss
|
|
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.
|
aiorefoss-1.0.3/PKG-INFO
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: aiorefoss
|
|
3
|
+
Version: 1.0.3
|
|
4
|
+
Summary: Asynchronous Python library for Refoss smart devices
|
|
5
|
+
Author: ashionky
|
|
6
|
+
Author-email: ashionky <495519020@qq.com>
|
|
7
|
+
Project-URL: Homepage, https://github.com/ashionky/aiorefoss
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/ashionky/aiorefoss/issues
|
|
9
|
+
Project-URL: Repository, https://github.com/ashionky/aiorefoss
|
|
10
|
+
Keywords: refoss,homeassistant,iot,smart-home,automation
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Topic :: Home Automation
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.12
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: aiohttp>=3.9.0
|
|
24
|
+
Requires-Dist: yarl>=1.9.0
|
|
25
|
+
Provides-Extra: fastjson
|
|
26
|
+
Requires-Dist: orjson>=3.9.0; extra == "fastjson"
|
|
27
|
+
Dynamic: author
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
Dynamic: requires-python
|
|
30
|
+
|
|
31
|
+
# aiorefoss
|
|
32
|
+
|
|
33
|
+
Asynchronous Python library for Refoss smart devices, designed for Home Assistant integration.
|
|
34
|
+
|
|
35
|
+
## Features
|
|
36
|
+
|
|
37
|
+
- Async WebSocket connection
|
|
38
|
+
- Device authentication support for new firmware (EM16P v3.1.11+)
|
|
39
|
+
- Automatic auth challenge handling
|
|
40
|
+
- Real-time status updates
|
|
41
|
+
- Device configuration management
|
|
42
|
+
- Cross-platform JSON support (orjson with stdlib fallback)
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install aiorefoss
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
With faster JSON support:
|
|
51
|
+
```bash
|
|
52
|
+
pip install aiorefoss[fastjson]
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Quick Start
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import asyncio
|
|
59
|
+
from aiorefoss.rpc_device.device import RpcDevice
|
|
60
|
+
from aiorefoss.common import process_ip_or_options
|
|
61
|
+
|
|
62
|
+
async def main():
|
|
63
|
+
options = await process_ip_or_options("192.168.1.100")
|
|
64
|
+
device = await RpcDevice.create(None, options)
|
|
65
|
+
await device.initialize()
|
|
66
|
+
print(f"Device model: {device.model}")
|
|
67
|
+
print(f"Firmware version: {device.firmware_version}")
|
|
68
|
+
await device.shutdown()
|
|
69
|
+
|
|
70
|
+
asyncio.run(main())
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Requirements
|
|
74
|
+
|
|
75
|
+
- Python 3.12+
|
|
76
|
+
- aiohttp
|
|
77
|
+
- yarl
|
|
78
|
+
- orjson (optional, for better performance)
|
|
79
|
+
|
|
80
|
+
## License
|
|
81
|
+
|
|
82
|
+
MIT
|
|
83
|
+
|
|
84
|
+
## Support
|
|
85
|
+
|
|
86
|
+
- Email: support@refoss.net
|
|
87
|
+
- Issues: https://github.com/ashionky/aiorefoss/issues
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# aiorefoss
|
|
2
|
+
|
|
3
|
+
Asynchronous Python library for Refoss smart devices, designed for Home Assistant integration.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- Async WebSocket connection
|
|
8
|
+
- Device authentication support for new firmware (EM16P v3.1.11+)
|
|
9
|
+
- Automatic auth challenge handling
|
|
10
|
+
- Real-time status updates
|
|
11
|
+
- Device configuration management
|
|
12
|
+
- Cross-platform JSON support (orjson with stdlib fallback)
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install aiorefoss
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
With faster JSON support:
|
|
21
|
+
```bash
|
|
22
|
+
pip install aiorefoss[fastjson]
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Quick Start
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import asyncio
|
|
29
|
+
from aiorefoss.rpc_device.device import RpcDevice
|
|
30
|
+
from aiorefoss.common import process_ip_or_options
|
|
31
|
+
|
|
32
|
+
async def main():
|
|
33
|
+
options = await process_ip_or_options("192.168.1.100")
|
|
34
|
+
device = await RpcDevice.create(None, options)
|
|
35
|
+
await device.initialize()
|
|
36
|
+
print(f"Device model: {device.model}")
|
|
37
|
+
print(f"Firmware version: {device.firmware_version}")
|
|
38
|
+
await device.shutdown()
|
|
39
|
+
|
|
40
|
+
asyncio.run(main())
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Requirements
|
|
44
|
+
|
|
45
|
+
- Python 3.12+
|
|
46
|
+
- aiohttp
|
|
47
|
+
- yarl
|
|
48
|
+
- orjson (optional, for better performance)
|
|
49
|
+
|
|
50
|
+
## License
|
|
51
|
+
|
|
52
|
+
MIT
|
|
53
|
+
|
|
54
|
+
## Support
|
|
55
|
+
|
|
56
|
+
- Email: support@refoss.net
|
|
57
|
+
- Issues: https://github.com/ashionky/aiorefoss/issues
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Refoss asynchronous Python library for Home Assistant.
|
|
2
|
+
|
|
3
|
+
This library provides async support for Refoss smart devices using WebSocket.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__version__ = "1.0.3"
|
|
7
|
+
|
|
8
|
+
from .common import ConnectionOptions, IpOrOptionsType, get_info, process_ip_or_options
|
|
9
|
+
from .exceptions import (
|
|
10
|
+
DeviceConnectionError,
|
|
11
|
+
DeviceConnectionTimeoutError,
|
|
12
|
+
InvalidAuthError,
|
|
13
|
+
MacAddressMismatchError,
|
|
14
|
+
NotInitialized,
|
|
15
|
+
RefossError,
|
|
16
|
+
RpcCallError,
|
|
17
|
+
WrongRefoss,
|
|
18
|
+
)
|
|
19
|
+
from .rpc_device.device import RpcDevice, RpcUpdateType
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"ConnectionOptions",
|
|
23
|
+
"DeviceConnectionError",
|
|
24
|
+
"DeviceConnectionTimeoutError",
|
|
25
|
+
"InvalidAuthError",
|
|
26
|
+
"IpOrOptionsType",
|
|
27
|
+
"MacAddressMismatchError",
|
|
28
|
+
"NotInitialized",
|
|
29
|
+
"RefossError",
|
|
30
|
+
"RpcCallError",
|
|
31
|
+
"RpcDevice",
|
|
32
|
+
"RpcUpdateType",
|
|
33
|
+
"WrongRefoss",
|
|
34
|
+
"get_info",
|
|
35
|
+
"process_ip_or_options",
|
|
36
|
+
]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Common code for Refoss library."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import ipaddress
|
|
7
|
+
import logging
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from socket import gethostbyname
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
from aiohttp import BasicAuth, ClientSession, ClientTimeout
|
|
13
|
+
from yarl import URL
|
|
14
|
+
|
|
15
|
+
from .const import (
|
|
16
|
+
CONNECT_ERRORS,
|
|
17
|
+
DEFAULT_HTTP_PORT,
|
|
18
|
+
DEVICE_IO_TIMEOUT,
|
|
19
|
+
)
|
|
20
|
+
from .exceptions import (
|
|
21
|
+
DeviceConnectionError,
|
|
22
|
+
DeviceConnectionTimeoutError,
|
|
23
|
+
MacAddressMismatchError,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_LOGGER = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
DEVICE_IO_TIMEOUT_CLIENT_TIMEOUT = ClientTimeout(total=DEVICE_IO_TIMEOUT)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(slots=True)
|
|
32
|
+
class ConnectionOptions:
|
|
33
|
+
"""Refoss options for connection."""
|
|
34
|
+
|
|
35
|
+
ip_address: str
|
|
36
|
+
username: str | None = None
|
|
37
|
+
password: str | None = None
|
|
38
|
+
device_mac: str | None = None
|
|
39
|
+
port: int = DEFAULT_HTTP_PORT
|
|
40
|
+
auth: BasicAuth | None = None
|
|
41
|
+
|
|
42
|
+
def __post_init__(self) -> None:
|
|
43
|
+
"""Call after initialization."""
|
|
44
|
+
if self.username is not None:
|
|
45
|
+
if self.password is None:
|
|
46
|
+
raise ValueError("Supply both username and password")
|
|
47
|
+
object.__setattr__(self, "auth", BasicAuth(self.username, self.password))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
IpOrOptionsType = str | ConnectionOptions
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
async def process_ip_or_options(ip_or_options: IpOrOptionsType) -> ConnectionOptions:
|
|
54
|
+
"""Return ConnectionOptions class from ip str or ConnectionOptions."""
|
|
55
|
+
if isinstance(ip_or_options, str):
|
|
56
|
+
options = ConnectionOptions(ip_or_options)
|
|
57
|
+
else:
|
|
58
|
+
options = ip_or_options
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
ipaddress.ip_address(options.ip_address)
|
|
62
|
+
except ValueError:
|
|
63
|
+
loop = asyncio.get_running_loop()
|
|
64
|
+
options.ip_address = await loop.run_in_executor(
|
|
65
|
+
None, gethostbyname, options.ip_address
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
return options
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
async def get_info(
|
|
72
|
+
aiohttp_session: ClientSession,
|
|
73
|
+
ip_address: str,
|
|
74
|
+
device_mac: str | None = None,
|
|
75
|
+
port: int = DEFAULT_HTTP_PORT,
|
|
76
|
+
) -> dict[str, Any]:
|
|
77
|
+
"""Get info from device through REST call."""
|
|
78
|
+
url = URL.build(
|
|
79
|
+
scheme="http",
|
|
80
|
+
host=ip_address,
|
|
81
|
+
port=port,
|
|
82
|
+
path="/rpc/Refoss.DeviceInfo.Get",
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
async with aiohttp_session.get(
|
|
87
|
+
url,
|
|
88
|
+
raise_for_status=True,
|
|
89
|
+
timeout=DEVICE_IO_TIMEOUT_CLIENT_TIMEOUT,
|
|
90
|
+
) as resp:
|
|
91
|
+
result: dict[str, Any] = await resp.json()
|
|
92
|
+
except TimeoutError as err:
|
|
93
|
+
error = DeviceConnectionTimeoutError(err)
|
|
94
|
+
_LOGGER.warning(
|
|
95
|
+
"host %s:%s: Connection timeout while fetching device info: %r",
|
|
96
|
+
ip_address,
|
|
97
|
+
port,
|
|
98
|
+
error,
|
|
99
|
+
)
|
|
100
|
+
raise error from err
|
|
101
|
+
except CONNECT_ERRORS as err:
|
|
102
|
+
error = DeviceConnectionError(err)
|
|
103
|
+
_LOGGER.warning(
|
|
104
|
+
"host %s:%s: Connection error while fetching device info: %r",
|
|
105
|
+
ip_address,
|
|
106
|
+
port,
|
|
107
|
+
error,
|
|
108
|
+
)
|
|
109
|
+
raise error from err
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
mac = result["mac"]
|
|
113
|
+
except KeyError as err:
|
|
114
|
+
error = DeviceConnectionError(f"Device response missing 'mac' field: {result}")
|
|
115
|
+
_LOGGER.error(
|
|
116
|
+
"host %s:%s: Invalid device info response, missing mac field: %s",
|
|
117
|
+
ip_address,
|
|
118
|
+
port,
|
|
119
|
+
result,
|
|
120
|
+
)
|
|
121
|
+
raise error from err
|
|
122
|
+
|
|
123
|
+
if device_mac and device_mac != mac:
|
|
124
|
+
error = MacAddressMismatchError(f"Input MAC: {device_mac}, Refoss MAC: {mac}")
|
|
125
|
+
_LOGGER.warning(
|
|
126
|
+
"host %s:%s: MAC address mismatch: expected=%s, got=%s",
|
|
127
|
+
ip_address,
|
|
128
|
+
port,
|
|
129
|
+
device_mac,
|
|
130
|
+
mac,
|
|
131
|
+
)
|
|
132
|
+
raise error
|
|
133
|
+
|
|
134
|
+
return result
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def fmt_macaddress(macaddress: str):
|
|
138
|
+
"""internal component macaddress representation (lowercase without dots/colons)"""
|
|
139
|
+
return macaddress.replace(":", "").lower()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def mac_address_from_name(name: str) -> str | None:
|
|
143
|
+
"""Convert a name to a mac address."""
|
|
144
|
+
mac = name.partition(".")[0].partition("-")[-1]
|
|
145
|
+
return mac.lower() if len(mac) == 12 else None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def get_info_auth(info: dict[str, Any]) -> bool:
|
|
149
|
+
"""Return true if device has authorization enabled."""
|
|
150
|
+
return cast(bool, info.get("auth_en"))
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Constants for refoss."""
|
|
2
|
+
|
|
3
|
+
from enum import Enum
|
|
4
|
+
|
|
5
|
+
import aiohttp
|
|
6
|
+
|
|
7
|
+
from .exceptions import DeviceConnectionError
|
|
8
|
+
|
|
9
|
+
CONNECT_ERRORS = (aiohttp.ClientError, DeviceConnectionError, OSError)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class UndefinedType(Enum):
|
|
13
|
+
"""Singleton type for use with not set sentinel values."""
|
|
14
|
+
|
|
15
|
+
_singleton = 0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
UNDEFINED = UndefinedType._singleton
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# Timeout used for Device IO
|
|
22
|
+
DEVICE_IO_TIMEOUT = 10.0
|
|
23
|
+
|
|
24
|
+
# Timeout used for polling
|
|
25
|
+
DEVICE_POLL_TIMEOUT = 20.0
|
|
26
|
+
|
|
27
|
+
# Timeout used for initial connection calls
|
|
28
|
+
# after the connection has been established
|
|
29
|
+
DEVICE_INIT_TIMEOUT = 30.0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
WS_HEARTBEAT = 30
|
|
33
|
+
|
|
34
|
+
# Notification sent by device in case of WebSocket close
|
|
35
|
+
NOTIFY_WS_CLOSED = "NotifyWebSocketClosed"
|
|
36
|
+
|
|
37
|
+
DEFAULT_HTTP_PORT = 80
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Refoss exceptions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class RefossError(Exception):
|
|
7
|
+
"""Base class for aioRefoss errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ConnectionClosed(RefossError):
|
|
11
|
+
"""Exception raised when the connection is closed."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class InvalidMessage(RefossError):
|
|
15
|
+
"""Exception raised when an invalid message is received."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NotInitialized(RefossError):
|
|
19
|
+
"""Raised if device is not initialized."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class WrongRefoss(RefossError):
|
|
23
|
+
"""Exception raised to indicate wrong Refoss generation."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# Errors to be handled by the caller:
|
|
27
|
+
# Errors that are expected to happen and should be handled by the caller.
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class DeviceConnectionError(RefossError):
|
|
31
|
+
"""Exception indicates device connection errors."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class DeviceConnectionTimeoutError(DeviceConnectionError):
|
|
35
|
+
"""Exception indicates device connection timeout errors."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class InvalidAuthError(RefossError):
|
|
39
|
+
"""Raised to indicate invalid or missing authentication error."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class MacAddressMismatchError(RefossError):
|
|
43
|
+
"""Raised if input MAC address does not match the device MAC address."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class RpcCallError(RefossError):
|
|
47
|
+
"""Raised to indicate errors in RPC call."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, code: int, message: str = "") -> None:
|
|
50
|
+
"""Initialize JSON RPC errors."""
|
|
51
|
+
self.code = code
|
|
52
|
+
self.message = message
|
|
53
|
+
super().__init__(code, message)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""JSON helper.
|
|
2
|
+
|
|
3
|
+
Uses orjson for better performance if available, falls back to standard library json.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import orjson
|
|
11
|
+
|
|
12
|
+
JSONDecodeError = orjson.JSONDecodeError
|
|
13
|
+
json_loads = orjson.loads
|
|
14
|
+
_has_orjson = True
|
|
15
|
+
|
|
16
|
+
def json_encoder_default(obj: Any) -> Any:
|
|
17
|
+
"""Convert objects for orjson."""
|
|
18
|
+
if isinstance(obj, set | tuple):
|
|
19
|
+
return list(obj)
|
|
20
|
+
raise TypeError
|
|
21
|
+
|
|
22
|
+
def json_dumps(data: Any) -> str:
|
|
23
|
+
"""Dump json string using orjson."""
|
|
24
|
+
return orjson.dumps(
|
|
25
|
+
data,
|
|
26
|
+
option=orjson.OPT_NON_STR_KEYS,
|
|
27
|
+
default=json_encoder_default,
|
|
28
|
+
).decode("utf-8")
|
|
29
|
+
|
|
30
|
+
def json_bytes(data: Any) -> bytes:
|
|
31
|
+
"""Dump json bytes using orjson."""
|
|
32
|
+
return orjson.dumps(
|
|
33
|
+
data,
|
|
34
|
+
option=orjson.OPT_NON_STR_KEYS,
|
|
35
|
+
default=json_encoder_default,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
except ImportError:
|
|
39
|
+
# Fallback to standard library json
|
|
40
|
+
JSONDecodeError = json.JSONDecodeError
|
|
41
|
+
json_loads = json.loads
|
|
42
|
+
_has_orjson = False
|
|
43
|
+
|
|
44
|
+
def _json_encoder_default(obj: Any) -> Any:
|
|
45
|
+
"""Convert objects for standard json."""
|
|
46
|
+
if isinstance(obj, set | tuple):
|
|
47
|
+
return list(obj)
|
|
48
|
+
raise TypeError
|
|
49
|
+
|
|
50
|
+
def json_dumps(data: Any) -> str:
|
|
51
|
+
"""Dump json string using standard library json."""
|
|
52
|
+
return json.dumps(data, default=_json_encoder_default)
|
|
53
|
+
|
|
54
|
+
def json_bytes(data: Any) -> bytes:
|
|
55
|
+
"""Dump json bytes using standard library json."""
|
|
56
|
+
return json.dumps(data, default=_json_encoder_default).encode("utf-8")
|