aidlabsdk 2.5.0__py3-none-win_amd64.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.
aidlab/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """
2
+ Aidlab Python SDK
3
+ """
4
+
5
+ from .activity_type import ActivityType
6
+ from .aidlab_error import AidlabError, AidlabErrorCode
7
+ from .aidlab_manager import AidlabManager
8
+ from .body_position import BodyPosition
9
+ from .data_type import DataType
10
+ from .device import Device
11
+ from .device_delegate import DeviceDelegate
12
+ from .disconnect_reason import DisconnectReason
13
+ from .sync_state import SyncState
14
+ from .transport import AidlabScanner, AidlabTransport, AidlabTransportFactory, DeviceInfo
15
+ from .wear_state import WearState
16
+
17
+ try:
18
+ from . import bleak_adapter as _bleak_adapter
19
+ except ImportError:
20
+ _bleak_exports = []
21
+ else:
22
+ BleakAidlabScanner = _bleak_adapter.BleakAidlabScanner
23
+ BleakTransport = _bleak_adapter.BleakTransport
24
+ BleakTransportFactory = _bleak_adapter.BleakTransportFactory
25
+ _bleak_exports = ["BleakAidlabScanner", "BleakTransport", "BleakTransportFactory"]
26
+
27
+ __all__ = [
28
+ "ActivityType",
29
+ "AidlabError",
30
+ "AidlabErrorCode",
31
+ "AidlabManager",
32
+ "AidlabScanner",
33
+ "AidlabTransport",
34
+ "AidlabTransportFactory",
35
+ "BodyPosition",
36
+ "DataType",
37
+ "Device",
38
+ "DeviceDelegate",
39
+ "DeviceInfo",
40
+ "DisconnectReason",
41
+ "SyncState",
42
+ "WearState",
43
+ ] + _bleak_exports
aidlab/_native.py ADDED
@@ -0,0 +1,62 @@
1
+ """Native Aidlab SDK library selection shared by runtime and packaging."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ import sys
7
+ from typing import TypedDict
8
+
9
+
10
+ class NativeTarget(TypedDict):
11
+ library: str
12
+ wheel_platform: str
13
+
14
+
15
+ NATIVE_TARGETS: dict[str, NativeTarget] = {
16
+ "linux-x86_64": {
17
+ "library": "aidlabsdk-linux-gnu.so",
18
+ "wheel_platform": "linux_x86_64",
19
+ },
20
+ "linux-aarch64": {
21
+ "library": "aidlabsdk-linux-gnu-aarch64.so",
22
+ "wheel_platform": "linux_aarch64",
23
+ },
24
+ "linux-armv7l": {
25
+ "library": "aidlabsdk-linux-gnueabihf.so",
26
+ "wheel_platform": "linux_armv7l",
27
+ },
28
+ "macos-universal2": {
29
+ "library": "aidlabsdk.dylib",
30
+ "wheel_platform": "macosx_11_0_universal2",
31
+ },
32
+ "windows-x86_64": {
33
+ "library": "aidlabsdk.dll",
34
+ "wheel_platform": "win_amd64",
35
+ },
36
+ }
37
+
38
+
39
+ def native_target_key(system_platform: str | None = None, machine: str | None = None) -> str:
40
+ """Return the distribution target for the current host."""
41
+ current_platform = (system_platform or sys.platform).lower()
42
+ current_machine = (machine or platform.machine()).lower()
43
+
44
+ if current_platform.startswith("linux"):
45
+ if current_machine in {"x86_64", "amd64"}:
46
+ return "linux-x86_64"
47
+ if current_machine in {"aarch64", "arm64"}:
48
+ return "linux-aarch64"
49
+ if current_machine in {"armv6l", "armv7l"}:
50
+ return "linux-armv7l"
51
+ raise RuntimeError(f"Unsupported Linux architecture: {current_machine}")
52
+
53
+ if current_platform == "darwin":
54
+ return "macos-universal2"
55
+ if current_platform == "win32":
56
+ return "windows-x86_64"
57
+ raise RuntimeError(f"Unsupported operating system: {current_platform}")
58
+
59
+
60
+ def native_library_name(system_platform: str | None = None, machine: str | None = None) -> str:
61
+ """Return the packaged library filename for the requested host."""
62
+ return NATIVE_TARGETS[native_target_key(system_platform, machine)]["library"]
@@ -0,0 +1,27 @@
1
+ """
2
+ Created by Jakub Domaszewicz on 16.03.2024.
3
+ """
4
+
5
+ from enum import IntEnum
6
+
7
+
8
+ class ActivityType(IntEnum):
9
+ """
10
+ Enumerates the possible types of activities that can be recognized by the device.
11
+
12
+ Attributes:
13
+ UNKNOWN (0): The activity is unknown or not recognized.
14
+ AUTOMOTIVE (1): The user is in a vehicle, such as a car, bus, or train.
15
+ WALKING (2): The user is walking.
16
+ RUNNING (4): The user is running.
17
+ CYCLING (8): The user is cycling.
18
+ STILL (16): The user is still, i.e. not moving.
19
+
20
+ """
21
+
22
+ UNKNOWN = 0
23
+ AUTOMOTIVE = 1
24
+ WALKING = 2
25
+ RUNNING = 4
26
+ CYCLING = 8
27
+ STILL = 16
aidlab/aidlab_error.py ADDED
@@ -0,0 +1,25 @@
1
+ from dataclasses import dataclass
2
+ from enum import IntEnum
3
+
4
+
5
+ class AidlabErrorCode(IntEnum):
6
+ NONE = 0
7
+ TRANSPORT = 1000
8
+ PROTOCOL = 2000
9
+ SDK = 9000
10
+
11
+ @classmethod
12
+ def from_value(cls, value: int) -> "AidlabErrorCode":
13
+ try:
14
+ return cls(value)
15
+ except ValueError:
16
+ return cls.SDK
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class AidlabError:
21
+ code: AidlabErrorCode
22
+ message: str
23
+
24
+ def __str__(self) -> str:
25
+ return f"AidlabError(code={self.code.name}, message={self.message})"
@@ -0,0 +1,64 @@
1
+ """
2
+ Part of the Aidlab Python SDK, providing the core functionality for scanning compatible devices.
3
+
4
+ To customise logging, configure the standard Python logging system in your
5
+ application, for example:
6
+
7
+ logging.getLogger("aidlab.aidlab_manager").setLevel(logging.INFO)
8
+
9
+ Created by Szymon Gesicki on 09.05.2020.
10
+ """
11
+
12
+ import logging
13
+
14
+ from .device import Device
15
+ from .transport import AidlabScanner, AidlabTransportFactory
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class AidlabManager:
21
+ """
22
+ The central class of the Aidlab SDK for scanning compatible devices.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ scanner: AidlabScanner | None = None,
28
+ transport_factory: AidlabTransportFactory | None = None,
29
+ ):
30
+ if scanner is None or transport_factory is None:
31
+ try:
32
+ from .bleak_adapter import BleakAidlabScanner, BleakTransportFactory
33
+ except ImportError as exc:
34
+ raise RuntimeError(
35
+ "Default BLE adapter requires the 'bleak' dependency. "
36
+ "Install it or provide custom scanner and transport_factory."
37
+ ) from exc
38
+
39
+ self._scanner = scanner if scanner is not None else BleakAidlabScanner()
40
+ self._transport_factory = transport_factory if transport_factory is not None else BleakTransportFactory()
41
+
42
+ async def scan(self, timeout: int = 10) -> list[Device]:
43
+ """
44
+ Scans for compatible devices.
45
+
46
+ :param timeout: The time in seconds to scan for devices.
47
+ """
48
+
49
+ logger.info("Scanning for devices (timeout: %d seconds)...", timeout)
50
+
51
+ devices = await self._scanner.scan(timeout)
52
+
53
+ compatible_devices = [
54
+ Device(
55
+ address=device.address,
56
+ name=device.name,
57
+ transport=self._transport_factory.create(device),
58
+ )
59
+ for device in devices
60
+ ]
61
+
62
+ logger.info("Finished scanning. Found %d devices.", len(compatible_devices))
63
+
64
+ return compatible_devices
aidlab/aidlabsdk.dll ADDED
Binary file
@@ -0,0 +1,185 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from contextlib import suppress
5
+
6
+ from bleak import BleakClient, BleakScanner
7
+ from bleak.backends.characteristic import BleakGATTCharacteristic
8
+ from bleak.backends.device import BLEDevice
9
+
10
+ from .transport import (
11
+ AidlabScanner,
12
+ AidlabTransport,
13
+ AidlabTransportFactory,
14
+ DeviceInfo,
15
+ )
16
+
17
+
18
+ class BleakTransport(AidlabTransport):
19
+ def __init__(self, device: str | BLEDevice):
20
+ self._device = device
21
+ self._client: BleakClient | None = None
22
+ self._loop: asyncio.AbstractEventLoop | None = None
23
+ self._disconnect_queue: asyncio.Queue[None] = asyncio.Queue()
24
+ self._notify_slots: dict[str, _NotifySlot] = {}
25
+
26
+ @property
27
+ def mtu_size(self) -> int:
28
+ client = self._client
29
+ if client is None:
30
+ return 23
31
+ return getattr(client, "mtu_size", 23)
32
+
33
+ async def connect(self) -> None:
34
+ await self._reset_notifications()
35
+ self._loop = asyncio.get_running_loop()
36
+
37
+ def _on_disconnect(_client: BleakClient) -> None:
38
+ loop = self._loop
39
+ if loop is not None and not loop.is_closed():
40
+ loop.call_soon_threadsafe(self._disconnect_queue.put_nowait, None)
41
+
42
+ client = BleakClient(self._device, disconnected_callback=_on_disconnect)
43
+ self._client = client
44
+ await client.connect(timeout=10)
45
+
46
+ async def disconnect(self) -> None:
47
+ try:
48
+ await self._require_client().disconnect()
49
+ finally:
50
+ await self._reset_notifications()
51
+
52
+ async def read_char(self, uuid: str) -> bytes:
53
+ return bytes(await self._require_client().read_gatt_char(uuid))
54
+
55
+ async def write_char(self, uuid: str, data: bytes, response: bool = True) -> None:
56
+ client = self._require_client()
57
+ characteristic = client.services.get_characteristic(uuid)
58
+ if characteristic is None:
59
+ raise RuntimeError(f"BLE characteristic {uuid} is unavailable")
60
+
61
+ properties = set(characteristic.properties)
62
+ if response:
63
+ if "write" not in properties:
64
+ raise RuntimeError(f"BLE characteristic {uuid} does not support writes with response")
65
+ elif "write-without-response" not in properties:
66
+ raise RuntimeError(f"BLE characteristic {uuid} does not support writes without response")
67
+
68
+ await client.write_gatt_char(characteristic, data, response)
69
+
70
+ async def notifications(self, uuid: str):
71
+ slot = self._notify_slots.get(uuid)
72
+ if slot is None:
73
+ slot = _NotifySlot(uuid=uuid, transport=self)
74
+ self._notify_slots[uuid] = slot
75
+ return await slot.subscribe()
76
+
77
+ async def disconnections(self):
78
+ return _queue_iter(self._disconnect_queue)
79
+
80
+ def _require_client(self) -> BleakClient:
81
+ client = self._client
82
+ if client is None:
83
+ raise RuntimeError("BLE client is not connected")
84
+ return client
85
+
86
+ async def _reset_notifications(self) -> None:
87
+ slots = list(self._notify_slots.values())
88
+ self._notify_slots.clear()
89
+ for slot in slots:
90
+ await slot.close()
91
+
92
+
93
+ async def _queue_iter(queue: asyncio.Queue[None] | asyncio.Queue[bytes]):
94
+ while True:
95
+ item = await queue.get()
96
+ yield item
97
+
98
+
99
+ class _NotifySlot:
100
+ def __init__(self, uuid: str, transport: BleakTransport):
101
+ self._uuid = uuid
102
+ self._transport = transport
103
+ self._queues: list[asyncio.Queue[bytes]] = []
104
+ self._active = False
105
+ self._lock = asyncio.Lock()
106
+
107
+ async def subscribe(self):
108
+ queue: asyncio.Queue[bytes] = asyncio.Queue()
109
+ self._queues.append(queue)
110
+ await self._ensure_started()
111
+
112
+ async def _gen():
113
+ try:
114
+ while True:
115
+ data = await queue.get()
116
+ yield data
117
+ finally:
118
+ await self._remove_queue(queue)
119
+
120
+ return _gen()
121
+
122
+ async def _ensure_started(self) -> None:
123
+ async with self._lock:
124
+ if self._active:
125
+ return
126
+ self._active = True
127
+ client = self._transport._require_client()
128
+ loop = asyncio.get_running_loop()
129
+
130
+ def _on_data(_sender: BleakGATTCharacteristic, data: bytearray) -> None:
131
+ payload = bytes(data)
132
+ loop.call_soon_threadsafe(self._deliver_payload, payload)
133
+
134
+ await client.start_notify(self._uuid, _on_data)
135
+
136
+ def _deliver_payload(self, payload: bytes) -> None:
137
+ if not self._active:
138
+ return
139
+ for q in list(self._queues):
140
+ q.put_nowait(payload)
141
+
142
+ async def _remove_queue(self, queue: asyncio.Queue[bytes]) -> None:
143
+ async with self._lock:
144
+ with suppress(ValueError):
145
+ self._queues.remove(queue)
146
+ if self._queues:
147
+ return
148
+ if not self._active:
149
+ return
150
+ self._active = False
151
+ client = self._transport._client
152
+ if client is None:
153
+ return
154
+ with suppress(Exception):
155
+ await client.stop_notify(self._uuid)
156
+
157
+ async def close(self) -> None:
158
+ async with self._lock:
159
+ self._queues.clear()
160
+ if not self._active:
161
+ return
162
+ self._active = False
163
+ client = self._transport._client
164
+ if client is None:
165
+ return
166
+ with suppress(Exception):
167
+ await client.stop_notify(self._uuid)
168
+
169
+
170
+ class BleakAidlabScanner(AidlabScanner):
171
+ async def scan(self, timeout: float = 10.0) -> list[DeviceInfo]:
172
+ devices = await BleakScanner.discover(timeout=timeout)
173
+ compatible_devices: list[DeviceInfo] = []
174
+
175
+ for device in devices:
176
+ if (device.name == "Aidlab 2" or device.name == "Aidlab") and device.address:
177
+ compatible_devices.append(DeviceInfo(address=device.address, name=device.name, metadata=device))
178
+
179
+ return compatible_devices
180
+
181
+
182
+ class BleakTransportFactory(AidlabTransportFactory):
183
+ def create(self, device: DeviceInfo) -> AidlabTransport:
184
+ native_device = device.metadata if isinstance(device.metadata, BLEDevice) else device.address
185
+ return BleakTransport(native_device)
@@ -0,0 +1,25 @@
1
+ """
2
+ Created by Jakub Domaszewicz on 17.12.2023.
3
+ """
4
+
5
+ from enum import IntEnum
6
+
7
+
8
+ class BodyPosition(IntEnum):
9
+ """
10
+ Enumerates the possible positions of a body when lying on a bed with a device.
11
+ Each value represents a specific orientation of the body relative to the bed.
12
+
13
+ Attributes:
14
+ UNKNOWN (0): The body's position is unknown or not recognized.
15
+ PRONE (1): The body is lying face down on its stomach.
16
+ SUPINE (2): The body is lying face up on its back.
17
+ LEFT_SIDE (3): The body is lying on its left side.
18
+ RIGHT_SIDE (4): The body is lying on its right side.
19
+ """
20
+
21
+ UNKNOWN = 0
22
+ PRONE = 1
23
+ SUPINE = 2
24
+ LEFT_SIDE = 3
25
+ RIGHT_SIDE = 4
aidlab/data_type.py ADDED
@@ -0,0 +1,31 @@
1
+ """
2
+ Created by Szymon Gesicki on 07.11.2021.
3
+ """
4
+
5
+ from enum import IntEnum
6
+
7
+
8
+ class DataType(IntEnum):
9
+ """
10
+ Data types that can be received from Aidlab and Aidmed One.
11
+ See the documentation to learn more about each data type.
12
+ """
13
+
14
+ ECG = 0
15
+ RESPIRATION = 1
16
+ SKIN_TEMPERATURE = 2
17
+ MOTION = 3
18
+ RESERVED_0 = 4 # Was BATTERY. Enabled by default since SDK 1.6.0
19
+ ACTIVITY = 5
20
+ ORIENTATION = 6
21
+ STEPS = 7
22
+ HEART_RATE = 8
23
+ RESERVED_1 = 9 # Was HEALTH_THERMOMETHER. No longer in use. Use SKIN_TEMPERATURE instead.
24
+ SOUND_VOLUME = 10
25
+ RR = 11
26
+ PRESSURE = 12 # Supported since Firmware 3.0.0. No longer available as characteristic.
27
+ RESERVED_2 = 13 # Was SOUND_FEATURES. No longer in use.
28
+ RESPIRATION_RATE = 14
29
+ BODY_POSITION = 15
30
+ EDA = 16
31
+ GPS = 17