python-gopro 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.
- pygopro/__init__.py +67 -0
- pygopro/__main__.py +3 -0
- pygopro/ble.py +451 -0
- pygopro/cli.py +144 -0
- pygopro/const.py +235 -0
- pygopro/exceptions.py +38 -0
- pygopro/firmware.py +60 -0
- pygopro/http.py +373 -0
- pygopro/models.py +228 -0
- pygopro/protocol.py +189 -0
- pygopro/schema.py +163 -0
- python_gopro-0.1.0.dist-info/METADATA +103 -0
- python_gopro-0.1.0.dist-info/RECORD +16 -0
- python_gopro-0.1.0.dist-info/WHEEL +4 -0
- python_gopro-0.1.0.dist-info/entry_points.txt +2 -0
- python_gopro-0.1.0.dist-info/licenses/LICENSE +21 -0
pygopro/__init__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Local async client for GoPro cameras (Open GoPro HTTP/COHN + BLE)."""
|
|
2
|
+
|
|
3
|
+
from .const import GOPRO_MANUFACTURER_ID, GOPRO_SERVICE_UUID, PresetGroup, Status
|
|
4
|
+
from .exceptions import (
|
|
5
|
+
GoProAuthError,
|
|
6
|
+
GoProBleError,
|
|
7
|
+
GoProCommandError,
|
|
8
|
+
GoProConnectionError,
|
|
9
|
+
GoProControllerUnavailableError,
|
|
10
|
+
GoProError,
|
|
11
|
+
)
|
|
12
|
+
from .firmware import fetch_catalog, latest_for
|
|
13
|
+
from .http import GoProHttp, build_ssl_context
|
|
14
|
+
from .models import (
|
|
15
|
+
AccessPoint,
|
|
16
|
+
CameraInfo,
|
|
17
|
+
CameraState,
|
|
18
|
+
CohnCredentials,
|
|
19
|
+
CohnStatus,
|
|
20
|
+
FirmwareRelease,
|
|
21
|
+
HardwareInfo,
|
|
22
|
+
MediaFile,
|
|
23
|
+
Preset,
|
|
24
|
+
)
|
|
25
|
+
from .schema import Schema, Setting, SettingOption, StatusField
|
|
26
|
+
|
|
27
|
+
__version__ = "0.1.0"
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"GOPRO_MANUFACTURER_ID",
|
|
31
|
+
"GOPRO_SERVICE_UUID",
|
|
32
|
+
"AccessPoint",
|
|
33
|
+
"CameraInfo",
|
|
34
|
+
"CameraState",
|
|
35
|
+
"CohnCredentials",
|
|
36
|
+
"CohnStatus",
|
|
37
|
+
"FirmwareRelease",
|
|
38
|
+
"GoProAuthError",
|
|
39
|
+
"GoProBle",
|
|
40
|
+
"GoProBleError",
|
|
41
|
+
"GoProCommandError",
|
|
42
|
+
"GoProConnectionError",
|
|
43
|
+
"GoProControllerUnavailableError",
|
|
44
|
+
"GoProError",
|
|
45
|
+
"GoProHttp",
|
|
46
|
+
"HardwareInfo",
|
|
47
|
+
"MediaFile",
|
|
48
|
+
"Preset",
|
|
49
|
+
"PresetGroup",
|
|
50
|
+
"Schema",
|
|
51
|
+
"Setting",
|
|
52
|
+
"SettingOption",
|
|
53
|
+
"Status",
|
|
54
|
+
"StatusField",
|
|
55
|
+
"build_ssl_context",
|
|
56
|
+
"fetch_catalog",
|
|
57
|
+
"latest_for",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def __getattr__(name: str):
|
|
62
|
+
# bleak is optional: import the BLE client lazily.
|
|
63
|
+
if name == "GoProBle":
|
|
64
|
+
from .ble import GoProBle
|
|
65
|
+
|
|
66
|
+
return GoProBle
|
|
67
|
+
raise AttributeError(name)
|
pygopro/__main__.py
ADDED
pygopro/ble.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
"""Async BLE client (Open GoPro over GATT), using bleak.
|
|
2
|
+
|
|
3
|
+
Validated live on a MAX2 (H24.02.01.34.00):
|
|
4
|
+
|
|
5
|
+
* Notifications on the response characteristics require an encrypted link; the first
|
|
6
|
+
``start_notify`` fails with "Encryption is insufficient" and makes macOS/BlueZ pair. The camera
|
|
7
|
+
must be in pairing mode (Preferences > Connections > Connect Device) the first time.
|
|
8
|
+
* Messages must fit in one write (MTU 515 on macOS); continuation packets written with response
|
|
9
|
+
are rejected with GATT error 0xD1.
|
|
10
|
+
* Protobuf queries (feature 0xF5) go to the *query* characteristic, commands (0xF1) and network
|
|
11
|
+
management (0x02) to their own characteristics.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import contextlib
|
|
18
|
+
import logging
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from datetime import datetime
|
|
21
|
+
from typing import TYPE_CHECKING, Any
|
|
22
|
+
|
|
23
|
+
from .const import (
|
|
24
|
+
ACTION_CLEAR_COHN_CERT,
|
|
25
|
+
ACTION_CONNECT,
|
|
26
|
+
ACTION_CONNECT_NEW,
|
|
27
|
+
ACTION_CREATE_COHN_CERT,
|
|
28
|
+
ACTION_GET_COHN_CERT,
|
|
29
|
+
ACTION_GET_COHN_STATUS,
|
|
30
|
+
ACTION_GET_LAST_MEDIA,
|
|
31
|
+
ACTION_NOTIF_PROVISIONING,
|
|
32
|
+
ACTION_NOTIF_SCAN,
|
|
33
|
+
ACTION_SCAN_ENTRIES,
|
|
34
|
+
ACTION_SCAN_START,
|
|
35
|
+
ACTION_SET_CAMERA_CONTROL,
|
|
36
|
+
ACTION_SET_COHN_SETTING,
|
|
37
|
+
ACTION_SET_TURBO,
|
|
38
|
+
FEATURE_COMMAND,
|
|
39
|
+
FEATURE_NETWORK,
|
|
40
|
+
FEATURE_QUERY,
|
|
41
|
+
KEEP_ALIVE_SETTING,
|
|
42
|
+
KEEP_ALIVE_VALUE,
|
|
43
|
+
UUID_AP_PASSWORD,
|
|
44
|
+
UUID_AP_SSID,
|
|
45
|
+
UUID_COMMAND,
|
|
46
|
+
UUID_COMMAND_RESP,
|
|
47
|
+
UUID_NETWORK,
|
|
48
|
+
UUID_NETWORK_RESP,
|
|
49
|
+
UUID_QUERY,
|
|
50
|
+
UUID_QUERY_RESP,
|
|
51
|
+
UUID_SETTINGS,
|
|
52
|
+
UUID_SETTINGS_RESP,
|
|
53
|
+
BleCommand,
|
|
54
|
+
BleQuery,
|
|
55
|
+
CohnState,
|
|
56
|
+
ProvisioningState,
|
|
57
|
+
)
|
|
58
|
+
from .exceptions import GoProBleError
|
|
59
|
+
from .models import AccessPoint, CohnCredentials, CohnStatus, HardwareInfo
|
|
60
|
+
from .protocol import (
|
|
61
|
+
Reassembler,
|
|
62
|
+
as_int,
|
|
63
|
+
fragment,
|
|
64
|
+
parse_id_values,
|
|
65
|
+
parse_tlv,
|
|
66
|
+
pb_decode,
|
|
67
|
+
pb_encode,
|
|
68
|
+
pb_first,
|
|
69
|
+
pb_str,
|
|
70
|
+
tlv_command,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
if TYPE_CHECKING:
|
|
74
|
+
from bleak import BleakClient
|
|
75
|
+
from bleak.backends.device import BLEDevice
|
|
76
|
+
|
|
77
|
+
_LOGGER = logging.getLogger(__name__)
|
|
78
|
+
_PROTO_FEATURES = (FEATURE_NETWORK, FEATURE_COMMAND, FEATURE_QUERY)
|
|
79
|
+
RESPONSE_UUIDS = (UUID_COMMAND_RESP, UUID_SETTINGS_RESP, UUID_QUERY_RESP, UUID_NETWORK_RESP)
|
|
80
|
+
|
|
81
|
+
ClientFactory = Callable[["BLEDevice | str"], "asyncio.Future[BleakClient]"]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class GoProBle:
|
|
85
|
+
"""One BLE session with a camera.
|
|
86
|
+
|
|
87
|
+
``connect_func`` lets Home Assistant pass ``bleak_retry_connector.establish_connection``;
|
|
88
|
+
by default a plain ``BleakClient`` is used.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
def __init__(
|
|
92
|
+
self,
|
|
93
|
+
device: BLEDevice | str,
|
|
94
|
+
*,
|
|
95
|
+
connect_func: Callable[..., Any] | None = None,
|
|
96
|
+
timeout: float = 15.0,
|
|
97
|
+
pair: bool = True,
|
|
98
|
+
) -> None:
|
|
99
|
+
self._device = device
|
|
100
|
+
self._connect_func = connect_func
|
|
101
|
+
self._timeout = timeout
|
|
102
|
+
self._pair = pair
|
|
103
|
+
self._client: BleakClient | None = None
|
|
104
|
+
self._asm = {u: Reassembler() for u in RESPONSE_UUIDS}
|
|
105
|
+
self._waiters: dict[Any, asyncio.Queue[bytes]] = {}
|
|
106
|
+
self._lock = asyncio.Lock()
|
|
107
|
+
self.status_callbacks: list[Callable[[dict[int, bytes]], None]] = []
|
|
108
|
+
self.setting_callbacks: list[Callable[[dict[int, bytes]], None]] = []
|
|
109
|
+
|
|
110
|
+
# -- connection ----------------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def connected(self) -> bool:
|
|
114
|
+
return bool(self._client and self._client.is_connected)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def mtu(self) -> int:
|
|
118
|
+
try:
|
|
119
|
+
return int(self._client.mtu_size) if self._client else 23
|
|
120
|
+
except Exception:
|
|
121
|
+
return 23
|
|
122
|
+
|
|
123
|
+
async def connect(self) -> None:
|
|
124
|
+
from bleak import BleakClient
|
|
125
|
+
|
|
126
|
+
if self.connected:
|
|
127
|
+
return
|
|
128
|
+
if self._connect_func is not None:
|
|
129
|
+
self._client = await self._connect_func(BleakClient, self._device, getattr(self._device, "name", "GoPro"))
|
|
130
|
+
else:
|
|
131
|
+
self._client = BleakClient(self._device, timeout=self._timeout)
|
|
132
|
+
await self._client.connect()
|
|
133
|
+
if self._pair:
|
|
134
|
+
with contextlib.suppress(Exception): # macOS pairs implicitly; some backends lack pair()
|
|
135
|
+
await self._client.pair()
|
|
136
|
+
last: Exception | None = None
|
|
137
|
+
for _ in range(12):
|
|
138
|
+
try:
|
|
139
|
+
for uuid in RESPONSE_UUIDS:
|
|
140
|
+
await self._client.start_notify(uuid, self._on_notify)
|
|
141
|
+
break
|
|
142
|
+
except Exception as err:
|
|
143
|
+
last = err
|
|
144
|
+
_LOGGER.debug("waiting for encryption/pairing: %s", err)
|
|
145
|
+
await asyncio.sleep(5)
|
|
146
|
+
else:
|
|
147
|
+
await self.disconnect()
|
|
148
|
+
raise GoProBleError(f"could not enable notifications (camera not paired?): {last}")
|
|
149
|
+
|
|
150
|
+
async def disconnect(self) -> None:
|
|
151
|
+
if self._client:
|
|
152
|
+
with contextlib.suppress(Exception):
|
|
153
|
+
await self._client.disconnect()
|
|
154
|
+
self._client = None
|
|
155
|
+
|
|
156
|
+
async def __aenter__(self) -> GoProBle:
|
|
157
|
+
await self.connect()
|
|
158
|
+
return self
|
|
159
|
+
|
|
160
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
161
|
+
await self.disconnect()
|
|
162
|
+
|
|
163
|
+
# -- transport -----------------------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def _on_notify(self, char: Any, data: bytearray) -> None:
|
|
166
|
+
uuid = str(getattr(char, "uuid", char)).lower()
|
|
167
|
+
asm = self._asm.get(uuid)
|
|
168
|
+
if asm is None:
|
|
169
|
+
return
|
|
170
|
+
msg = asm.feed(bytes(data))
|
|
171
|
+
if msg is None or not msg:
|
|
172
|
+
return
|
|
173
|
+
if msg[0] in _PROTO_FEATURES and len(msg) >= 2:
|
|
174
|
+
key: Any = ("pb", msg[0], msg[1])
|
|
175
|
+
payload = msg[2:]
|
|
176
|
+
elif uuid == UUID_QUERY_RESP and msg[0] in (BleQuery.NOTIF_STATUS_VALUE, BleQuery.NOTIF_SETTING_VALUE):
|
|
177
|
+
values = parse_id_values(msg[2:])
|
|
178
|
+
cbs = self.status_callbacks if msg[0] == BleQuery.NOTIF_STATUS_VALUE else self.setting_callbacks
|
|
179
|
+
for cb in cbs:
|
|
180
|
+
cb(values)
|
|
181
|
+
return
|
|
182
|
+
else:
|
|
183
|
+
key, payload = ("tlv", uuid, msg[0]), msg
|
|
184
|
+
self._queue(key).put_nowait(payload)
|
|
185
|
+
|
|
186
|
+
def _queue(self, key: Any) -> asyncio.Queue[bytes]:
|
|
187
|
+
return self._waiters.setdefault(key, asyncio.Queue())
|
|
188
|
+
|
|
189
|
+
async def _write(self, uuid: str, payload: bytes) -> None:
|
|
190
|
+
if not self._client:
|
|
191
|
+
raise GoProBleError("not connected")
|
|
192
|
+
for packet in fragment(payload, max(20, self.mtu - 3)):
|
|
193
|
+
await self._client.write_gatt_char(uuid, packet, response=True)
|
|
194
|
+
|
|
195
|
+
async def _wait(self, key: Any, timeout: float | None = None) -> bytes:
|
|
196
|
+
try:
|
|
197
|
+
return await asyncio.wait_for(self._queue(key).get(), timeout or self._timeout)
|
|
198
|
+
except TimeoutError as err:
|
|
199
|
+
raise GoProBleError(f"timeout waiting for {key}") from err
|
|
200
|
+
|
|
201
|
+
async def tlv(self, uuid: str, resp_uuid: str, command_id: int, *params: bytes, timeout: float | None = None) -> bytes:
|
|
202
|
+
"""Send a TLV message and return the full response ``[id][status][payload...]``."""
|
|
203
|
+
async with self._lock:
|
|
204
|
+
q = self._queue(("tlv", resp_uuid, command_id))
|
|
205
|
+
while not q.empty():
|
|
206
|
+
q.get_nowait()
|
|
207
|
+
await self._write(uuid, tlv_command(command_id, *params))
|
|
208
|
+
resp = await self._wait(("tlv", resp_uuid, command_id), timeout)
|
|
209
|
+
if len(resp) > 1 and resp[1] != 0:
|
|
210
|
+
raise GoProBleError(f"command 0x{command_id:02x} failed with status {resp[1]}")
|
|
211
|
+
return resp
|
|
212
|
+
|
|
213
|
+
async def proto(
|
|
214
|
+
self,
|
|
215
|
+
uuid: str,
|
|
216
|
+
feature: int,
|
|
217
|
+
action: int,
|
|
218
|
+
fields: list[tuple[int, Any]] | None = None,
|
|
219
|
+
*,
|
|
220
|
+
response_action: int | None = None,
|
|
221
|
+
timeout: float | None = None,
|
|
222
|
+
) -> dict[int, list[Any]]:
|
|
223
|
+
key = ("pb", feature, response_action if response_action is not None else action | 0x80)
|
|
224
|
+
async with self._lock:
|
|
225
|
+
q = self._queue(key)
|
|
226
|
+
while not q.empty():
|
|
227
|
+
q.get_nowait()
|
|
228
|
+
await self._write(uuid, bytes([feature, action]) + pb_encode(fields or []))
|
|
229
|
+
return pb_decode(await self._wait(key, timeout))
|
|
230
|
+
|
|
231
|
+
async def wait_proto(self, feature: int, action: int, timeout: float = 30) -> dict[int, list[Any]]:
|
|
232
|
+
return pb_decode(await self._wait(("pb", feature, action), timeout))
|
|
233
|
+
|
|
234
|
+
# -- commands ------------------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
async def get_hardware_info(self) -> HardwareInfo:
|
|
237
|
+
resp = await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.GET_HARDWARE_INFO)
|
|
238
|
+
f = [v.decode(errors="replace") if isinstance(v, bytes) else v for v in parse_tlv(resp[2:])]
|
|
239
|
+
raw = parse_tlv(resp[2:])
|
|
240
|
+
return HardwareInfo(
|
|
241
|
+
model_number=as_int(raw[0]) if raw else 0,
|
|
242
|
+
model_name=f[1] if len(f) > 1 else "",
|
|
243
|
+
firmware_version=f[3] if len(f) > 3 else "",
|
|
244
|
+
serial_number=f[4] if len(f) > 4 else "",
|
|
245
|
+
ap_ssid=f[5] if len(f) > 5 else "",
|
|
246
|
+
ap_mac=f[6] if len(f) > 6 else "",
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
async def get_open_gopro_version(self) -> str:
|
|
250
|
+
resp = await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.GET_OPEN_GOPRO_VERSION)
|
|
251
|
+
parts = parse_tlv(resp[2:])
|
|
252
|
+
return ".".join(str(as_int(p)) for p in parts) if parts else ""
|
|
253
|
+
|
|
254
|
+
async def shutter(self, start: bool) -> None:
|
|
255
|
+
await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.SET_SHUTTER, bytes([int(start)]))
|
|
256
|
+
|
|
257
|
+
async def sleep(self) -> None:
|
|
258
|
+
await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.SLEEP)
|
|
259
|
+
|
|
260
|
+
async def hilight(self) -> None:
|
|
261
|
+
await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.HILIGHT_MOMENT)
|
|
262
|
+
|
|
263
|
+
async def set_ap(self, enabled: bool) -> None:
|
|
264
|
+
"""Camera access point on/off. Turning it on drops the home-network (STA) link."""
|
|
265
|
+
await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.SET_AP_CONTROL, bytes([int(enabled)]))
|
|
266
|
+
|
|
267
|
+
async def load_preset_group(self, group_id: int) -> None:
|
|
268
|
+
await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.LOAD_PRESET_GROUP, group_id.to_bytes(2, "big"))
|
|
269
|
+
|
|
270
|
+
async def load_preset(self, preset_id: int) -> None:
|
|
271
|
+
await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.LOAD_PRESET, preset_id.to_bytes(4, "big"))
|
|
272
|
+
|
|
273
|
+
async def set_third_party_client(self) -> None:
|
|
274
|
+
await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.SET_THIRD_PARTY_CLIENT)
|
|
275
|
+
|
|
276
|
+
async def get_date_time(self) -> datetime:
|
|
277
|
+
r = await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.GET_DATE_TIME)
|
|
278
|
+
p = r[3:]
|
|
279
|
+
return datetime(p[0] << 8 | p[1], p[2], p[3], p[4], p[5], p[6])
|
|
280
|
+
|
|
281
|
+
async def set_date_time(self, when: datetime) -> None:
|
|
282
|
+
payload = bytes([when.year >> 8, when.year & 0xFF, when.month, when.day, when.hour, when.minute, when.second])
|
|
283
|
+
await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.SET_DATE_TIME, payload)
|
|
284
|
+
|
|
285
|
+
async def set_local_date_time(self, when: datetime, tz_offset_minutes: int, dst: bool = False) -> None:
|
|
286
|
+
payload = bytes([when.year >> 8, when.year & 0xFF, when.month, when.day, when.hour, when.minute, when.second])
|
|
287
|
+
tz = tz_offset_minutes.to_bytes(2, "big", signed=True)
|
|
288
|
+
await self.tlv(UUID_COMMAND, UUID_COMMAND_RESP, BleCommand.SET_LOCAL_DATE_TIME, payload, tz, bytes([int(dst)]))
|
|
289
|
+
|
|
290
|
+
async def set_setting(self, setting_id: int, value: int, size: int = 1) -> None:
|
|
291
|
+
await self.tlv(UUID_SETTINGS, UUID_SETTINGS_RESP, setting_id, value.to_bytes(size, "big"))
|
|
292
|
+
|
|
293
|
+
async def keep_alive(self) -> None:
|
|
294
|
+
await self.set_setting(KEEP_ALIVE_SETTING, KEEP_ALIVE_VALUE)
|
|
295
|
+
|
|
296
|
+
async def get_statuses(self, *status_ids: int) -> dict[int, bytes]:
|
|
297
|
+
async with self._lock:
|
|
298
|
+
key = ("tlv", UUID_QUERY_RESP, int(BleQuery.GET_STATUS_VALUES))
|
|
299
|
+
q = self._queue(key)
|
|
300
|
+
while not q.empty():
|
|
301
|
+
q.get_nowait()
|
|
302
|
+
await self._write(UUID_QUERY, bytes([BleQuery.GET_STATUS_VALUES, *status_ids]))
|
|
303
|
+
resp = await self._wait(key)
|
|
304
|
+
return parse_id_values(resp[2:])
|
|
305
|
+
|
|
306
|
+
async def get_settings(self, *setting_ids: int) -> dict[int, bytes]:
|
|
307
|
+
async with self._lock:
|
|
308
|
+
key = ("tlv", UUID_QUERY_RESP, int(BleQuery.GET_SETTING_VALUES))
|
|
309
|
+
q = self._queue(key)
|
|
310
|
+
while not q.empty():
|
|
311
|
+
q.get_nowait()
|
|
312
|
+
await self._write(UUID_QUERY, bytes([BleQuery.GET_SETTING_VALUES, *setting_ids]))
|
|
313
|
+
resp = await self._wait(key)
|
|
314
|
+
return parse_id_values(resp[2:])
|
|
315
|
+
|
|
316
|
+
async def register_status(self, *status_ids: int) -> dict[int, bytes]:
|
|
317
|
+
async with self._lock:
|
|
318
|
+
key = ("tlv", UUID_QUERY_RESP, int(BleQuery.REGISTER_STATUS_VALUES))
|
|
319
|
+
await self._write(UUID_QUERY, bytes([BleQuery.REGISTER_STATUS_VALUES, *status_ids]))
|
|
320
|
+
resp = await self._wait(key)
|
|
321
|
+
return parse_id_values(resp[2:])
|
|
322
|
+
|
|
323
|
+
async def read_ap_credentials(self) -> tuple[str, str]:
|
|
324
|
+
if not self._client:
|
|
325
|
+
raise GoProBleError("not connected")
|
|
326
|
+
ssid = (await self._client.read_gatt_char(UUID_AP_SSID)).decode(errors="replace")
|
|
327
|
+
password = (await self._client.read_gatt_char(UUID_AP_PASSWORD)).decode(errors="replace")
|
|
328
|
+
return ssid, password
|
|
329
|
+
|
|
330
|
+
# -- protobuf features ---------------------------------------------------------------------------
|
|
331
|
+
|
|
332
|
+
async def set_camera_control(self, external: bool = True) -> None:
|
|
333
|
+
await self.proto(UUID_COMMAND, FEATURE_COMMAND, ACTION_SET_CAMERA_CONTROL, [(1, 2 if external else 0)])
|
|
334
|
+
|
|
335
|
+
async def set_turbo_transfer(self, enabled: bool) -> None:
|
|
336
|
+
await self.proto(UUID_COMMAND, FEATURE_COMMAND, ACTION_SET_TURBO, [(1, int(enabled))])
|
|
337
|
+
|
|
338
|
+
async def get_last_captured(self) -> str | None:
|
|
339
|
+
r = await self.proto(UUID_QUERY, FEATURE_QUERY, ACTION_GET_LAST_MEDIA)
|
|
340
|
+
media = pb_first(r, 2)
|
|
341
|
+
if not isinstance(media, bytes):
|
|
342
|
+
return None
|
|
343
|
+
m = pb_decode(media)
|
|
344
|
+
return f"{pb_str(m, 1)}/{pb_str(m, 2)}"
|
|
345
|
+
|
|
346
|
+
async def scan_networks(self, timeout: float = 40) -> list[AccessPoint]:
|
|
347
|
+
start = await self.proto(UUID_NETWORK, FEATURE_NETWORK, ACTION_SCAN_START)
|
|
348
|
+
_LOGGER.debug("scan start: %s", start)
|
|
349
|
+
while True:
|
|
350
|
+
n = await self.wait_proto(FEATURE_NETWORK, ACTION_NOTIF_SCAN, timeout)
|
|
351
|
+
state = pb_first(n, 1, 0)
|
|
352
|
+
if state == 5: # EnumScanning.SCANNING_SUCCESS
|
|
353
|
+
break
|
|
354
|
+
if state not in (0, 1, 2):
|
|
355
|
+
raise GoProBleError(f"scan failed (state {state})")
|
|
356
|
+
scan_id = pb_first(n, 2, 0)
|
|
357
|
+
r = await self.proto(UUID_NETWORK, FEATURE_NETWORK, ACTION_SCAN_ENTRIES, [(1, 0), (2, 100), (3, scan_id)])
|
|
358
|
+
out = []
|
|
359
|
+
for raw in r.get(3, []):
|
|
360
|
+
e = pb_decode(raw)
|
|
361
|
+
out.append(AccessPoint(pb_str(e, 1), int(pb_first(e, 2, 0)), int(pb_first(e, 4, 0)), int(pb_first(e, 5, 0))))
|
|
362
|
+
return sorted(out, key=lambda a: -a.signal_bars)
|
|
363
|
+
|
|
364
|
+
async def _await_provisioning(self, timeout: float) -> ProvisioningState:
|
|
365
|
+
while True:
|
|
366
|
+
n = await self.wait_proto(FEATURE_NETWORK, ACTION_NOTIF_PROVISIONING, timeout)
|
|
367
|
+
state = ProvisioningState(int(pb_first(n, 1, 0)))
|
|
368
|
+
if state not in (ProvisioningState.UNKNOWN, ProvisioningState.NEVER_STARTED, ProvisioningState.STARTED):
|
|
369
|
+
return state
|
|
370
|
+
|
|
371
|
+
async def connect_new_network(self, ssid: str, password: str, timeout: float = 60) -> ProvisioningState:
|
|
372
|
+
"""Join a Wi-Fi network (the camera requires a scan first)."""
|
|
373
|
+
await self.scan_networks()
|
|
374
|
+
await self.proto(UUID_NETWORK, FEATURE_NETWORK, ACTION_CONNECT_NEW, [(1, ssid), (2, password)])
|
|
375
|
+
state = await self._await_provisioning(timeout)
|
|
376
|
+
if state not in (ProvisioningState.SUCCESS_NEW_AP, ProvisioningState.SUCCESS_OLD_AP):
|
|
377
|
+
raise GoProBleError(f"provisioning failed: {state.name}")
|
|
378
|
+
return state
|
|
379
|
+
|
|
380
|
+
async def connect_known_network(self, ssid: str, timeout: float = 60) -> ProvisioningState:
|
|
381
|
+
await self.scan_networks()
|
|
382
|
+
await self.proto(UUID_NETWORK, FEATURE_NETWORK, ACTION_CONNECT, [(1, ssid)])
|
|
383
|
+
state = await self._await_provisioning(timeout)
|
|
384
|
+
if state not in (ProvisioningState.SUCCESS_NEW_AP, ProvisioningState.SUCCESS_OLD_AP):
|
|
385
|
+
raise GoProBleError(f"provisioning failed: {state.name}")
|
|
386
|
+
return state
|
|
387
|
+
|
|
388
|
+
async def cohn_create_certificate(self, override: bool = True) -> None:
|
|
389
|
+
r = await self.proto(UUID_COMMAND, FEATURE_COMMAND, ACTION_CREATE_COHN_CERT, [(1, int(override))])
|
|
390
|
+
if pb_first(r, 1) != 1:
|
|
391
|
+
raise GoProBleError(f"create COHN cert failed: {r}")
|
|
392
|
+
|
|
393
|
+
async def cohn_clear_certificate(self) -> None:
|
|
394
|
+
r = await self.proto(UUID_COMMAND, FEATURE_COMMAND, ACTION_CLEAR_COHN_CERT)
|
|
395
|
+
if pb_first(r, 1) != 1:
|
|
396
|
+
raise GoProBleError(f"clear COHN cert failed: {r}")
|
|
397
|
+
|
|
398
|
+
async def cohn_set_enabled(self, enabled: bool) -> None:
|
|
399
|
+
r = await self.proto(UUID_COMMAND, FEATURE_COMMAND, ACTION_SET_COHN_SETTING, [(1, int(enabled))])
|
|
400
|
+
if pb_first(r, 1) != 1:
|
|
401
|
+
raise GoProBleError(f"set COHN setting failed: {r}")
|
|
402
|
+
|
|
403
|
+
async def cohn_get_certificate(self) -> str:
|
|
404
|
+
r = await self.proto(UUID_QUERY, FEATURE_QUERY, ACTION_GET_COHN_CERT)
|
|
405
|
+
return pb_str(r, 2)
|
|
406
|
+
|
|
407
|
+
async def cohn_get_status(self, wait_for_ip: bool = False, timeout: float = 60) -> CohnStatus:
|
|
408
|
+
r = await self.proto(UUID_QUERY, FEATURE_QUERY, ACTION_GET_COHN_STATUS, [(1, 1)], response_action=0xEF)
|
|
409
|
+
deadline = asyncio.get_running_loop().time() + timeout
|
|
410
|
+
while wait_for_ip and not pb_str(r, 5):
|
|
411
|
+
remaining = deadline - asyncio.get_running_loop().time()
|
|
412
|
+
if remaining <= 0:
|
|
413
|
+
break
|
|
414
|
+
r = await self.wait_proto(FEATURE_QUERY, 0xEF, remaining)
|
|
415
|
+
state = int(pb_first(r, 2, 0))
|
|
416
|
+
return CohnStatus(
|
|
417
|
+
provisioned=pb_first(r, 1) == 1,
|
|
418
|
+
state=CohnState(state).name if state in CohnState._value2member_map_ else str(state),
|
|
419
|
+
username=pb_str(r, 3),
|
|
420
|
+
password=pb_str(r, 4),
|
|
421
|
+
ip_address=pb_str(r, 5),
|
|
422
|
+
enabled=bool(pb_first(r, 6, 0)),
|
|
423
|
+
ssid=pb_str(r, 7),
|
|
424
|
+
mac_address=pb_str(r, 8),
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
async def provision_cohn(
|
|
428
|
+
self, ssid: str | None = None, password: str | None = None, *, new_certificate: bool = False
|
|
429
|
+
) -> CohnCredentials:
|
|
430
|
+
"""Join Wi-Fi (optional), make sure COHN is on and return the credentials."""
|
|
431
|
+
if ssid:
|
|
432
|
+
if password is not None:
|
|
433
|
+
await self.connect_new_network(ssid, password)
|
|
434
|
+
else:
|
|
435
|
+
await self.connect_known_network(ssid)
|
|
436
|
+
status = await self.cohn_get_status()
|
|
437
|
+
if new_certificate or not status.provisioned:
|
|
438
|
+
await self.cohn_create_certificate(override=True)
|
|
439
|
+
await self.cohn_set_enabled(True)
|
|
440
|
+
status = await self.cohn_get_status(wait_for_ip=True)
|
|
441
|
+
cert = await self.cohn_get_certificate()
|
|
442
|
+
if not status.ip_address:
|
|
443
|
+
raise GoProBleError("camera has no IP on the home network (is Wi-Fi provisioned?)")
|
|
444
|
+
return CohnCredentials(
|
|
445
|
+
host=status.ip_address,
|
|
446
|
+
username=status.username,
|
|
447
|
+
password=status.password,
|
|
448
|
+
certificate=cert,
|
|
449
|
+
mac_address=status.mac_address,
|
|
450
|
+
ssid=status.ssid,
|
|
451
|
+
)
|
pygopro/cli.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Command line: ``pygopro ble-scan``, ``pygopro provision``, ``pygopro state``...
|
|
2
|
+
|
|
3
|
+
Credentials for HTTP commands come from ``--creds file.json`` (as written by ``provision``)
|
|
4
|
+
or ``--host/--password/--cert``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import asyncio
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from dataclasses import asdict
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .http import GoProHttp
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _http(args: argparse.Namespace) -> GoProHttp:
|
|
20
|
+
if args.creds:
|
|
21
|
+
c = json.loads(Path(args.creds).read_text())
|
|
22
|
+
return GoProHttp(c["host"], username=c["username"], password=c["password"], certificate=c["certificate"])
|
|
23
|
+
if args.cert:
|
|
24
|
+
cert = Path(args.cert).read_text()
|
|
25
|
+
return GoProHttp(args.host, username=args.username, password=args.password, certificate=cert)
|
|
26
|
+
return GoProHttp(args.host, ssl=False, port=args.port or 8080)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _dump(obj) -> None:
|
|
30
|
+
if hasattr(obj, "__dataclass_fields__"):
|
|
31
|
+
obj = asdict(obj)
|
|
32
|
+
elif isinstance(obj, list):
|
|
33
|
+
obj = [asdict(o) if hasattr(o, "__dataclass_fields__") else o for o in obj]
|
|
34
|
+
print(json.dumps(obj, indent=2, default=str, ensure_ascii=False))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def _ble_device(name: str | None):
|
|
38
|
+
from bleak import BleakScanner
|
|
39
|
+
|
|
40
|
+
from .const import GOPRO_MANUFACTURER_ID
|
|
41
|
+
|
|
42
|
+
def match(d, adv) -> bool:
|
|
43
|
+
if name:
|
|
44
|
+
return (d.name or "") == name or d.address == name
|
|
45
|
+
return GOPRO_MANUFACTURER_ID in adv.manufacturer_data or (d.name or "").startswith("GoPro")
|
|
46
|
+
|
|
47
|
+
dev = await BleakScanner.find_device_by_filter(match, timeout=20)
|
|
48
|
+
if dev is None:
|
|
49
|
+
sys.exit("GoPro not found over BLE (is it on / advertising?)")
|
|
50
|
+
return dev
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
async def run(args: argparse.Namespace) -> None:
|
|
54
|
+
cmd = args.cmd
|
|
55
|
+
if cmd == "ble-scan":
|
|
56
|
+
from bleak import BleakScanner
|
|
57
|
+
|
|
58
|
+
from .const import GOPRO_MANUFACTURER_ID
|
|
59
|
+
|
|
60
|
+
found = await BleakScanner.discover(timeout=10, return_adv=True)
|
|
61
|
+
for d, adv in found.values():
|
|
62
|
+
if GOPRO_MANUFACTURER_ID in adv.manufacturer_data or (d.name or "").startswith("GoPro"):
|
|
63
|
+
print(d.address, d.name, adv.rssi)
|
|
64
|
+
return
|
|
65
|
+
if cmd in {"provision", "ble-info", "wifi-scan", "wake"}:
|
|
66
|
+
from .ble import GoProBle
|
|
67
|
+
|
|
68
|
+
async with GoProBle(await _ble_device(args.device)) as cam:
|
|
69
|
+
if cmd == "ble-info":
|
|
70
|
+
_dump(await cam.get_hardware_info())
|
|
71
|
+
_dump({"open_gopro": await cam.get_open_gopro_version(), "cohn": asdict(await cam.cohn_get_status())})
|
|
72
|
+
elif cmd == "wifi-scan":
|
|
73
|
+
_dump(await cam.scan_networks())
|
|
74
|
+
elif cmd == "wake":
|
|
75
|
+
await cam.keep_alive()
|
|
76
|
+
print("ok")
|
|
77
|
+
else:
|
|
78
|
+
creds = await cam.provision_cohn(args.ssid, args.wifi_password, new_certificate=args.new_cert)
|
|
79
|
+
out = asdict(creds)
|
|
80
|
+
if args.out:
|
|
81
|
+
Path(args.out).write_text(json.dumps(out, indent=2))
|
|
82
|
+
Path(args.out).chmod(0o600)
|
|
83
|
+
print(f"credentials written to {args.out} (host {creds.host})")
|
|
84
|
+
else:
|
|
85
|
+
_dump(out)
|
|
86
|
+
return
|
|
87
|
+
async with _http(args) as cam:
|
|
88
|
+
if cmd == "info":
|
|
89
|
+
_dump(await cam.get_info())
|
|
90
|
+
elif cmd == "state":
|
|
91
|
+
_dump(await cam.get_state())
|
|
92
|
+
elif cmd == "schema":
|
|
93
|
+
_dump((await cam.get_schema()).raw)
|
|
94
|
+
elif cmd == "presets":
|
|
95
|
+
_dump(await cam.get_presets())
|
|
96
|
+
elif cmd == "media":
|
|
97
|
+
_dump(await cam.get_media_list())
|
|
98
|
+
elif cmd == "shutter":
|
|
99
|
+
await cam.shutter(args.action == "start")
|
|
100
|
+
elif cmd == "set":
|
|
101
|
+
await cam.set_setting(args.setting, args.option)
|
|
102
|
+
elif cmd == "locate":
|
|
103
|
+
await cam.locate(args.action == "on")
|
|
104
|
+
elif cmd == "sleep":
|
|
105
|
+
await cam.sleep()
|
|
106
|
+
elif cmd == "get":
|
|
107
|
+
_dump(await cam.request(args.path))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def main(argv: list[str] | None = None) -> None:
|
|
111
|
+
p = argparse.ArgumentParser(prog="pygopro", description=__doc__)
|
|
112
|
+
p.add_argument("--host", default="172.2x.1yz.51")
|
|
113
|
+
p.add_argument("--port", type=int)
|
|
114
|
+
p.add_argument("--username", default="gopro")
|
|
115
|
+
p.add_argument("--password")
|
|
116
|
+
p.add_argument("--cert", help="camera root CA (PEM) for COHN")
|
|
117
|
+
p.add_argument("--creds", help="JSON written by `provision --out`")
|
|
118
|
+
p.add_argument("--device", help="BLE name or address")
|
|
119
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
120
|
+
sub.add_parser("ble-scan")
|
|
121
|
+
sub.add_parser("ble-info")
|
|
122
|
+
sub.add_parser("wifi-scan")
|
|
123
|
+
sub.add_parser("wake")
|
|
124
|
+
pr = sub.add_parser("provision", help="join Wi-Fi + enable COHN, print credentials")
|
|
125
|
+
pr.add_argument("--ssid")
|
|
126
|
+
pr.add_argument("--wifi-password")
|
|
127
|
+
pr.add_argument("--new-cert", action="store_true")
|
|
128
|
+
pr.add_argument("--out")
|
|
129
|
+
for c in ("info", "state", "schema", "presets", "media", "sleep"):
|
|
130
|
+
sub.add_parser(c)
|
|
131
|
+
s = sub.add_parser("shutter")
|
|
132
|
+
s.add_argument("action", choices=["start", "stop"])
|
|
133
|
+
s = sub.add_parser("locate")
|
|
134
|
+
s.add_argument("action", choices=["on", "off"])
|
|
135
|
+
s = sub.add_parser("set")
|
|
136
|
+
s.add_argument("setting", type=int)
|
|
137
|
+
s.add_argument("option", type=int)
|
|
138
|
+
s = sub.add_parser("get")
|
|
139
|
+
s.add_argument("path")
|
|
140
|
+
asyncio.run(run(p.parse_args(argv)))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
if __name__ == "__main__":
|
|
144
|
+
main()
|