python-igps-ble 0.1.0__py3-none-any.whl → 0.3.4__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.
igps_ble/__init__.py CHANGED
@@ -1,7 +1,18 @@
1
1
  """Pure-Python BLE library for the iGPSPORT iGS10S cycling computer."""
2
2
 
3
- from .models import IGPSDeviceState
3
+ from .client import IGPSClient, IGPSCommandError, IGPSSession, read_state, set_profile
4
+ from .models import Activity, IGPSDeviceState, UserProfile
4
5
 
5
- __version__ = "0.1.0"
6
+ __version__ = "0.3.4"
6
7
 
7
- __all__ = ["IGPSDeviceState", "__version__"]
8
+ __all__ = [
9
+ "Activity",
10
+ "IGPSClient",
11
+ "IGPSCommandError",
12
+ "IGPSDeviceState",
13
+ "IGPSSession",
14
+ "UserProfile",
15
+ "__version__",
16
+ "read_state",
17
+ "set_profile",
18
+ ]
igps_ble/__main__.py CHANGED
@@ -20,11 +20,8 @@ async def _scan(timeout: float) -> None:
20
20
 
21
21
  async def _info(address: str) -> None:
22
22
  state = await IGPSClient(address).async_read_state()
23
- print(f"Endereço: {state.address}")
24
- print(f"Modelo: {state.model}")
25
- print(f"Firmware: {state.firmware}")
26
- print(f"Fabricante: {state.manufacturer}")
27
- print(f"Bateria: {state.battery_level}%")
23
+ for name in state.__slots__:
24
+ print(f"{name:17} {getattr(state, name)}")
28
25
 
29
26
 
30
27
  def main() -> None:
@@ -32,7 +29,7 @@ def main() -> None:
32
29
  sub = parser.add_subparsers(dest="cmd", required=True)
33
30
  p_scan = sub.add_parser("scan", help="Procura aparelhos iGPSPORT por perto")
34
31
  p_scan.add_argument("--timeout", type=float, default=10.0)
35
- p_info = sub.add_parser("info", help="Conecta e lê bateria/device-info")
32
+ p_info = sub.add_parser("info", help="Conecta e lê tudo que o aparelho expõe")
36
33
  p_info.add_argument("address")
37
34
 
38
35
  args = parser.parse_args()
igps_ble/client.py CHANGED
@@ -1,13 +1,20 @@
1
- """Client async que conecta no iGS10S e lê as characteristics em escopo.
1
+ """I/O BLE do iGS10S: device-info SIG + protocolo protobuf proprietário.
2
2
 
3
- Único módulo que abre conexão BLE. Aceita um BleakClient já criado (ou um
4
- BLEDevice) — útil pra reaproveitar a conexão do bleak-retry-connector no HA.
3
+ Único módulo que fala com o rádio. As funções aceitam um ``BleakClient`` já
4
+ conectado — o HA passa o do bleak-retry-connector; a CLI usa ``IGPSClient``.
5
5
  """
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ import asyncio
10
+ import logging
11
+ import struct
12
+ from dataclasses import replace
13
+ from datetime import datetime, timedelta
14
+
9
15
  from bleak import BleakClient
10
16
 
17
+ from . import protocol as p
11
18
  from .const import (
12
19
  BATTERY_LEVEL_UUID,
13
20
  FIRMWARE_REVISION_UUID,
@@ -16,12 +23,498 @@ from .const import (
16
23
  MODEL_NUMBER_UUID,
17
24
  SOFTWARE_REVISION_UUID,
18
25
  )
19
- from .models import IGPSDeviceState
26
+ from .models import Activity, IGPSDeviceState, UserProfile
20
27
  from .parser import decode_device_string, parse_battery_level
21
28
 
29
+ _LOGGER = logging.getLogger(__name__)
30
+
31
+ # Epoch FIT (1989-12-31 00:00). O aparelho guarda horário *local* nessa base.
32
+ FIT_EPOCH = datetime(1989, 12, 31)
33
+ CYCLING_STATUS = {0: "idle", 1: "recording", 2: "paused"}
34
+ RIDE_FIELDS = {
35
+ 1: "speed", 2: "avg_speed", 3: "riding_time", 4: "distance", 5: "cadence",
36
+ 6: "heart_rate", 7: "avg_heart_rate", 8: "power", 9: "total_ascent",
37
+ 10: "avg_rise", 11: "altitude", 12: "slope", 13: "max_speed",
38
+ 14: "max_heart_rate", 15: "avg_cadence", 16: "max_cadence",
39
+ 17: "avg_power", 18: "max_power", 19: "course",
40
+ } # fmt: skip
41
+
42
+
43
+ class IGPSCommandError(Exception):
44
+ """O aparelho respondeu com ACK de erro (``DeviceReturnStatus``)."""
45
+
46
+ def __init__(self, status: int) -> None:
47
+ super().__init__(f"device returned status {status}")
48
+ self.status = status
49
+
50
+
51
+ def fit_time(seconds: int) -> datetime:
52
+ return FIT_EPOCH + timedelta(seconds=seconds)
53
+
54
+
55
+ def _double(raw: int) -> float:
56
+ return struct.unpack("<d", raw.to_bytes(8, "little"))[0]
57
+
58
+
59
+ def _first(msg: dict, key: int, default=None):
60
+ return msg.get(key, [default])[0]
61
+
62
+
63
+ class IGPSSession:
64
+ """Request/response sobre os canais NUS (um comando por vez)."""
65
+
66
+ def __init__(self, client: BleakClient) -> None:
67
+ self._client = client
68
+ self._buffer = bytearray()
69
+ self._frames: asyncio.Queue[tuple[p.Header, bytes]] = asyncio.Queue()
70
+ self._lock = asyncio.Lock()
71
+
72
+ @property
73
+ def client(self) -> BleakClient:
74
+ return self._client
75
+
76
+ async def start(self) -> None:
77
+ for char in (p.DATA_TX, p.THIRD_TX):
78
+ await self._client.start_notify(char, self._on_data)
79
+ await self._client.start_notify(p.CONTROL_TX, self._on_control)
80
+
81
+ def _on_data(self, _char, data: bytearray) -> None:
82
+ self._buffer += data
83
+
84
+ def _on_control(self, _char, data: bytearray) -> None:
85
+ header = p.parse_header(bytes(data))
86
+ if header is None:
87
+ return
88
+ payload = b""
89
+ if header.kind == p.FRAME_HEADER:
90
+ payload = bytes(self._buffer)
91
+ self._buffer.clear()
92
+ self._frames.put_nowait((header, payload))
93
+
94
+ async def send(
95
+ self,
96
+ service: int,
97
+ op: int,
98
+ payload: bytes,
99
+ sub: int = 0xFF,
100
+ channel: str = p.DATA_RX,
101
+ ) -> None:
102
+ """Escreve payload + header. Descarta frames antigos ainda na fila."""
103
+ while not self._frames.empty():
104
+ self._frames.get_nowait()
105
+ self._buffer.clear()
106
+ # O firmware só lê 20 B por pacote (MTU padrão); o app fatia igual.
107
+ for i in range(0, len(payload), p.PACKET_SIZE):
108
+ chunk = payload[i : i + p.PACKET_SIZE]
109
+ await self._client.write_gatt_char(channel, chunk, response=True)
110
+ await self._client.write_gatt_char(
111
+ p.CONTROL_RX, p.build_header(service, op, payload, sub), True
112
+ )
113
+
114
+ async def receive(
115
+ self, service: int, timeout: float = 5.0
116
+ ) -> tuple[p.Header, bytes]:
117
+ """Próximo frame do ``service`` (pushes de outros serviços são ignorados).
118
+
119
+ ACK com status != 0 vira ``IGPSCommandError``.
120
+ """
121
+ async with asyncio.timeout(timeout):
122
+ while True:
123
+ header, payload = await self._frames.get()
124
+ if header.service != service:
125
+ continue
126
+ if header.kind == p.FRAME_ACK and header.status != 0:
127
+ raise IGPSCommandError(header.status)
128
+ return header, payload
129
+
130
+ async def ack(self, service: int, op: int, status: int = 0) -> None:
131
+ await self._client.write_gatt_char(
132
+ p.CONTROL_RX, p.build_ack(service, op, status), True
133
+ )
134
+
135
+ async def request(
136
+ self,
137
+ service: int,
138
+ op: int,
139
+ payload: bytes,
140
+ sub: int = 0xFF,
141
+ channel: str = p.DATA_RX,
142
+ timeout: float = 10.0,
143
+ ) -> dict[int, list]:
144
+ """Envia e devolve a resposta decodificada (``{}`` para um ACK de SET)."""
145
+ async with self._lock:
146
+ await self.send(service, op, payload, sub, channel)
147
+ return p.decode((await self.receive(service, timeout))[1])
148
+
149
+ async def simple(self, service: int, op: int, extra=(), **kw) -> dict[int, list]:
150
+ """Mensagem padrão ``{1: service, 2: op, ...}``."""
151
+ payload, _ = p.request(service, op, extra)
152
+ return await self.request(service, op, payload, **kw)
153
+
154
+
155
+ # ------------------------------------------------------------------- reads
156
+
157
+
158
+ async def _sig(client: BleakClient, uuid: str) -> str | None:
159
+ if client.services.get_characteristic(uuid) is None:
160
+ return None
161
+ try:
162
+ return decode_device_string(await client.read_gatt_char(uuid))
163
+ except Exception: # noqa: BLE001 - char some/erra => ausente
164
+ return None
165
+
166
+
167
+ async def _sig_battery(client: BleakClient) -> int | None:
168
+ if client.services.get_characteristic(BATTERY_LEVEL_UUID) is None:
169
+ return None
170
+ try:
171
+ return parse_battery_level(await client.read_gatt_char(BATTERY_LEVEL_UUID))
172
+ except Exception: # noqa: BLE001
173
+ return None
174
+
175
+
176
+ async def _read_protocol(s: IGPSSession) -> dict:
177
+ """Cada consulta é independente: falha numa não derruba as outras."""
178
+ out: dict = {}
179
+
180
+ async def attempt(fn):
181
+ try:
182
+ await fn()
183
+ except (IGPSCommandError, TimeoutError, ValueError) as err:
184
+ _LOGGER.debug("consulta %s falhou: %r", fn.__name__, err)
185
+
186
+ async def battery():
187
+ msg = p.decode(_first(await s.simple(p.Service.FACTORY, 6), 6, b""))
188
+ out["battery_voltage"] = _first(msg, 1, 0) / 1000 or None
189
+ out["battery_level"] = _first(msg, 2)
190
+
191
+ async def serial():
192
+ sn = p.decode(_first(await s.simple(p.Service.FACTORY, 1), 3, b""))
193
+ out["serial"] = _first(sn, 1, b"").decode() or None
194
+
195
+ async def version():
196
+ ver = p.decode(_first(await s.simple(p.Service.DEV_VER_INFO, 2), 3, b""))
197
+ if (proto := _first(ver, 6)) is not None:
198
+ out["protocol_version"] = f"{proto // 100}.{proto % 100:02d}"
199
+
200
+ async def memory():
201
+ mem = p.decode(_first(await s.simple(p.Service.FACTORY, 5), 5, b""))
202
+ out["memory_total"], out["memory_free"] = _first(mem, 1), _first(mem, 2)
203
+
204
+ async def sensors():
205
+ for raw in (await s.simple(p.Service.FACTORY, 4)).get(4, []):
206
+ sensor = p.decode(raw)
207
+ kind, data = _first(sensor, 1), _first(sensor, 2, 0)
208
+ if kind == 2 and data: # RTC
209
+ out["device_time"] = fit_time(data)
210
+ elif kind == 4: # TEM, décimos de °C
211
+ out["temperature"] = p.int32(data) / 10
212
+
213
+ async def status():
214
+ msg = await s.simple(p.Service.DEV_STATUS, 1)
215
+ cyc = p.decode(_first(msg, 3, b""))
216
+ out["cycling_status"] = CYCLING_STATUS.get(_first(cyc, 1, 0))
217
+ if start := _first(cyc, 2):
218
+ out["cycling_start"] = fit_time(start)
219
+ gps = p.decode(_first(msg, 4, b""))
220
+ if 1 in gps and 2 in gps:
221
+ out["latitude"] = round(_double(gps[1][0]), 6)
222
+ out["longitude"] = round(_double(gps[2][0]), 6)
223
+ rt = p.decode(_first(msg, 5, b""))
224
+ out["ride"] = {
225
+ RIDE_FIELDS[k]: p.int32(v[0]) for k, v in rt.items() if k in RIDE_FIELDS
226
+ }
227
+
228
+ async def activities():
229
+ msg = await s.simple(p.Service.CYCLING_DATA, 1, channel=p.THIRD_RX, timeout=20)
230
+ items = (p.decode(raw) for raw in msg.get(3, []))
231
+ out["activities"] = tuple(
232
+ sorted(
233
+ (
234
+ Activity(
235
+ _first(i, 1, 0), fit_time(_first(i, 1, 0)), _first(i, 2, 0)
236
+ )
237
+ for i in items
238
+ ),
239
+ key=lambda a: a.start,
240
+ reverse=True,
241
+ )
242
+ )
243
+
244
+ for fn in (battery, serial, version, memory, sensors, status, activities):
245
+ await attempt(fn)
246
+ return out
247
+
248
+
249
+ async def read_state(
250
+ client: BleakClient,
251
+ address: str,
252
+ name: str = "iGS10S",
253
+ rssi: int | None = None,
254
+ session: IGPSSession | None = None,
255
+ ) -> IGPSDeviceState:
256
+ """Lê device-info SIG + tudo que o protocolo proprietário responde.
257
+
258
+ Passe ``session`` (já iniciada) para reaproveitar a conexão em comandos.
259
+ """
260
+ firmware = await _sig(client, SOFTWARE_REVISION_UUID) or await _sig(
261
+ client, FIRMWARE_REVISION_UUID
262
+ )
263
+ state = IGPSDeviceState(
264
+ address=address,
265
+ name=name,
266
+ rssi=rssi,
267
+ battery_level=await _sig_battery(client),
268
+ model=await _sig(client, MODEL_NUMBER_UUID),
269
+ firmware=firmware,
270
+ hardware=await _sig(client, HARDWARE_REVISION_UUID),
271
+ manufacturer=await _sig(client, MANUFACTURER_NAME_UUID),
272
+ )
273
+ if session is None:
274
+ session = IGPSSession(client)
275
+ try:
276
+ await session.start()
277
+ except Exception: # noqa: BLE001 - aparelho sem NUS => só SIG
278
+ return state
279
+ return replace(state, **await _read_protocol(session))
280
+
281
+
282
+ # ---------------------------------------------------------------- commands
283
+
284
+
285
+ async def set_profile(session: IGPSSession, profile: UserProfile) -> None:
286
+ """Grava o perfil inteiro (USER_CONFIG/SET).
287
+
288
+ O iGS10S aceita o SET mas o GET devolve sempre zeros, então não dá pra
289
+ fazer read-modify-write: quem chama guarda o perfil. Campo ausente = 0.
290
+ ``time_zone_s`` define o fuso do relógio (que vem do GPS).
291
+ """
292
+ data = [
293
+ (1, profile.sex),
294
+ (2, round(profile.weight_kg * 10)),
295
+ (3, profile.age),
296
+ (4, profile.height_cm),
297
+ (5, profile.wheel_mm),
298
+ (6, round(profile.bike_weight_kg * 10)),
299
+ (7, profile.time_zone_s),
300
+ ]
301
+ await session.simple(p.Service.USER_CONFIG, 1, [(3, data)])
302
+
303
+
304
+ async def download_activity(
305
+ session: IGPSSession,
306
+ activity_id: int,
307
+ size: int | None = None,
308
+ timeout: float = 30.0,
309
+ attempts: int = 3,
310
+ ) -> bytes:
311
+ """Baixa o ``.fit`` de uma atividade (CYCLING_DATA/FILE_GET no ch3).
312
+
313
+ O aparelho manda pedaços de ~4 KB; cada um é confirmado (ACK 0) ou pedido
314
+ de novo (ACK 1) se o CRC/tamanho não bater — igual ao app. Com ``size``
315
+ (da lista de atividades), um arquivo incompleto é baixado de novo.
316
+ """
317
+ for attempt in range(attempts):
318
+ data = await _download_once(session, activity_id, timeout)
319
+ if size is None or len(data) == size:
320
+ return data
321
+ _LOGGER.debug(
322
+ "fit %s incompleto (%d de %d B), tentativa %d",
323
+ activity_id, len(data), size, attempt + 1,
324
+ ) # fmt: skip
325
+ raise IGPSCommandError(1)
326
+
327
+
328
+ async def _download_once(
329
+ session: IGPSSession, activity_id: int, timeout: float
330
+ ) -> bytes:
331
+ svc, file_get, file_send = p.Service.CYCLING_DATA, 3, 4
332
+ payload, _ = p.request(svc, file_get, [(3, [(1, activity_id)])])
333
+ content = bytearray()
334
+ async with session._lock:
335
+ await session.send(svc, file_get, payload, channel=p.THIRD_RX)
336
+ retries = 0
337
+ while True:
338
+ header, chunk = await session.receive(svc, timeout)
339
+ if header.op != file_send:
340
+ continue
341
+ if len(chunk) != header.length or p.crc8(chunk) != header.payload_crc:
342
+ retries += 1
343
+ _LOGGER.debug(
344
+ "fit %s: pedaço inválido (%d/%d B), reenvio %d",
345
+ activity_id, len(chunk), header.length, retries,
346
+ ) # fmt: skip
347
+ if retries > 5:
348
+ raise IGPSCommandError(1)
349
+ await session.ack(svc, file_send, status=1)
350
+ continue
351
+ retries = 0
352
+ msg = p.decode(chunk)
353
+ if p.decode(_first(msg, 3, b"")).get(1, [activity_id])[0] != activity_id:
354
+ raise IGPSCommandError(1) # aparelho mandou outra atividade
355
+ content += _first(msg, 4, b"")
356
+ _LOGGER.debug(
357
+ "fit %s: %d B (last=%s)", activity_id, len(content), header.last
358
+ )
359
+ if header.last:
360
+ return bytes(content)
361
+ await session.ack(svc, file_send)
362
+
363
+
364
+ # ------------------------------------------------- atividades / manutenção
365
+ #
366
+ # Tudo abaixo segue o app (``SyncActivityDelegate``, ``FactorySettingsDelegate``,
367
+ # ``PairBindingDelegate``, ``FirmwareUpdateDelegate``). Vários são comandos de
368
+ # bancada de fábrica sem tela no app: os nomes vêm dos enums do protobuf.
369
+
370
+ # Factory.CONTROL_CMD_TYPE (FACTORY/CONTROL_SET).
371
+ CONTROL = {
372
+ "enter_check": 1, # modo de teste de fábrica
373
+ "lock": 2,
374
+ "format": 16, # formata a memória (apaga atividades)
375
+ "low_level_format": 17,
376
+ "reset_settings": 18, # PARA_RESET: volta ajustes ao padrão
377
+ "factory_reset": 19,
378
+ "temperature_log": 32,
379
+ "voltage_log": 33,
380
+ "ant_log": 34,
381
+ }
382
+ # Factory.GPS_CONTROL_CMD_TYPE (FACTORY/GPS_CONTROL_CMD_SET).
383
+ GPS_COMMAND = {"power": 1, "cold_start": 2, "power_save": 3, "gnss": 4}
384
+ # Factory.GNSS_TYPE — bitmask para FACTORY/GPS_GNSS_SET.
385
+ GNSS = {
386
+ "gps": 1, "beidou": 2, "glonass": 4, "qzss": 8,
387
+ "sbas": 16, "galileo": 32, "imes": 64,
388
+ } # fmt: skip
389
+ # Factory.GPS_DYNAMIC_TYPE (modelo dinâmico do receptor).
390
+ GPS_DYNAMIC = {
391
+ "portable": 1, "stationary": 2, "pedestrian": 3, "automotive": 4, "sea": 5,
392
+ "airborne_1g": 6, "airborne_2g": 7, "airborne_4g": 8, "wrist": 9, "bike": 10,
393
+ } # fmt: skip
394
+ # Factory.FILTER_TYPE (FACTORY/FILTER_SET).
395
+ FILTERS = {
396
+ "smart_save": 1, "speed": 2, "cadence": 3, "heart_rate": 4,
397
+ "gps_icon": 5, "ant_icon": 6,
398
+ } # fmt: skip
399
+ # Comandos que podem reiniciar o aparelho antes de responder.
400
+ _REBOOTING = {"format", "low_level_format", "reset_settings", "factory_reset"}
401
+
402
+
403
+ async def command(
404
+ session: IGPSSession,
405
+ service: int,
406
+ op: int,
407
+ fields=(),
408
+ sub: int = 0xFF,
409
+ channel: str = p.DATA_RX,
410
+ timeout: float = 10.0,
411
+ ) -> dict[int, list]:
412
+ """Comando cru: ``{1: service, 2: op, *fields}`` — para o que não tem helper."""
413
+ return await session.simple(
414
+ service, op, list(fields), sub=sub, channel=channel, timeout=timeout
415
+ )
416
+
417
+
418
+ async def delete_activity(session: IGPSSession, activity_id: int) -> None:
419
+ """Apaga uma atividade (CYCLING_DATA/FILE_DEL no ch3)."""
420
+ await session.simple(
421
+ p.Service.CYCLING_DATA, 5, [(3, [(1, activity_id)])], channel=p.THIRD_RX
422
+ )
423
+
424
+
425
+ async def delete_all_activities(session: IGPSSession) -> None:
426
+ """Apaga todas as atividades (CYCLING_DATA/ALL_DEL no ch3)."""
427
+ await session.simple(p.Service.CYCLING_DATA, 6, channel=p.THIRD_RX)
428
+
429
+
430
+ async def _factory(session: IGPSSession, op: int, field: int, data, **kw) -> None:
431
+ await session.simple(p.Service.FACTORY, op, [(field, data)], **kw)
432
+
433
+
434
+ async def factory_control(session: IGPSSession, cmd: str, status: int = 1) -> None:
435
+ """FACTORY/CONTROL_SET: format, factory_reset, reset_settings, lock, logs…
436
+
437
+ Os que reiniciam o aparelho podem não responder: timeout conta como enviado.
438
+ """
439
+ try:
440
+ await _factory(session, 23, 8, [(1, CONTROL[cmd]), (2, status)], timeout=10)
441
+ except TimeoutError:
442
+ if cmd not in _REBOOTING:
443
+ raise
444
+
445
+
446
+ async def gps_control(session: IGPSSession, cmd: str, status: int = 1) -> None:
447
+ """Liga/desliga GPS (``power``), ``cold_start``, ``power_save``, ``gnss``."""
448
+ await _factory(session, 16, 14, [(1, GPS_COMMAND[cmd]), (2, status)])
449
+
450
+
451
+ async def set_gnss(session: IGPSSession, systems) -> None:
452
+ """Constelações ativas, ex. ``{"gps", "glonass", "galileo"}``."""
453
+ mask = 0
454
+ for name in systems:
455
+ mask |= GNSS[name]
456
+ await _factory(session, 18, 15, [(1, mask)])
457
+
458
+
459
+ async def set_gps_dynamic(session: IGPSSession, mode: str) -> None:
460
+ await _factory(session, 20, 16, [(1, GPS_DYNAMIC[mode])])
461
+
462
+
463
+ async def set_gps_position(
464
+ session: IGPSSession, latitude: float, longitude: float
465
+ ) -> None:
466
+ """Posição de referência (ajuda o primeiro fix)."""
467
+ await _factory(session, 8, 9, [(1, float(latitude)), (2, float(longitude))])
468
+
469
+
470
+ async def set_power_save_time(session: IGPSSession, value: int) -> None:
471
+ """FACTORY/POWER_SAVE_TIME_SET (valor cru do firmware)."""
472
+ await _factory(session, 11, 11, [(1, value)])
473
+
474
+
475
+ async def set_sun_time(session: IGPSSession, sunrise: int, sunset: int) -> None:
476
+ """FACTORY/SUN_TIME_SET (valores crus; usados no backlight automático)."""
477
+ await _factory(session, 9, 10, [(1, sunrise), (2, sunset)])
478
+
479
+
480
+ async def set_filter(session: IGPSSession, name: str, enabled: bool) -> None:
481
+ await _factory(session, 14, 13, [(1, FILTERS[name]), (2, int(enabled))])
482
+
483
+
484
+ async def set_rtc(session: IGPSSession, local: datetime) -> None:
485
+ """FACTORY/RTC_SET. O iGS10S confirma mas o GPS sobrescreve a hora."""
486
+ await _factory(session, 12, 12, [(1, int((local - FIT_EPOCH).total_seconds()))])
487
+
488
+
489
+ async def simulate_activities(session: IGPSSession, count: int, size: int) -> None:
490
+ """FACTORY/SIM_FIT_SET: gera atividades .fit falsas (teste de fábrica)."""
491
+ await _factory(session, 7, 7, [(1, count), (2, size)])
492
+
493
+
494
+ async def set_serial(session: IGPSSession, serial: str) -> None:
495
+ """FACTORY/SN_SET: regrava o número de série."""
496
+ await _factory(session, 3, 3, [(1, serial)])
497
+
498
+
499
+ async def unbond(session: IGPSSession) -> None:
500
+ """BLE/UNBOND: desfaz o vínculo com o app (``sendCancelBonding``)."""
501
+ await session.simple(p.Service.BLE, 4)
502
+
503
+
504
+ async def enter_dfu(session: IGPSSession) -> None:
505
+ """FIRMWARE/BLE_UPDATE: reinicia no bootloader Nordic DFU.
506
+
507
+ Lá ele espera um .zip de firmware (ex.: nRF Connect / nrfutil). Costuma
508
+ reiniciar sem responder, então timeout conta como enviado.
509
+ """
510
+ try:
511
+ await session.simple(p.Service.FIRMWARE, 5, timeout=5)
512
+ except TimeoutError:
513
+ pass
514
+
22
515
 
23
516
  class IGPSClient:
24
- """Lê presença/bateria/device-info de um iGS10S via BLE."""
517
+ """Conveniência p/ CLI: abre a conexão, lê tudo e desconecta."""
25
518
 
26
519
  def __init__(
27
520
  self, address: str, name: str = "iGS10S", rssi: int | None = None
@@ -31,39 +524,5 @@ class IGPSClient:
31
524
  self._rssi = rssi
32
525
 
33
526
  async def async_read_state(self) -> IGPSDeviceState:
34
- """Conecta, lê o que o aparelho expõe, e devolve o snapshot."""
35
527
  async with BleakClient(self._address) as client:
36
- battery = await self._read(client, BATTERY_LEVEL_UUID)
37
- model = await self._read(client, MODEL_NUMBER_UUID)
38
- # O iGS10S expõe o firmware na Software Revision (0x2A28); outros
39
- # aparelhos usam a Firmware Revision (0x2A26). Tentamos as duas.
40
- firmware = await self._read(client, SOFTWARE_REVISION_UUID)
41
- if firmware is None:
42
- firmware = await self._read(client, FIRMWARE_REVISION_UUID)
43
- hardware = await self._read(client, HARDWARE_REVISION_UUID)
44
- manufacturer = await self._read(client, MANUFACTURER_NAME_UUID)
45
-
46
- return IGPSDeviceState(
47
- address=self._address,
48
- name=self._name,
49
- rssi=self._rssi,
50
- battery_level=parse_battery_level(battery) if battery is not None else None,
51
- model=decode_device_string(model) if model is not None else None,
52
- firmware=decode_device_string(firmware) if firmware is not None else None,
53
- hardware=decode_device_string(hardware) if hardware is not None else None,
54
- manufacturer=(
55
- decode_device_string(manufacturer)
56
- if manufacturer is not None
57
- else None
58
- ),
59
- )
60
-
61
- @staticmethod
62
- async def _read(client: BleakClient, uuid: str) -> bytes | None:
63
- """Lê a char se ela existir; None se o aparelho não a expõe."""
64
- if client.services.get_characteristic(uuid) is None:
65
- return None
66
- try:
67
- return await client.read_gatt_char(uuid)
68
- except Exception: # noqa: BLE001 - char some/erra => trata como ausente
69
- return None
528
+ return await read_state(client, self._address, self._name, self._rssi)
igps_ble/models.py CHANGED
@@ -2,15 +2,37 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class UserProfile:
11
+ """``user_config_data_msg`` (serviço USER_CONFIG). Unidades já convertidas."""
12
+
13
+ sex: int = 1 # 1 = masculino, 0 = feminino (``isGendar`` no app)
14
+ weight_kg: float = 0.0
15
+ age: int = 0
16
+ height_cm: int = 0
17
+ wheel_mm: int = 0
18
+ bike_weight_kg: float = 0.0
19
+ time_zone_s: int = 0
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class Activity:
24
+ """Uma atividade gravada no aparelho (lista do serviço CYCLING_DATA)."""
25
+
26
+ id: int # timestamp FIT cru — identifica a atividade nos comandos
27
+ start: datetime # horário local do aparelho (naive)
28
+ size: int # bytes do .fit
6
29
 
7
30
 
8
31
  @dataclass(frozen=True, slots=True)
9
32
  class IGPSDeviceState:
10
33
  """Snapshot do que a lib conseguiu ler do aparelho.
11
34
 
12
- Campos opcionais ficam None quando o aparelho não expõe a characteristic
13
- correspondente (ex.: sem Battery Service => battery_level None).
35
+ Campos opcionais ficam None quando o aparelho não expõe/responde o dado.
14
36
  """
15
37
 
16
38
  address: str
@@ -21,3 +43,17 @@ class IGPSDeviceState:
21
43
  firmware: str | None = None
22
44
  hardware: str | None = None
23
45
  manufacturer: str | None = None
46
+ # --- protocolo proprietário (protobuf no Nordic UART) ---
47
+ battery_voltage: float | None = None # V
48
+ serial: str | None = None
49
+ protocol_version: str | None = None
50
+ memory_total: int | None = None # unidade do aparelho (KB)
51
+ memory_free: int | None = None
52
+ temperature: float | None = None # °C, sensor interno
53
+ device_time: datetime | None = None # relógio do aparelho (local, naive)
54
+ cycling_status: str | None = None # "idle" | "recording" | "paused"
55
+ cycling_start: datetime | None = None
56
+ latitude: float | None = None # última posição GPS conhecida
57
+ longitude: float | None = None
58
+ ride: dict[str, int] = field(default_factory=dict) # rt_data_message bruto
59
+ activities: tuple[Activity, ...] | None = None
igps_ble/protocol.py ADDED
@@ -0,0 +1,210 @@
1
+ """iGPSPORT "gen 3" protobuf-over-NUS framing (iGS10S, iGS320, iGS50S, ...).
2
+
3
+ Reverse engineered from the iGPSPORT Ride Android app (com.qiwu.worldwide.ride
4
+ 8.06.46, package com.igpsport.blelib) and validated against a real iGS10S.
5
+
6
+ A request is a protobuf message written to the data channel (NUS #1 RX),
7
+ followed by a 20-byte header written to the control channel (NUS #2 RX):
8
+
9
+ [0] 0x01 (header) [1] service [2] sub-service (0xff = none)
10
+ [3] 0xff [4] operation [5] 0xff
11
+ [6] 0xff [7:9] payload length (big-endian)
12
+ [9] crc8(payload) [10] 0x01 (end type = protobuf)
13
+ [11:19] 0xff * 8 [19] crc8(header[0:19])
14
+
15
+ The device answers the same way (payload notifications first, then the
16
+ header on the control channel). A 0x02 frame on the control channel is an
17
+ ACK (``ConfirmCommand``): ``02 svc sub ff op ff ff status ...``.
18
+
19
+ CRC is CRC-8/MAXIM (reflected poly 0x31, init 0).
20
+
21
+ The protobuf payloads always start with ``1: service`` and ``2: operation``.
22
+ Only a tiny wire codec is needed, so we ship one instead of protoc output.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import struct
28
+ from dataclasses import dataclass
29
+
30
+ # NUS instances. Base 6e40000X-b5a3-f393-e0a9-e50e24dccaYe.
31
+ DATA_RX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
32
+ DATA_TX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
33
+ CONTROL_RX = "6e400002-b5a3-f393-e0a9-e50e24dcca8e"
34
+ CONTROL_TX = "6e400003-b5a3-f393-e0a9-e50e24dcca8e"
35
+ THIRD_RX = "6e400002-b5a3-f393-e0a9-e50e24dcca7e"
36
+ THIRD_TX = "6e400003-b5a3-f393-e0a9-e50e24dcca7e"
37
+ FOURTH_TX = "6e400003-b5a3-f393-e0a9-e50e24dcca6e"
38
+ TX_CHARS = (DATA_TX, CONTROL_TX, THIRD_TX, FOURTH_TX)
39
+
40
+ PACKET_SIZE = 20 # payload chunk per write (firmware ignores the rest)
41
+ FRAME_HEADER = 0x01
42
+ FRAME_ACK = 0x02
43
+
44
+
45
+ class Service:
46
+ """``Common.service_type_index`` (subset relevant to a bike computer)."""
47
+
48
+ FIRMWARE = 4
49
+ CYCLING_DATA = 6
50
+ USER_CONFIG = 9
51
+ BLE = 10
52
+ FACTORY = 11
53
+ CONFIG = 12
54
+ DEV_STATUS = 13
55
+ SENSOR = 14
56
+ DEV_VER_INFO = 17
57
+
58
+
59
+ # --------------------------------------------------------------------- CRC
60
+
61
+
62
+ def crc8(data: bytes) -> int:
63
+ crc = 0
64
+ for byte in data:
65
+ crc ^= byte
66
+ for _ in range(8):
67
+ crc = (crc >> 1) ^ 0x8C if crc & 1 else crc >> 1
68
+ return crc
69
+
70
+
71
+ def build_header(service: int, op: int, payload: bytes, sub: int = 0xFF) -> bytes:
72
+ head = (
73
+ bytes([FRAME_HEADER, service, sub, 0xFF, op, 0xFF, 0xFF])
74
+ + len(payload).to_bytes(2, "big")
75
+ + bytes([crc8(payload), 0x01])
76
+ + b"\xff" * 8
77
+ )
78
+ return head + bytes([crc8(head)])
79
+
80
+
81
+ def build_ack(service: int, op: int, status: int = 0, sub: int = 0xFF) -> bytes:
82
+ """``ConfirmCommand``: confirma (0) ou pede reenvio (1) de um pedaço."""
83
+ head = bytes([FRAME_ACK, service, sub, 0xFF, op, 0xFF, 0xFF, status]) + b"\xff" * 11
84
+ return head + bytes([crc8(head)])
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class Header:
89
+ kind: int
90
+ service: int
91
+ sub: int
92
+ op: int
93
+ length: int
94
+ payload_crc: int
95
+ raw: bytes
96
+
97
+ @property
98
+ def last(self) -> bool:
99
+ """Último pedaço de uma transferência de arquivo (end type 3)."""
100
+ return self.raw[10] == 3
101
+
102
+ @property
103
+ def status(self) -> int:
104
+ """ACK status byte (``ConfirmCommand.status``)."""
105
+ return self.raw[7]
106
+
107
+
108
+ def parse_header(frame: bytes) -> Header | None:
109
+ if len(frame) != 20 or frame[0] not in (FRAME_HEADER, FRAME_ACK):
110
+ return None
111
+ if crc8(frame[:19]) != frame[19]:
112
+ return None
113
+ return Header(
114
+ kind=frame[0],
115
+ service=frame[1],
116
+ sub=frame[2],
117
+ op=frame[4],
118
+ length=int.from_bytes(frame[7:9], "big"),
119
+ payload_crc=frame[9],
120
+ raw=bytes(frame),
121
+ )
122
+
123
+
124
+ # ---------------------------------------------------------------- protobuf
125
+
126
+
127
+ def _varint(value: int) -> bytes:
128
+ value &= (1 << 64) - 1 # negative int32/int64 -> 10-byte two's complement
129
+ out = bytearray()
130
+ while True:
131
+ byte = value & 0x7F
132
+ value >>= 7
133
+ if value:
134
+ out.append(byte | 0x80)
135
+ else:
136
+ out.append(byte)
137
+ return bytes(out)
138
+
139
+
140
+ def encode(fields: list[tuple[int, int | bytes | str | list]]) -> bytes:
141
+ """Encode ``[(field_no, value)]``. int → varint, float → double,
142
+ bytes/str → len-delimited, list → nested message (same shape)."""
143
+ out = bytearray()
144
+ for number, value in fields:
145
+ if isinstance(value, float): # double (wire type 1)
146
+ out += _varint(number << 3 | 1) + struct.pack("<d", value)
147
+ continue
148
+ if isinstance(value, bool | int):
149
+ out += _varint(number << 3) + _varint(int(value))
150
+ continue
151
+ if isinstance(value, list):
152
+ value = encode(value)
153
+ elif isinstance(value, str):
154
+ value = value.encode()
155
+ out += _varint(number << 3 | 2) + _varint(len(value)) + value
156
+ return bytes(out)
157
+
158
+
159
+ def decode(data: bytes) -> dict[int, list]:
160
+ """Decode one message level into ``{field_no: [raw values]}``.
161
+
162
+ Varints come back as unsigned ints, len-delimited as bytes, fixed as int.
163
+ Callers decide whether bytes are a nested message (``decode`` again).
164
+ """
165
+ out: dict[int, list] = {}
166
+ i = 0
167
+ while i < len(data):
168
+ key, i = _read_varint(data, i)
169
+ number, wire = key >> 3, key & 7
170
+ if wire == 0:
171
+ value, i = _read_varint(data, i)
172
+ elif wire == 2:
173
+ size, i = _read_varint(data, i)
174
+ value, i = bytes(data[i : i + size]), i + size
175
+ elif wire == 5:
176
+ value, i = int.from_bytes(data[i : i + 4], "little"), i + 4
177
+ elif wire == 1:
178
+ value, i = int.from_bytes(data[i : i + 8], "little"), i + 8
179
+ else:
180
+ raise ValueError(f"unsupported wire type {wire}")
181
+ out.setdefault(number, []).append(value)
182
+ return out
183
+
184
+
185
+ def _read_varint(data: bytes, i: int) -> tuple[int, int]:
186
+ shift = result = 0
187
+ while True:
188
+ if i >= len(data):
189
+ raise ValueError("truncated varint")
190
+ byte = data[i]
191
+ i += 1
192
+ result |= (byte & 0x7F) << shift
193
+ if not byte & 0x80:
194
+ return result, i
195
+ shift += 7
196
+
197
+
198
+ def int32(value: int) -> int:
199
+ """Reinterpret an unsigned varint as a signed int32/int64."""
200
+ if value >= 1 << 63:
201
+ return value - (1 << 64)
202
+ if value >= 1 << 31 and value < 1 << 32:
203
+ return value - (1 << 32)
204
+ return value
205
+
206
+
207
+ def request(service: int, op: int, extra=(), sub: int = 0xFF) -> tuple[bytes, bytes]:
208
+ """Return ``(payload, header)`` for a ``{1: service, 2: op, ...}`` request."""
209
+ payload = encode([(1, service), (2, op), *extra])
210
+ return payload, build_header(service, op, payload, sub)
igps_ble/scanner.py CHANGED
@@ -26,7 +26,5 @@ async def discover_devices(timeout: float = 10.0) -> list[IGPSDeviceState]:
26
26
  name = adv.local_name or device.name
27
27
  if not is_igps_device(name):
28
28
  continue
29
- results.append(
30
- IGPSDeviceState(address=address, name=name, rssi=adv.rssi)
31
- )
29
+ results.append(IGPSDeviceState(address=address, name=name, rssi=adv.rssi))
32
30
  return results
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-igps-ble
3
+ Version: 0.3.4
4
+ Summary: Pure-Python BLE library for the iGPSPORT iGS10S cycling computer (battery, sensors, ride status, activities, profile)
5
+ Author-email: Hudson Brendon <contato.hudsonbrendon@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/hudsonbrendon/python-igps-ble
8
+ Project-URL: Issues, https://github.com/hudsonbrendon/python-igps-ble/issues
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: bleak>=0.22
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=8; extra == "dev"
15
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
16
+ Requires-Dist: ruff>=0.5; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ <p align="center">
20
+ <img src="assets/igpsport-logo.png" alt="iGPSPORT" width="420">
21
+ </p>
22
+
23
+ # python-igps-ble
24
+
25
+ [![CI](https://github.com/hudsonbrendon/python-igps-ble/actions/workflows/ci.yml/badge.svg)](https://github.com/hudsonbrendon/python-igps-ble/actions/workflows/ci.yml)
26
+ [![PyPI](https://img.shields.io/pypi/v/python-igps-ble)](https://pypi.org/project/python-igps-ble/)
27
+ [![Python](https://img.shields.io/pypi/pyversions/python-igps-ble)](https://pypi.org/project/python-igps-ble/)
28
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
29
+
30
+ Talk to an **iGPSPORT iGS10S** cycling computer over Bluetooth LE from Python —
31
+ battery, internal sensors, ride status, stored activities, last GPS position and
32
+ the rider/bike profile, through iGPSPORT's proprietary protobuf-over-Nordic-UART
33
+ protocol (reverse engineered from the official app, no pairing or login needed).
34
+
35
+ This library powers the
36
+ [**iGPSPORT iGS10S Home Assistant integration**](https://github.com/hudsonbrendon/ha-igps-ble),
37
+ but works standalone in any async Python project (or straight from the command line).
38
+
39
+ > Protocol notes:
40
+ > [`ha-igps-ble/docs/PROTOCOL.md`](https://github.com/hudsonbrendon/ha-igps-ble/blob/main/docs/PROTOCOL.md).
41
+
42
+ ## Features
43
+
44
+ - 🔌 **Async BLE control** built on [`bleak`](https://github.com/hbldh/bleak) —
45
+ works on Linux, macOS, and Windows.
46
+ - 🔍 **Discovery helper** — `discover_devices()` finds nearby iGPSPORT devices
47
+ (presence + RSSI).
48
+ - 🏷️ **Device info** — manufacturer, hardware revision, firmware, serial and
49
+ protocol version.
50
+ - 🔋 **Battery** — level (%) and voltage.
51
+ - 🌡️ **Sensors** — internal temperature, free memory, device clock.
52
+ - 🚴 **Ride status** — idle / recording / paused, live ride fields while recording,
53
+ last GPS position.
54
+ - 🗂️ **Activities** — list of rides stored on the device (start time, size).
55
+ - 💾 **`.fit` download** — `download_activity(session, id, size)` with per-chunk CRC and
56
+ size checks.
57
+ - 🧹 **Maintenance** — delete one/all activities, `factory_control()` (format,
58
+ factory reset, settings reset, lock, logs, test mode), unbind, DFU mode.
59
+ - 🛰️ **GPS** — `gps_control()`, `set_gnss()`, `set_gps_dynamic()`, `set_gps_position()`.
60
+ - 🧪 **Raw** — `command(session, service, op, fields)` for anything else.
61
+ - ⚙️ **Profile** — write rider weight/height/age/sex, wheel circumference, bike
62
+ weight and time zone (`set_profile`).
63
+ - 🖥️ **CLI** — `igps-ble scan / info` for quick testing.
64
+
65
+ ## Requirements
66
+
67
+ - Python **3.11** or newer.
68
+ - A Bluetooth LE adapter (built-in or USB).
69
+ - An iGPSPORT iGS10S (other iGPSPORT models exposing the same standard services
70
+ may also work).
71
+
72
+ ## Installation
73
+
74
+ ```bash
75
+ pip install python-igps-ble
76
+ ```
77
+
78
+ ## CLI usage
79
+
80
+ ```bash
81
+ igps-ble scan # find nearby iGPSPORT devices
82
+ igps-ble info AA:BB:CC:DD:EE:FF # connect and read everything
83
+ ```
84
+
85
+ ## Library usage
86
+
87
+ ```python
88
+ import asyncio
89
+ from igps_ble import IGPSDeviceState
90
+ from igps_ble.scanner import discover_devices
91
+ from igps_ble.client import IGPSClient
92
+
93
+
94
+ async def main():
95
+ for dev in await discover_devices(timeout=10):
96
+ state: IGPSDeviceState = await IGPSClient(
97
+ dev.address, dev.name
98
+ ).async_read_state()
99
+ print(state.manufacturer, state.model, state.firmware, state.battery_level)
100
+
101
+
102
+ asyncio.run(main())
103
+ ```
104
+
105
+ `IGPSClient` accepts a `bleak` `BLEDevice` (preferred — e.g. from Home Assistant's
106
+ shared scanner or a Bluetooth proxy) or a string MAC/UUID address.
107
+
108
+ ### API
109
+
110
+ | Symbol | Description |
111
+ |---|---|
112
+ | `discover_devices(timeout=10.0)` | List nearby iGPSPORT devices as `IGPSDeviceState` (presence + RSSI; does not connect). |
113
+ | `is_igps_device(local_name)` | `True` if an advertisement name matches a known iGPSPORT prefix. |
114
+ | `IGPSClient(address, name="iGS10S", rssi=None)` | Async client; `await client.async_read_state()` connects and returns an `IGPSDeviceState`. |
115
+ | `read_state(client, address, name, rssi, session=None)` | Read everything over an already-connected `BleakClient`. |
116
+ | `IGPSSession(client)` | Request/response over the NUS channels; `await session.start()` once per connection. |
117
+ | `set_profile(session, UserProfile(...))` | Write the whole rider/bike profile (the device does not report it back). |
118
+ | `IGPSDeviceState` | Frozen dataclass with everything read (battery, sensors, ride status, GPS, activities…). |
119
+ | `igps_ble.protocol` | Framing (20-byte header, CRC-8/MAXIM) and a tiny protobuf codec. |
120
+ | `parse_battery_level(data)` / `decode_device_string(data)` | Pure parsers for the standard Bluetooth SIG characteristics. |
121
+
122
+ ## Scope
123
+
124
+ | Data | Supported | Source |
125
+ |------|-----------|--------|
126
+ | Presence | ✅ | BLE advertisement |
127
+ | Manufacturer / hardware / firmware | ✅ | Device Information Service `0x180A` |
128
+ | Battery % / voltage | ✅ | FACTORY service (protobuf) |
129
+ | Serial, memory, temperature, clock | ✅ | FACTORY service |
130
+ | Ride status, last GPS fix, live ride fields | ✅ | DEV_STATUS service (live field units unconfirmed) |
131
+ | Stored activity list | ✅ | CYCLING_DATA service |
132
+ | Rider/bike profile, time zone | ✅ write-only | USER_CONFIG service |
133
+ | `.fit` download | ✅ | CYCLING_DATA FILE_GET |
134
+ | Delete activities, format, factory reset, GPS/factory settings, unbind, DFU | ✅ not live-tested | FACTORY / CYCLING_DATA / BLE / FIRMWARE |
135
+ | Display/page settings, time sync | ❌ | unsupported by the iGS10S firmware |
136
+
137
+ ## Development
138
+
139
+ ```bash
140
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
141
+ .venv/bin/pytest
142
+ ```
143
+
144
+ ## Credits
145
+
146
+ Built to back the [`ha-igps-ble`](https://github.com/hudsonbrendon/ha-igps-ble)
147
+ Home Assistant integration. Author [@hudsonbrendon](https://github.com/hudsonbrendon).
148
+
149
+ ## License
150
+
151
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,14 @@
1
+ igps_ble/__init__.py,sha256=CutdfSzl3Zl_G1xmPyfItiWlcAiiBAUJRKKoC8Qad6A,432
2
+ igps_ble/__main__.py,sha256=GX7qDcyGKu7MwhDyhPzqe3vEwMHadg0axIQBTSbdrxU,1273
3
+ igps_ble/client.py,sha256=BMNYH4yi7J6neDvpmAW2yBpxjq4r3a87v7atYNZjZuk,18994
4
+ igps_ble/const.py,sha256=0PfoY4CCFypAJ4bEKyBpFLDZufB6aRZKd04IFdI35sM,1161
5
+ igps_ble/models.py,sha256=xm7zEXypx21PnhreKpuj_xzcmhnhuTzJxFSsV4HAv_E,2010
6
+ igps_ble/parser.py,sha256=IkY_fpODaJkXwSilkA5JzXks1VEP5MsoHjf4aOr9JtE,627
7
+ igps_ble/protocol.py,sha256=KDtRI-EhIfLox-jrUb8u4Lrub8mJKhOCUEVQCIpdwGU,6752
8
+ igps_ble/scanner.py,sha256=ogezk2bSMm7_Eivar-3a_O7tFn69871egWBS1lAkyaA,1063
9
+ python_igps_ble-0.3.4.dist-info/licenses/LICENSE,sha256=4Zgd3fbLJqWSkwKA-hh1rNN6DC9tNQ3rWLX93fingOw,1071
10
+ python_igps_ble-0.3.4.dist-info/METADATA,sha256=ZFO5UIidvuFozzcpZDCWTv9lWB8NN2Wen6NAlT2QQvE,6489
11
+ python_igps_ble-0.3.4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ python_igps_ble-0.3.4.dist-info/entry_points.txt,sha256=WmO3pSZ-qD2ZfHtnxxqyvUycW8LEwMFIJIC1k7oFSuY,52
13
+ python_igps_ble-0.3.4.dist-info/top_level.txt,sha256=69O33W2-0wC37bi3yvYxMJqOVdk612_CqJYgxErMS8A,9
14
+ python_igps_ble-0.3.4.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hudson Brendon
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.
@@ -1,78 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: python-igps-ble
3
- Version: 0.1.0
4
- Summary: Pure-Python BLE library for the iGPSPORT iGS10S cycling computer (presence, battery, device info)
5
- Author-email: Hudson Brendon <contato.hudsonbrendon@gmail.com>
6
- License: MIT
7
- Project-URL: Homepage, https://github.com/hudsonbrendon/python-igps-ble
8
- Project-URL: Issues, https://github.com/hudsonbrendon/python-igps-ble/issues
9
- Requires-Python: >=3.11
10
- Description-Content-Type: text/markdown
11
- Requires-Dist: bleak>=0.22
12
- Provides-Extra: dev
13
- Requires-Dist: pytest>=8; extra == "dev"
14
- Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
15
- Requires-Dist: ruff>=0.5; extra == "dev"
16
-
17
- # python-igps-ble
18
-
19
- Pure-Python BLE library for the **iGPSPORT iGS10S** cycling computer.
20
-
21
- Reads, over standard Bluetooth Low Energy, what the device exposes to
22
- third parties: **presence**, **battery level**, and **device info**
23
- (model / firmware / manufacturer). The proprietary `.fit` sync used by the
24
- official iGPSPORT app is **out of scope** (see `ha-igps-ble/docs/PROTOCOL.md`).
25
-
26
- > Built to back the [`ha-igps-ble`](https://github.com/hudsonbrendon/ha-igps-ble)
27
- > Home Assistant integration, but usable standalone.
28
-
29
- ## Install
30
-
31
- ```bash
32
- pip install python-igps-ble
33
- ```
34
-
35
- ## CLI
36
-
37
- ```bash
38
- igps-ble scan # procura aparelhos iGPSPORT por perto
39
- igps-ble info AA:BB:CC:DD:EE:FF # bateria + device-info
40
- ```
41
-
42
- ## Uso programático
43
-
44
- ```python
45
- import asyncio
46
- from igps_ble import IGPSDeviceState
47
- from igps_ble.scanner import discover_devices
48
- from igps_ble.client import IGPSClient
49
-
50
- async def main():
51
- for dev in await discover_devices(timeout=10):
52
- state: IGPSDeviceState = await IGPSClient(dev.address, dev.name).async_read_state()
53
- print(state)
54
-
55
- asyncio.run(main())
56
- ```
57
-
58
- ## Escopo
59
-
60
- | Dado | Suportado | Fonte |
61
- |------|-----------|-------|
62
- | Presença | ✅ | advertisement BLE |
63
- | Bateria % | ✅* | Battery Service `0x180F` |
64
- | Modelo / firmware | ✅* | Device Information `0x180A` |
65
- | Velocidade / distância / pedalada | ❌ | sync proprietário (não exposto por BLE) |
66
-
67
- \* depende de o iGS10S expor o serviço SIG correspondente — confirmado por recon.
68
-
69
- ## Desenvolvimento
70
-
71
- ```bash
72
- python -m venv .venv && .venv/bin/pip install -e ".[dev]"
73
- .venv/bin/pytest
74
- ```
75
-
76
- ## Licença
77
-
78
- MIT
@@ -1,12 +0,0 @@
1
- igps_ble/__init__.py,sha256=eeV-l5_0sdRkAEPeB9uUUE4G2dZ-rCq1T6y1UJhDWbk,178
2
- igps_ble/__main__.py,sha256=mCoZbDckv8FDd613fWJE0pTaCVwv2fG3Snn2V6KhWGY,1414
3
- igps_ble/client.py,sha256=f66p39IP5g-UVkOn30JACZrjOOPuQs5IGJ6_7g665gg,2728
4
- igps_ble/const.py,sha256=0PfoY4CCFypAJ4bEKyBpFLDZufB6aRZKd04IFdI35sM,1161
5
- igps_ble/models.py,sha256=H6UNnnMfVovc0EsqYHyC0oIPPvnJ99i8Vi9y_SyWL-I,620
6
- igps_ble/parser.py,sha256=IkY_fpODaJkXwSilkA5JzXks1VEP5MsoHjf4aOr9JtE,627
7
- igps_ble/scanner.py,sha256=aJj3bE_K9ky9fJKicKLrRoWf1YSeXZRRsGghpzBauP4,1085
8
- python_igps_ble-0.1.0.dist-info/METADATA,sha256=QX_XkHtYvVZV8Dg7aNWzuIYMCo7P9bvi8z1aV-QHjcs,2253
9
- python_igps_ble-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
- python_igps_ble-0.1.0.dist-info/entry_points.txt,sha256=WmO3pSZ-qD2ZfHtnxxqyvUycW8LEwMFIJIC1k7oFSuY,52
11
- python_igps_ble-0.1.0.dist-info/top_level.txt,sha256=69O33W2-0wC37bi3yvYxMJqOVdk612_CqJYgxErMS8A,9
12
- python_igps_ble-0.1.0.dist-info/RECORD,,