vdm10-python 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.
@@ -0,0 +1,574 @@
1
+ """The station's SIP endpoint: socket, RTSP server, packet helpers, the
2
+ receive loop and request routing, run/shutdown."""
3
+
4
+ import logging
5
+ import re
6
+ import shutil
7
+ import signal
8
+ import socket
9
+ import threading
10
+ import time
11
+ from typing import ClassVar
12
+
13
+ from metzler.media.rtsp_server import RtspServer
14
+ from metzler.provider import FritzTrunk, SipProvider
15
+ from metzler.sip.message import UA, Packet, branch, tag, uri_of
16
+ from metzler.sip.sdp import parse_sdp
17
+ from metzler.station.door_unlock import isapi_open_door
18
+
19
+ log = logging.getLogger("indoor")
20
+
21
+
22
+ class StationCore:
23
+ """The station's SIP endpoint: socket, RTSP server, packet helpers, the
24
+ receive loop and request routing, run/shutdown."""
25
+
26
+ def __init__(self, o):
27
+ self.o = o
28
+ self.server = (o.server, o.server_port)
29
+ self.sip = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
30
+ self.sip.bind(("0.0.0.0", o.listen_port))
31
+ self.bind_port = self.sip.getsockname()[1]
32
+ self.expires = o.expires
33
+ self.init_registrations() # self.regs + self.registered (primary ext)
34
+ self.calls = {} # intercom/door-side Call-ID -> Call
35
+ self.ended_invites = {} # ended Call-ID -> (final resp, ts); retransmit answers
36
+ self.out_calls = {} # our outbound Call-ID -> dict
37
+ # vdm10-ha hook: callable(str, Call) | None - ring/answered/ended events
38
+ self.call_events = getattr(o, "call_events", None)
39
+ self._stop = threading.Event() # set by shutdown() to wake the daemon loops
40
+ self._threads = [] # spawned by start_threads(), joined by shutdown()
41
+ self.running = True
42
+ self.local_tag = tag()
43
+ self.local_mode = bool(o.local_audio or o.local_mic or o.local_tone or o.video_player)
44
+ # standard-SIP trunk to the provider (None in local headset mode)
45
+ self.provider = SipProvider(self, o) if (o.sip_host and not self.local_mode) else None
46
+ # --fritz: second, inbound-only trunk - REGISTERs as an IP phone at a
47
+ # Fritz!Box; its calls reach us on this same socket, told apart from
48
+ # intercom/provider traffic by the sender's address (is_provider_addr)
49
+ self.fritz = FritzTrunk(self, o) if (o.fritz and not self.local_mode) else None
50
+ self.rtsp = None
51
+ # the intercom RTSP server is needed in BOTH modes: local (headset mic)
52
+ # and provider (the caller pulls :554 to receive the SIP peer's audio)
53
+ try:
54
+ self.rtsp = RtspServer(o)
55
+ self.rtsp.start()
56
+ log.info("intercom RTSP server listening on %s:%d", o.local_ip, o.rtsp_port)
57
+ except OSError as e:
58
+ log.warning("cannot bind RTSP :%d (%s) - caller can't pull our stream", o.rtsp_port, e)
59
+
60
+ def send(self, pkt, addr):
61
+ pkt.set("Content-Length", str(len(pkt.body)), True)
62
+ data = str(pkt).encode()
63
+ self.sip.sendto(data, addr)
64
+ log.debug(">> %s:%d\n%s", addr[0], addr[1], data.decode(errors="replace"))
65
+
66
+ def via(self):
67
+ return f"SIP/2.0/UDP {self.o.local_ip}:{self.bind_port};rport;branch={branch()}"
68
+
69
+ def contact(self):
70
+ return f"<sip:{self.o.username}@{self.o.local_ip}:{self.bind_port}>"
71
+
72
+ def base_request(self, method, uri, to_uri=None, frm_uri=None):
73
+ p = Packet()
74
+ p.status_line = f"{method} {uri} SIP/2.0"
75
+ p.set("Via", self.via())
76
+ p.set("Max-Forwards", "70")
77
+ p.set("Contact", self.contact())
78
+ p.set("To", to_uri or f"<sip:{self.o.username}@{self.o.server}:{self.o.server_port}>")
79
+ p.set(
80
+ "From",
81
+ frm_uri
82
+ or f'"{self.o.name}"<sip:{self.o.username}@{self.o.server}:{self.o.server_port}>;tag={self.local_tag}',
83
+ )
84
+ p.set("User-Agent", UA)
85
+ p.set("Allow", "INVITE, ACK, CANCEL, BYE, REFER, INFO, OPTIONS, MESSAGE")
86
+ return p
87
+
88
+ def in_dialog_response(self, req, code, body="", ctype=None, extra_to_tag=None):
89
+ p = Packet()
90
+ p.status_line = f"SIP/2.0 {code}"
91
+ for v in req.get_all("Via"):
92
+ p.set("Via", v)
93
+ for v in req.get_all("Record-Route"):
94
+ p.set("Record-Route", v)
95
+ to = req.get("To")
96
+ if extra_to_tag and "tag=" not in to:
97
+ to += f";tag={extra_to_tag}"
98
+ p.set("To", to)
99
+ p.set("From", req.get("From"))
100
+ p.set("Call-ID", req.get("Call-ID"))
101
+ p.set("CSeq", req.get("CSeq"))
102
+ p.set("Contact", self.contact())
103
+ p.set("User-Agent", UA)
104
+ if ctype:
105
+ p.set("Content-Type", ctype)
106
+ p.body = body
107
+ return p
108
+
109
+ def reply(self, call, pkt):
110
+ """answer call.invite and remember the response - a retransmitted
111
+ INVITE gets it resent (see _retransmitted_invite)"""
112
+ call.last_resp = pkt
113
+ self.send(pkt, call.addr)
114
+
115
+ def _fire_event(self, name, call):
116
+ """call_events hook (vdm10-ha): a listener bug must never kill call handling"""
117
+ if self.call_events:
118
+ try:
119
+ self.call_events(name, call)
120
+ except Exception:
121
+ log.exception("call_events %s hook failed", name)
122
+
123
+ def _close_call(self, call, cid):
124
+ """stop the call and drop it from self.calls; its final response is
125
+ kept ~64s (INVITE client transaction lifetime) so a late retransmit
126
+ still gets answered instead of spawning a ghost call"""
127
+ self._fire_event("ended", call) # before stop(): listeners see the pre-end state
128
+ if call.last_resp is not None:
129
+ self.ended_invites[cid] = (call.last_resp, time.time())
130
+ call.stop()
131
+ self.calls.pop(cid, None)
132
+
133
+ def ended_resp(self, cid):
134
+ """the final response of a just-ended call, or None; lazily prunes"""
135
+ now = time.time()
136
+ for old in [c for c, (_, ts) in self.ended_invites.items() if now - ts > 64]:
137
+ del self.ended_invites[old]
138
+ ent = self.ended_invites.get(cid)
139
+ return ent[0] if ent else None
140
+
141
+ RING_TIMEOUT: ClassVar[int] = 120 # s a call may ring before the janitor ends it
142
+
143
+ def _reaper_loop(self):
144
+ """safety net for callers that die without CANCEL/BYE (station crash,
145
+ network drop): a call still not established after RING_TIMEOUT is torn
146
+ down - 408 to the caller (clears the registrar's busy flag), CANCEL on
147
+ the live legs, media stopped. Established calls are never reaped."""
148
+ while self.running:
149
+ if self._stop.wait(30):
150
+ break
151
+ self._reap_once(time.time())
152
+
153
+ def _reap_once(self, now):
154
+ for cid, call in list(self.calls.items()):
155
+ if call.state == "established" or now - call.created <= self.RING_TIMEOUT:
156
+ continue
157
+ log.warning("reaping stale call %s (state %s, age %ds)", cid, call.state, now - call.created)
158
+ self.reply(call, self.in_dialog_response(call.invite, "408 Request Timeout", extra_to_tag=call.to_tag))
159
+ self._end_provider_leg(call)
160
+ call.end_reason = "timeout"
161
+ self._close_call(call, cid)
162
+ for cid, out in list(self.out_calls.items()):
163
+ if now - out.get("ts", now) > self.RING_TIMEOUT:
164
+ log.warning("reaping stale outbound call to %s", out["num"])
165
+ self.bye_outbound(cid)
166
+
167
+ # request method -> handler name; ACK needs no action (our 200s are not retransmitted)
168
+ REQUEST_HANDLERS: ClassVar[dict] = {
169
+ "OPTIONS": "on_options",
170
+ "MESSAGE": "on_message",
171
+ "INVITE": "on_invite",
172
+ "CANCEL": "on_cancel",
173
+ "BYE": "on_bye",
174
+ "INFO": "on_info",
175
+ "ACK": None,
176
+ }
177
+
178
+ def listener(self):
179
+ while self.running:
180
+ try:
181
+ data, addr = self.sip.recvfrom(65535)
182
+ except OSError:
183
+ return
184
+ if not data or addr is None: # shutdown(SHUT_RDWR) wakes recvfrom empty
185
+ return
186
+ self.handle_datagram(data, addr)
187
+
188
+ def handle_datagram(self, data, addr):
189
+ """parse one UDP datagram and route it (REGISTER replies go to the
190
+ waiting registration loops, everything else to its handler)"""
191
+ text = data.decode(errors="replace")
192
+ try:
193
+ pkt = Packet.parse(text)
194
+ except (ValueError, IndexError, AttributeError) as e:
195
+ return log.debug("unparseable from %s: %s", addr, e)
196
+ log.debug("<< %s:%d\n%s", addr[0], addr[1], text)
197
+ sl = pkt.status_line
198
+ if sl.startswith("SIP/2.0") and self._dispatch_reg_response(pkt):
199
+ return
200
+ name = "on_response" if sl.startswith("SIP/2.0") else self.REQUEST_HANDLERS.get(sl.split(" ", 1)[0])
201
+ if not name:
202
+ return
203
+ try:
204
+ getattr(self, name)(pkt, addr)
205
+ except Exception: # keep the rx loop alive on any handler bug
206
+ log.exception("error handling %s", sl)
207
+
208
+ def on_options(self, pkt, addr):
209
+ self.send(self.in_dialog_response(pkt, "200 OK"), addr)
210
+
211
+ def on_message(self, pkt, addr):
212
+ log.info("MESSAGE from %s: %s", addr, pkt.body[:300])
213
+ self.send(self.in_dialog_response(pkt, "200 OK"), addr)
214
+
215
+ def on_info(self, pkt, addr):
216
+ """SIP INFO: dtmf-relay bodies on a trunk leg feed the door-unlock
217
+ sequence detector (Signal=<d>); intercom-leg INFO is just acked"""
218
+ cid = pkt.get("Call-ID") or ""
219
+ call = self._trunk_call(cid)
220
+ m = re.search(r"Signal=([0-9A-Da-d#*])", pkt.body)
221
+ if call and m:
222
+ self._dtmf_digit(call, m.group(1))
223
+ else:
224
+ log.info("INFO body: %s", pkt.body[:200])
225
+ self.send(self.in_dialog_response(pkt, "200 OK"), addr)
226
+
227
+ def _trunk_call(self, cid):
228
+ """bridge call owning a provider- or fritz-leg Call-ID"""
229
+ for trunk in (self.provider, self.fritz):
230
+ if trunk:
231
+ call = trunk.calls.get(cid)
232
+ if call:
233
+ return call
234
+ return None
235
+
236
+ DTMF_SEQ_WINDOW = 3.0 # seconds between digits before the buffer resets
237
+ UNLOCK_COOLDOWN = 3.0 # seconds before the same call may unlock again
238
+
239
+ def _dtmf_digit(self, call, d):
240
+ """one decoded DTMF digit from the answered trunk leg (SIP INFO or
241
+ RFC4733): buffer the sequence; '#<n>' unlocks door n via ISAPI"""
242
+ log.info("DTMF digit %r on call %s (state %s, buf %r)", d, call.id, call.state, call.dtmf)
243
+ if call.state != "established" or call.inbound:
244
+ return
245
+ now = time.time()
246
+ if now - call.dtmf_ts > self.DTMF_SEQ_WINDOW:
247
+ call.dtmf = ""
248
+ call.dtmf, call.dtmf_ts = (call.dtmf + d)[-8:], now
249
+ m = re.search(r"#([12])$", call.dtmf)
250
+ if not m:
251
+ return
252
+ door = int(m.group(1))
253
+ call.dtmf = ""
254
+ if now - call.unlock_ts < self.UNLOCK_COOLDOWN: # RFC2833 + INFO both sent by the phone
255
+ return log.info("DTMF unlock ignored (cooldown, duplicate transport)")
256
+ call.unlock_ts = now
257
+ log.info("DTMF unlock request: door %d (call %s)", door, call.id)
258
+ self._spawn(self.unlock_door, call, door)
259
+
260
+ @staticmethod
261
+ def _spawn(fn, *args):
262
+ threading.Thread(target=fn, args=args, daemon=True).start()
263
+
264
+ def unlock_door(self, call, door):
265
+ """open door n: ISAPI PUT on the outdoor station (the SDP address of
266
+ the door that is calling us)"""
267
+ host = parse_sdp(call.invite.body)["ip"]
268
+ pw = self.o.door_isapi_pass or self.o.password
269
+ if not (host and pw):
270
+ return log.error("door unlock: no outdoor station address/password configured")
271
+ isapi_open_door(host, self.o.door_isapi_user, pw, door, port=self.o.door_isapi_port)
272
+
273
+ def _dispatch_reg_response(self, pkt):
274
+ """a REGISTER reply: hand it to whichever registration loop is
275
+ waiting (intercom ext(s), provider, fritz) - matched by Call-ID"""
276
+ for r in self.regs:
277
+ if r.is_reg_response(pkt):
278
+ r.reg_queue.put(pkt)
279
+ return True
280
+ for trunk in (self.provider, self.fritz):
281
+ if trunk and trunk.is_reg_response(pkt):
282
+ trunk.reg_queue.put(pkt)
283
+ return True
284
+ return False
285
+
286
+ def _out_invite_response(self, out, pkt, addr):
287
+ """response on an outbound intercom leg; a bridged app call gets the
288
+ intercom's ringing and its final result forwarded"""
289
+ cid, code = pkt.get("Call-ID"), int(pkt.status_line.split()[1])
290
+ call = out.get("bridged")
291
+ if code in (180, 183):
292
+ log.info("outbound call %s ringing", out["num"])
293
+ if call: # the app hears the intercom ring
294
+ self.reply(call, self.in_dialog_response(call.invite, "180 Ringing", extra_to_tag=call.to_tag))
295
+ elif 200 <= code < 300:
296
+ self.out_answered(out, pkt, addr)
297
+ elif code >= 300:
298
+ log.warning("outbound call to %s failed: %s", out["num"], pkt.status_line)
299
+ self._ack_dead_final(pkt, addr) # else the registrar retransmits ~30s
300
+ self.out_calls.pop(cid, None)
301
+ if call: # callee busy/gone -> tell the app
302
+ self.reply(call, self.in_dialog_response(call.invite, pkt.status_line[8:], extra_to_tag=call.to_tag))
303
+ call.end_reason = "rejected"
304
+ self._close_call(call, call.id)
305
+
306
+ def on_response(self, pkt, addr):
307
+ cseq = pkt.get("CSeq") or ""
308
+ cid = pkt.get("Call-ID") or ""
309
+ log.info("response %s (CSeq %s, Call-ID %s)", pkt.status_line, cseq, cid)
310
+ out = self.out_calls.get(cid)
311
+ if out and "INVITE" in cseq:
312
+ return self._out_invite_response(out, pkt, addr)
313
+ call = self.provider.calls.get(cid) if self.provider else None
314
+ if call and "INVITE" in cseq:
315
+ return self._provider_invite_response(call, pkt)
316
+ if self.fritz and "INVITE" in cseq and cid in self.fritz.calls:
317
+ return self._fritz_invite_response(self.fritz.calls[cid], pkt)
318
+ if "INVITE" in cseq and int(pkt.status_line.split()[1]) >= 300:
319
+ self._ack_dead_final(pkt, addr) # leg already torn down - still ACK
320
+
321
+ # explicit user rejections (decline on a ringing device) - unlike timeouts
322
+ # or transport failures these kill the whole race, not just that leg
323
+ DECLINE_CODES: ClassVar[frozenset] = frozenset((486, 603))
324
+
325
+ def _ack_dead_final(self, pkt, addr):
326
+ """a final response on an INVITE transaction we already dropped (a
327
+ racing leg CANCELLed or declined earlier): it still needs the
328
+ transaction ACK - our Via sits at the bottom of the response's list,
329
+ so its branch is the last branch= - or the peer retransmits ~30s"""
330
+ cseq, to = pkt.get("CSeq") or "", pkt.get("To")
331
+ branches = re.findall(r"branch=([^;\s,]+)", pkt.get("Via") or "")
332
+ if not to or not branches or "INVITE" not in cseq:
333
+ return
334
+ p = Packet()
335
+ p.status_line = f"ACK {uri_of(to)} SIP/2.0"
336
+ p.set("Via", f"SIP/2.0/UDP {self.o.local_ip}:{self.bind_port};rport;branch={branches[-1]}")
337
+ p.set("Max-Forwards", "70")
338
+ p.set("To", to)
339
+ p.set("From", pkt.get("From"))
340
+ p.set("Call-ID", pkt.get("Call-ID"))
341
+ p.set("CSeq", cseq.replace("INVITE", "ACK"))
342
+ p.set("User-Agent", UA)
343
+ try:
344
+ self.send(p, addr)
345
+ except OSError:
346
+ pass
347
+
348
+ def _decline_call(self, call, pkt):
349
+ """no leg left ringing, or a leg got explicitly declined: CANCEL any
350
+ still-racing leg and give the indoor caller the final outcome. A
351
+ 401/407 challenge is never propagated - the indoor gets a plain 486."""
352
+ if call.fritz_leg:
353
+ self.fritz.cancel_leg(call)
354
+ call.fritz_leg = None
355
+ if self.provider and call.prov_call_id in self.provider.calls:
356
+ self.provider.cancel(call)
357
+ self.provider.calls.pop(call.prov_call_id, None)
358
+ code = int(pkt.status_line.split()[1]) if pkt else 0
359
+ # the registrar clears its global busy flag only on 408/486/603;
360
+ # every other outcome (auth challenges, 488, 5xx) becomes a 486
361
+ status = pkt.status_line[8:] if code in (408, 486, 603) else "486 Busy Here"
362
+ self.reply(call, self.in_dialog_response(call.invite, status, extra_to_tag=call.to_tag))
363
+ call.end_reason = "error"
364
+ self._close_call(call, call.id)
365
+
366
+ def _provider_invite_response(self, call, pkt):
367
+ """response on the provider leg of a bridged call; on door calls a
368
+ fritz leg may be racing it - the winner keeps the call, the loser is
369
+ CANCELLed"""
370
+ cid = pkt.get("Call-ID")
371
+ result = self.provider.handle_response(call, pkt)
372
+ if result == "answered":
373
+ if call.fritz_leg: # the app won the race
374
+ self.fritz.cancel_leg(call)
375
+ call.fritz_leg = None
376
+ self.provider_answered(call, pkt)
377
+ elif result == "early":
378
+ self.early_media(call, pkt)
379
+ elif result == "fail":
380
+ self.provider.calls.pop(cid, None)
381
+ if call.fritz_leg and int(pkt.status_line.split()[1]) not in self.DECLINE_CODES:
382
+ return # fritz still rings - keep waiting
383
+ self._decline_call(call, pkt)
384
+
385
+ def _fritz_invite_response(self, call, pkt):
386
+ """response on the racing fritzfon leg of a door call"""
387
+ cid = pkt.get("Call-ID")
388
+ result = self.fritz.handle_response(call, pkt)
389
+ if result == "answered":
390
+ return self._fritz_won(call, pkt)
391
+ if result == "fail":
392
+ self.fritz.calls.pop(cid, None)
393
+ call.fritz_leg = None
394
+ prov_alive = self.provider and call.prov_call_id in self.provider.calls
395
+ if not prov_alive or int(pkt.status_line.split()[1]) in self.DECLINE_CODES:
396
+ self._decline_call(call, pkt)
397
+
398
+ def _fritz_won(self, call, resp):
399
+ """the fritzfon answered a door call first: CANCEL the still-racing
400
+ provider leg, promote the fritz leg into the call's SIP-leg fields
401
+ (ACK/teardown then work via call.trunk) and take the answered path.
402
+ Idempotent - a retransmitted 200 gets re-ACKed only."""
403
+ leg = call.fritz_leg
404
+ if not leg:
405
+ return self.fritz.ack(call, resp)
406
+ if call.prov_call_id in self.provider.calls:
407
+ self.provider.cancel(call) # prov_* still = the provider leg
408
+ self.provider.calls.pop(call.prov_call_id, None)
409
+ (call.prov_call_id, call.prov_branch, call.prov_cseq, call.prov_from) = (
410
+ leg["cid"],
411
+ leg["branch"],
412
+ leg["cseq"],
413
+ leg["from"],
414
+ )
415
+ call.prov_to = call.prov_uri = None # filled by ack() from the 200
416
+ for m in (
417
+ [call.media, getattr(call.media, "video", None)] if call.kind == "intercom" else [call.audio, call.video]
418
+ ):
419
+ if m:
420
+ m.srtp = None # fritz leg is plain RTP
421
+ call.prov_plain = True
422
+ call.provider_media = False # rebind media to the fritz peer
423
+ call.trunk = self.fritz
424
+ call.fritz_leg = None
425
+ self.provider_answered(call, resp)
426
+
427
+ def start_threads(self):
428
+ """spawn the daemon threads run() manages, WITHOUT installing the
429
+ SIGTERM handler or blocking on the main loop - for embedded/library
430
+ use (vdm10-ha drives the station from a non-main thread). Includes
431
+ the provider/fritz REGISTER loops in non-local mode (they are daemon
432
+ threads like the rest; a plain embedded start must not silently
433
+ skip the trunks)."""
434
+ self._threads = [
435
+ threading.Thread(target=self.listener, daemon=True),
436
+ *(threading.Thread(target=r.register_loop, daemon=True) for r in self.regs),
437
+ threading.Thread(target=self.heartbeat_loop, daemon=True),
438
+ threading.Thread(target=self._reaper_loop, daemon=True),
439
+ ]
440
+ if self.o.call:
441
+ self._threads.append(threading.Thread(target=self.call_out, args=(self.o.call,), daemon=True))
442
+ for t in self._threads:
443
+ t.start()
444
+ if not self.local_mode:
445
+ self._start_trunks()
446
+
447
+ def run(self):
448
+ self.start_threads()
449
+ if self.local_mode:
450
+ missing = [
451
+ t
452
+ for t, need in (
453
+ ("aplay", self.o.local_audio),
454
+ ("arecord", self.o.local_mic),
455
+ ("ffplay", self.o.video_player),
456
+ )
457
+ if need and not shutil.which(t)
458
+ ]
459
+ if missing:
460
+ log.warning(
461
+ "audio tools missing (%s) — install alsa-utils / ffmpeg, or run --list-audio to see devices",
462
+ ", ".join(missing),
463
+ )
464
+ log.info(
465
+ "indoor station sim on %s:%d -> registrar %s:%d [LOCAL headset mode: "
466
+ "spk=%s mic=%s tone=%s video=%s dev=%s]",
467
+ self.o.local_ip,
468
+ self.bind_port,
469
+ self.server[0],
470
+ self.server[1],
471
+ bool(self.o.local_audio),
472
+ bool(self.o.local_mic),
473
+ self.o.local_tone,
474
+ bool(self.o.video_player),
475
+ self.o.alsa_device,
476
+ )
477
+
478
+ def terminate(signum, frame):
479
+ raise KeyboardInterrupt
480
+
481
+ signal.signal(signal.SIGTERM, terminate) # plain `kill` must unregister too
482
+ try:
483
+ while True:
484
+ time.sleep(1)
485
+ except KeyboardInterrupt:
486
+ pass
487
+ finally:
488
+ self.shutdown()
489
+
490
+ def _start_trunks(self):
491
+ """provider (+ optional fritz) REGISTER loops and the startup log"""
492
+ if self.provider is None:
493
+ return # no --sip-host: intercom-only mode (HA embeds this path)
494
+ if self.provider.needs_register():
495
+ threading.Thread(target=self.provider.register_loop, daemon=True).start()
496
+ else:
497
+ log.info("no --sip-user/--sip-pass: trunk mode, provider REGISTER skipped")
498
+ if self.fritz and self.fritz.needs_register():
499
+ threading.Thread(target=self.fritz.register_loop, daemon=True).start()
500
+ log.info(
501
+ "indoor station sim on %s:%d -> registrar %s:%d, bridge via %s:%d to %s",
502
+ self.o.local_ip,
503
+ self.bind_port,
504
+ self.server[0],
505
+ self.server[1],
506
+ self.provider.proxy[0],
507
+ self.provider.proxy[1],
508
+ self.o.sip_target,
509
+ )
510
+
511
+ def shutdown(self):
512
+ """clean exit: end every call (BYE/CANCEL so the registrar's busy
513
+ tracking clears), then Expires=0 to remove our dev_reg row —
514
+ leaving stale state marks the whole system busy (486 to the door)"""
515
+ self.running = False
516
+ for cid in list(self.out_calls):
517
+ try:
518
+ self.bye_outbound(cid)
519
+ except OSError:
520
+ pass
521
+ self._stop.set() # wake the daemon loops (reaper/heartbeat/register sleeps)
522
+ for call in list(self.calls.values()):
523
+ self._end_call_on_shutdown(call)
524
+ self.calls.clear()
525
+ try:
526
+ for r in self.regs:
527
+ r.unregister()
528
+ if self.provider and self.provider.needs_register():
529
+ self.provider.unregister()
530
+ if self.fritz and self.fritz.needs_register():
531
+ self.fritz.unregister()
532
+ time.sleep(0.3)
533
+ except OSError:
534
+ pass
535
+ self._stop_threads()
536
+
537
+ def _stop_threads(self):
538
+ """wake + join every daemon thread shutdown owns. close() alone does NOT
539
+ wake a blocked recvfrom/accept on Linux - shutdown(SHUT_RDWR) is what
540
+ interrupts the listener/accept threads; the register poll gets a None
541
+ sentinel because a Queue.get can't be interrupted."""
542
+ try:
543
+ self.sip.shutdown(socket.SHUT_RDWR)
544
+ except OSError:
545
+ pass
546
+ self.sip.close()
547
+ if self.rtsp is not None: # own accept thread started in __init__
548
+ self.rtsp.running = False
549
+ try:
550
+ self.rtsp.ls.shutdown(socket.SHUT_RDWR)
551
+ self.rtsp.ls.close()
552
+ except OSError:
553
+ pass
554
+ self.rtsp.join(timeout=2)
555
+ for r in self.regs:
556
+ r.reg_queue.put(None) # sentinel: abort a register_once still blocked on get()
557
+ for t in self._threads:
558
+ t.join(timeout=2)
559
+
560
+ def _end_call_on_shutdown(self, call):
561
+ """established -> BYE the caller; still ringing -> a final response that
562
+ clears the registrar's busy state. The provider leg is ended as well."""
563
+ try:
564
+ if call.state == "established":
565
+ self.bye_intercom(call)
566
+ else:
567
+ # via the :5065 registrar only 408/603/486 clear its global busy flag (487 does not)
568
+ code = "486 Busy Here" if ":5065" in (call.invite.get("Via") or "") else "487 Request Terminated"
569
+ self.send(self.in_dialog_response(call.invite, code, extra_to_tag=call.to_tag), call.addr)
570
+ self._end_provider_leg(call)
571
+ except OSError:
572
+ pass
573
+ call.end_reason = "shutdown"
574
+ call.stop()
@@ -0,0 +1,42 @@
1
+ """Door unlock over the outdoor station's ISAPI (HTTP digest, stdlib only).
2
+
3
+ The outdoor station (VDM10-VM-POE, fw V2.2.56) exposes the standard Hikvision
4
+ route `PUT /ISAPI/AccessControl/RemoteControl/door/<n>` with
5
+ <RemoteControlDoor><cmd>open</cmd></RemoteControlDoor> (n = 1..2).
6
+ """
7
+
8
+ import logging
9
+ import re
10
+ import urllib.error
11
+ import urllib.request
12
+
13
+ log = logging.getLogger("indoor")
14
+
15
+ BODY = (
16
+ '<?xml version="1.0" encoding="UTF-8"?>'
17
+ '<RemoteControlDoor version="2.0" xmlns="http://www.isapi.org/ver20/XMLSchema">'
18
+ "<cmd>open</cmd></RemoteControlDoor>"
19
+ )
20
+
21
+
22
+ def digest_opener(url, user, password):
23
+ """urllib opener answering the outdoor station's HTTP Digest challenge"""
24
+ mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
25
+ mgr.add_password(None, url, user, password)
26
+ return urllib.request.build_opener(urllib.request.HTTPDigestAuthHandler(mgr))
27
+
28
+
29
+ def isapi_open_door(host, user, password, door, port=80, timeout=5.0):
30
+ """momentary unlock of `door` -> True when the station answered statusCode 1"""
31
+ url = f"http://{host}:{port}/ISAPI/AccessControl/RemoteControl/door/{door}"
32
+ opener = digest_opener(url, user, password)
33
+ req = urllib.request.Request(url, BODY.encode(), {"Content-Type": "application/xml"}, method="PUT")
34
+ try:
35
+ with opener.open(req, timeout=timeout) as r:
36
+ text = r.read().decode(errors="replace")
37
+ except (urllib.error.URLError, OSError) as e:
38
+ log.warning("ISAPI unlock door %d on %s failed: %s", door, host, e)
39
+ return False
40
+ ok = re.search(r"<statusCode>1</statusCode>", text) is not None
41
+ log.info("ISAPI unlock door %d on %s: %s", door, host, "ok" if ok else f"rejected {text[:160]!r}")
42
+ return ok