mipc-camera-client-local 0.2.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.
@@ -0,0 +1,322 @@
1
+ import logging
2
+ import math
3
+ import re
4
+ import threading
5
+ from typing import Literal, Union
6
+ from urllib.parse import urlsplit
7
+ from xml.etree import ElementTree
8
+
9
+ import json5
10
+ import requests
11
+
12
+ from .crypto_helpers import (
13
+ des_encrypt_password_hash,
14
+ dh_gen_private,
15
+ dh_gen_public,
16
+ dh_req_data,
17
+ dh_shared_secret,
18
+ format_nid,
19
+ hash_password,
20
+ )
21
+ from .operations import OperationsMixin
22
+ from .settings import (
23
+ MipcAuthenticationError,
24
+ MipcError,
25
+ MipcProtocolError,
26
+ MipcTransportError,
27
+ MipcUnsupportedError,
28
+ SettingsMixin,
29
+ )
30
+ from .sync import synchronized
31
+
32
+ LOGGER = logging.getLogger(__name__)
33
+
34
+ JSONP_PREFIX = "message("
35
+
36
+ __all__ = [
37
+ "MipcCameraClient",
38
+ "MipcError",
39
+ "MipcAuthenticationError",
40
+ "MipcProtocolError",
41
+ "MipcTransportError",
42
+ "MipcUnsupportedError",
43
+ ]
44
+
45
+
46
+ class MipcCameraClient(SettingsMixin, OperationsMixin):
47
+ """HTTP Client for MIPC-compatible cameras."""
48
+
49
+ _sn: Union[str, None]
50
+
51
+ def __init__(self, host: str, timeout: float = 10) -> None:
52
+ if not isinstance(host, str) or not host or re.search(r"[\s\\]", host):
53
+ raise ValueError("Expected a hostname or IP address with optional port")
54
+ endpoint = urlsplit(f"http://{host}")
55
+ if (
56
+ not endpoint.hostname
57
+ or endpoint.username
58
+ or endpoint.password
59
+ or endpoint.path
60
+ or endpoint.query
61
+ or endpoint.fragment
62
+ ):
63
+ raise ValueError("Expected a hostname or IP address with optional port")
64
+ try:
65
+ if endpoint.port == 0 or host.endswith(":"):
66
+ raise ValueError("Invalid camera port")
67
+ except ValueError as err:
68
+ raise ValueError("Invalid camera port") from err
69
+ if (
70
+ not isinstance(timeout, (int, float))
71
+ or not math.isfinite(timeout)
72
+ or timeout <= 0
73
+ ):
74
+ raise ValueError("Timeout must be positive")
75
+ self.timeout = timeout
76
+ self._lock = threading.RLock()
77
+ self.tid = 0
78
+ self.sid = ""
79
+ self.lid = ""
80
+ self.seq = 0
81
+ self._sn = None
82
+ self.shared_secret = None
83
+ self.host = host
84
+ self.init_keys()
85
+ self._r: requests.Session = requests.Session()
86
+ # Prevent ambient proxies and .netrc credentials from changing routing.
87
+ self._r.trust_env = False
88
+
89
+ def __repr__(self) -> str:
90
+ return f"MipcCameraClient(host={repr(self.host)})"
91
+
92
+ def init_keys(self, priv_key=None) -> None:
93
+ self.priv_key = priv_key or dh_gen_private()
94
+ self.pub_key = dh_gen_public(self.priv_key)
95
+
96
+ @synchronized
97
+ def run_dh(self) -> None:
98
+ dh_resp = self.run_rpc("cacs_dh_req", dh_req_data(self.pub_key, self.tid))
99
+
100
+ try:
101
+ if dh_resp.get("type") != "cacs_dh_ack":
102
+ raise ValueError("Unexpected DH acknowledgement")
103
+ self._handle_dh_ack(dh_resp["data"])
104
+ except (KeyError, TypeError, ValueError):
105
+ raise MipcProtocolError("cacs_dh_req") from None
106
+
107
+ def _handle_dh_ack(self, resp_data) -> None:
108
+ self.shared_secret = dh_shared_secret(resp_data["key_b2a"], self.priv_key)
109
+ self.tid = resp_data["tid"]
110
+ self.lid = resp_data["lid"]
111
+
112
+ @synchronized
113
+ def nid(self) -> str:
114
+ return self._create_nid_ex(0)
115
+
116
+ def _create_nid_ex(self, nid_type, incr_seq=True):
117
+ if incr_seq:
118
+ self.seq += 1
119
+ return format_nid(
120
+ self.seq,
121
+ self.lid if nid_type > 0 else self.sid,
122
+ str(self.shared_secret),
123
+ nid_type,
124
+ None,
125
+ None,
126
+ )
127
+
128
+ def _login_data(self, username, password, incr_nid=True):
129
+ data = {
130
+ "dlid": self.lid,
131
+ "dnid": self._create_nid_ex(2, incr_nid),
132
+ "duser": username,
133
+ "dpass": des_encrypt_password_hash(
134
+ hash_password(password), self.shared_secret
135
+ ),
136
+ "dsession_req": 1,
137
+ "dparam__x_countz_": 1,
138
+ "dparam": 1,
139
+ "dparam_name": "spv",
140
+ "dparam_value": "v1",
141
+ }
142
+
143
+ return data
144
+
145
+ def _handle_login_response(self, response_body):
146
+ data = response_body.get("data")
147
+ if not isinstance(data, dict):
148
+ raise MipcProtocolError("cacs_login_req")
149
+ if response_body.get("type") != "cacs_login_ack":
150
+ raise MipcProtocolError("cacs_login_req")
151
+ status = data.get("ret")
152
+ code = status.get("code") if isinstance(status, dict) else data.get("result")
153
+ if code != "":
154
+ raise MipcAuthenticationError("cacs_login_req")
155
+ if (
156
+ not all(isinstance(data.get(k), str) and data[k] for k in ("sid", "lid"))
157
+ or type(data.get("seq")) is not int
158
+ ):
159
+ raise MipcProtocolError("cacs_login_req")
160
+ self.sid = data["sid"]
161
+ self.seq = data["seq"]
162
+ self.lid = data["lid"]
163
+ self.client_addr = data.get("addr")
164
+
165
+ @synchronized
166
+ def run_rpc(self, msg_type, data, response_type="js", *, request_timeout=None):
167
+ """Low-level request to this host only; data must already be flattened."""
168
+ if not isinstance(msg_type, str) or not re.fullmatch(
169
+ r"[a-z][a-z0-9_]*", msg_type
170
+ ):
171
+ raise ValueError("Invalid RPC name")
172
+ if response_type not in ("js", "jpg", "jpeg", "bin"):
173
+ raise ValueError("Invalid response type")
174
+ timeout = self.timeout if request_timeout is None else request_timeout
175
+ if (
176
+ not isinstance(timeout, (int, float))
177
+ or not math.isfinite(timeout)
178
+ or timeout <= 0
179
+ ):
180
+ raise ValueError("Timeout must be positive and finite")
181
+ query_params = data
182
+
183
+ LOGGER.debug("MIPC RPC %s", msg_type)
184
+ try:
185
+ resp = self._r.request(
186
+ method="GET",
187
+ url=f"http://{self.host}/ccm/{msg_type}.{response_type}",
188
+ params=query_params,
189
+ timeout=timeout,
190
+ allow_redirects=False,
191
+ )
192
+ except requests.Timeout:
193
+ raise MipcTransportError(msg_type, "timeout") from None
194
+ except requests.RequestException:
195
+ # requests exceptions can contain credential-bearing query strings.
196
+ raise MipcTransportError(msg_type, "connection_error") from None
197
+ if resp.status_code in (404, 405, 501):
198
+ raise MipcUnsupportedError(msg_type, resp.status_code)
199
+ if resp.status_code in (401, 403):
200
+ raise MipcAuthenticationError(msg_type, f"http_{resp.status_code}")
201
+ if resp.status_code >= 400:
202
+ raise MipcTransportError(msg_type, f"http_{resp.status_code}")
203
+ if 300 <= resp.status_code < 400:
204
+ raise MipcProtocolError(msg_type)
205
+ if response_type == "js":
206
+ parsed = MipcCameraClient._parse_jsonp(resp.text)
207
+ return parsed
208
+ else:
209
+ return resp.content
210
+
211
+ @classmethod
212
+ def _parse_jsonp(cls, text: str) -> dict:
213
+ text = text.strip()
214
+ if not text.startswith(JSONP_PREFIX) or not text.endswith(");"):
215
+ raise MipcProtocolError("jsonp")
216
+ try:
217
+ parsed = json5.loads(text[len(JSONP_PREFIX) : -2])
218
+ except ValueError:
219
+ raise MipcProtocolError("jsonp") from None
220
+ if not isinstance(parsed, dict):
221
+ raise MipcProtocolError("jsonp")
222
+ return parsed
223
+
224
+ @synchronized
225
+ def login(self, username: str, password: str):
226
+ """log in to the camera api and start a session"""
227
+ self.sid = ""
228
+ if not self.shared_secret:
229
+ self.run_dh()
230
+ login_data = self._login_data(username, password)
231
+ login_response_json = self.run_rpc("cacs_login_req", login_data)
232
+ return self._handle_login_response(login_response_json)
233
+
234
+ @synchronized
235
+ def get_image(self, token: str = "p0_xxxxxxxxxx") -> bytes:
236
+ """gets a JPEG snapshot of what the camera sees now"""
237
+ if not self.sid:
238
+ raise MipcAuthenticationError("ccm_pic_get")
239
+ image = self.run_rpc(
240
+ "ccm_pic_get",
241
+ data={
242
+ "dsess": 1,
243
+ "dsess_nid": self.nid(),
244
+ "dsess_sn": self.get_device_sn(),
245
+ "dtoken": token,
246
+ },
247
+ response_type="jpg",
248
+ )
249
+ if not isinstance(image, bytes) or not image.startswith(b"\xff\xd8"):
250
+ # The f300 returns an XML error envelope from the JPEG endpoint.
251
+ # Bound parsing and reject declarations that could expand entities.
252
+ if (
253
+ isinstance(image, bytes)
254
+ and len(image) <= 65536
255
+ and b"\x00" not in image
256
+ and b"<!DOCTYPE" not in image.upper()
257
+ and b"<!ENTITY" not in image.upper()
258
+ ):
259
+ try:
260
+ reply = ElementTree.fromstring(image)
261
+ except (ElementTree.ParseError, LookupError, ValueError):
262
+ pass
263
+ else:
264
+ status = reply.find("data/ccm_pic_get_ack/ret")
265
+ if reply.tag == "message" and status is not None:
266
+ self._checked_response(
267
+ "ccm_pic_get",
268
+ {
269
+ "type": reply.findtext("type"),
270
+ "data": {
271
+ "ret": {
272
+ "code": status.findtext("code"),
273
+ "sub": status.findtext("sub"),
274
+ }
275
+ },
276
+ },
277
+ )
278
+ raise MipcProtocolError("ccm_pic_get")
279
+ return image
280
+
281
+ def get_rtmp_stream(self, token: Literal["p0", "p1", "p2", "p3"] = "p0"):
282
+ """Get an RTMP URL at the configured camera host."""
283
+ if token not in ("p0", "p1", "p2", "p3"):
284
+ raise ValueError("Invalid stream token")
285
+ return self.get_stream_url(token)
286
+
287
+ @synchronized
288
+ def close(self) -> None:
289
+ """Release the owned HTTP session."""
290
+ self._r.close()
291
+ self.sid = ""
292
+ self.shared_secret = None
293
+
294
+ def __enter__(self):
295
+ return self
296
+
297
+ def __exit__(self, exc_type, exc_value, traceback):
298
+ self.close()
299
+
300
+ @synchronized
301
+ def get_device_sn(self) -> Union[str, None]:
302
+ """gets the camera serial number (cached for the client lifetime)"""
303
+ if not self._sn:
304
+ sn = self.get_info().get("sn")
305
+ if not isinstance(sn, str) or not sn:
306
+ raise MipcProtocolError("ccm_info_get")
307
+ self._sn = sn
308
+ return self._sn
309
+
310
+ @synchronized
311
+ def control_ptz(self, tilt_x, tilt_y, speed_x=48, speed_y=16, token="ptz0"):
312
+ """Relative pan/tilt command; units and limits depend on firmware."""
313
+ self._range(tilt_x, -360, 360)
314
+ self._range(tilt_y, -360, 360)
315
+ self._range(speed_x, 1, 100)
316
+ self._range(speed_y, 1, 100)
317
+ return self._authenticated(
318
+ "ccm_ptz_ctl",
319
+ token=token,
320
+ trans={"pan_tilt": {"x": tilt_x, "y": tilt_y}},
321
+ speed={"pan_tilt": {"x": speed_x, "y": speed_y}},
322
+ )
@@ -0,0 +1,163 @@
1
+ """Interruptible local AAC talk uploads; PyAV is an optional dependency."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import time
7
+ from collections.abc import Iterable
8
+ from contextlib import closing
9
+ from dataclasses import dataclass
10
+ from fractions import Fraction
11
+ from itertools import chain
12
+ from threading import Event
13
+ from typing import TYPE_CHECKING
14
+
15
+ from .settings import MipcError, MipcTransportError
16
+
17
+ if TYPE_CHECKING:
18
+ from . import MipcCameraClient
19
+
20
+ SAMPLE_RATE = 16000
21
+ FRAME_SAMPLES = 320
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class AudioSendResult:
26
+ """Transport completion, not a guarantee of audible playback on all models."""
27
+
28
+ samples_sent: int
29
+ sample_rate: int = SAMPLE_RATE
30
+ cancelled: bool = False
31
+
32
+ @property
33
+ def duration(self) -> float:
34
+ return self.samples_sent / self.sample_rate
35
+
36
+
37
+ def pcm_frames(pcm, stop):
38
+ """Yield small aligned chunks and close a streaming decoder on stop/error."""
39
+ source = iter((pcm,)) if isinstance(pcm, bytes) else iter(pcm)
40
+ try:
41
+ for chunk in source:
42
+ if stop is not None and stop.is_set():
43
+ return
44
+ if not isinstance(chunk, bytes) or len(chunk) % 2:
45
+ raise ValueError("Expected complete PCM16 byte samples")
46
+ for offset in range(0, len(chunk), FRAME_SAMPLES * 2):
47
+ if stop is not None and stop.is_set():
48
+ return
49
+ yield chunk[offset : offset + FRAME_SAMPLES * 2]
50
+ finally:
51
+ close = getattr(source, "close", None)
52
+ if close:
53
+ close()
54
+
55
+
56
+ def send_pcm(
57
+ client: MipcCameraClient,
58
+ pcm: bytes | Iterable[bytes],
59
+ token: str,
60
+ timeout: float,
61
+ stop_event: Event | None = None,
62
+ ) -> AudioSendResult:
63
+ """Publish signed little-endian PCM16, mono, 16 kHz to the local speaker.
64
+
65
+ This synchronous operation holds this client's lock; use a separate client
66
+ for concurrent reads. Bytes or an iterable of PCM chunks are paced in real time.
67
+ There is no duration cap. Streaming producers must themselves be interruptible.
68
+ It never unmutes a microphone, changes volume, retries, or opens input URLs.
69
+ """
70
+ if isinstance(pcm, bytes):
71
+ if not pcm or len(pcm) % 2:
72
+ raise ValueError("Expected nonempty PCM16 bytes with complete samples")
73
+ elif isinstance(pcm, (str, bytearray)) or not isinstance(pcm, Iterable):
74
+ raise ValueError("Expected PCM16 bytes or an iterable of byte chunks")
75
+ if not isinstance(token, str) or not token.strip():
76
+ raise ValueError("Expected a camera profile token")
77
+ if (
78
+ type(timeout) not in (int, float)
79
+ or not math.isfinite(timeout)
80
+ or not 0 < timeout <= 30
81
+ ):
82
+ raise ValueError("Expected a timeout greater than zero and at most 30 seconds")
83
+ if stop_event is not None and not isinstance(stop_event, Event):
84
+ raise ValueError("Expected a threading.Event")
85
+ if stop_event is not None and stop_event.is_set():
86
+ return AudioSendResult(0, cancelled=True)
87
+ try:
88
+ import av
89
+ except ImportError:
90
+ raise ImportError(
91
+ "Install this library with its [audio] extra to send audio"
92
+ ) from None
93
+
94
+ with (
95
+ client._lock,
96
+ av.logging.Capture(local=True),
97
+ closing(pcm_frames(pcm, stop_event)) as chunks,
98
+ ):
99
+ try:
100
+ # Check the encoder before reserving the camera's single talk slot.
101
+ codec = av.codec.Codec("aac", "w")
102
+ resampler = av.AudioResampler(
103
+ format=codec.audio_formats[0].name, layout="mono", rate=SAMPLE_RATE
104
+ )
105
+ first = next(chunks, None)
106
+ if first is None:
107
+ if stop_event is not None and stop_event.is_set():
108
+ return AudioSendResult(0, cancelled=True)
109
+ raise ValueError("Audio has no samples")
110
+ # get_talk_url enforces the configured camera host. Remote URLs are
111
+ # never opted into by this higher-level operation.
112
+ url = client.get_talk_url(token)
113
+ with av.open(
114
+ url,
115
+ mode="w",
116
+ format="flv",
117
+ timeout=(timeout, timeout),
118
+ options={
119
+ "flvflags": "no_duration_filesize",
120
+ "rw_timeout": str(int(timeout * 1_000_000)),
121
+ },
122
+ ) as output:
123
+ stream = output.add_stream("aac", rate=SAMPLE_RATE)
124
+ stream.layout = "mono"
125
+ stream.bit_rate = 32000
126
+ started = time.monotonic()
127
+ samples = 0
128
+ for data in chain((first,), chunks):
129
+ if stop_event is not None and stop_event.is_set():
130
+ break
131
+ frame = av.AudioFrame(
132
+ format="s16", layout="mono", samples=len(data) // 2
133
+ )
134
+ frame.sample_rate = SAMPLE_RATE
135
+ frame.time_base = Fraction(1, SAMPLE_RATE)
136
+ frame.pts = samples
137
+ frame.planes[0].update(
138
+ data + bytes(frame.planes[0].buffer_size - len(data))
139
+ )
140
+ for converted in resampler.resample(frame):
141
+ for packet in stream.encode(converted):
142
+ output.mux(packet)
143
+ samples += frame.samples
144
+ time.sleep(
145
+ max(0, started + samples / SAMPLE_RATE - time.monotonic())
146
+ )
147
+ for frame in resampler.resample(None):
148
+ for packet in stream.encode(frame):
149
+ output.mux(packet)
150
+ for packet in stream.encode(None):
151
+ output.mux(packet)
152
+ # This f300 needs a short server-side cleanup interval before the
153
+ # next negotiation; do not retry an audio upload to work around it.
154
+ time.sleep(1)
155
+ return AudioSendResult(
156
+ samples, cancelled=stop_event is not None and stop_event.is_set()
157
+ )
158
+ except MipcError:
159
+ raise
160
+ except Exception:
161
+ # FFmpeg errors can include the private negotiated URL. Do not expose
162
+ # those messages, logs or exception chains to a caller.
163
+ raise MipcTransportError("send_audio", "audio_transport_failed") from None
@@ -0,0 +1,31 @@
1
+ """Explicit, read-only probes; success is evidence of readability only."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class CapabilityReport:
8
+ readable: frozenset[str]
9
+ rejected: dict[str, str]
10
+
11
+
12
+ # Deliberately excludes network scans, discovery/pairing, active firmware
13
+ # checks, subscriptions, and media-session creation.
14
+ READ_PROBES = {
15
+ "device_info": "get_device_info",
16
+ "microphones": "get_microphones",
17
+ "speaker": "get_speaker",
18
+ "imaging": "get_imaging",
19
+ "misc": "get_misc",
20
+ "osd": "get_osd",
21
+ "alerts": "get_alert_config",
22
+ "alert_actions": "get_alert_actions",
23
+ "recording": "get_recording",
24
+ "disks": "get_disks",
25
+ "video_sources": "get_video_sources",
26
+ "ntp": "get_ntp",
27
+ "date": "get_date",
28
+ "cruise": "get_cruise",
29
+ "scenes": "get_scenes",
30
+ "schedule": "get_schedule",
31
+ }
@@ -0,0 +1,10 @@
1
+ """Data-only catalog of observed client calls; not a capability claim."""
2
+
3
+ import json
4
+ from importlib.resources import files
5
+
6
+ ENDPOINTS: dict[str, dict] = json.loads(
7
+ files("mipc_camera_client_local")
8
+ .joinpath("endpoints.json")
9
+ .read_text(encoding="utf-8")
10
+ )