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,92 @@
1
+ """Embedded/HA mode (vdm10-ha): explicit answer + hangup for calls parked by ha_mode."""
2
+
3
+ import logging
4
+
5
+ from metzler.sip.sdp import parse_sdp, sdp_answer_firmware, sdp_answer_talkback
6
+ from metzler.station.ha_media import HaCallMedia, HaIntercomMedia
7
+
8
+ log = logging.getLogger("indoor")
9
+
10
+
11
+ class HaAnswerMixin:
12
+ """answer_call()/hangup_call() for calls parked in state 'early' by the
13
+ ha_mode branch in on_invite. The 200 OK reuses LocalAnswerMixin's dialect
14
+ (header-only talkback for intercom offers, firmware m= lines for door calls)
15
+ but binds HaCallMedia/HaIntercomMedia instead of ALSA media."""
16
+
17
+ def answer_call(self, cid):
18
+ """answer the parked call `cid`. Returns False when there is no ringing
19
+ call with that Call-ID (e.g. the caller already cancelled)."""
20
+ call = self.calls.get(cid)
21
+ # "early" = parked only; "bridging" = parked + a trunk leg is racing
22
+ if call is None or call.state not in ("early", "bridging") or not self.running:
23
+ return False
24
+ remote_sdp = parse_sdp(call.invite.body)
25
+ talkback = not remote_sdp["media"] # hicore intercom offers carry no m= lines
26
+ door_a = next((m for m in remote_sdp["media"] if m["type"] == "audio"), None)
27
+ door_v = next((m for m in remote_sdp["media"] if m["type"] == "video"), None)
28
+ intercom = talkback and self.rtsp
29
+ try:
30
+ call.local = self._ha_media(call, door_a, door_v, remote_sdp, talkback, intercom)
31
+ except OSError as e:
32
+ # e.g. a prior call's media still holds the fixed talkback port
33
+ log.warning("ha media init failed (%s) - declining call", e)
34
+ self.reply(call, self.in_dialog_response(call.invite, "486 Busy Here", extra_to_tag=call.to_tag))
35
+ call.state = "closed"
36
+ return False
37
+ call.local.start()
38
+ if call.state not in ("early", "bridging"): # a CANCEL/BYE raced the answer
39
+ call.local.stop()
40
+ return False
41
+ ok = self.in_dialog_response(call.invite, "200 OK", ctype="application/sdp", extra_to_tag=call.to_tag)
42
+ ok.body = self._ha_answer_sdp(call, talkback)
43
+ self.reply(call, ok)
44
+ # HA won the race against the trunk legs - CANCEL them before marking
45
+ # the call established (teardown keys BYE vs CANCEL off call.state)
46
+ self._end_provider_leg(call)
47
+ call.state = "established"
48
+ self._end_provider_leg(call) # ha_mode + trunk: CANCEL the racing legs
49
+ self._fire_event("answered", call)
50
+ log.info("ha call answered (%s, %s)", "intercom-rtsp" if intercom else "rtp", call.id)
51
+ return True
52
+
53
+ def _ha_media(self, call, door_a, door_v, remote_sdp, talkback, intercom):
54
+ """the HA-media counterpart of LocalAnswerMixin._local_media"""
55
+ if intercom:
56
+ return HaIntercomMedia(self.rtsp, getattr(self.o, "ha_mic_feed", None))
57
+ ip = remote_sdp["ip"]
58
+ audio = (
59
+ (door_a["ip"] or ip, door_a["port"]) if door_a else (ip, self.o.talkback_port) if talkback and ip else None
60
+ )
61
+ video = (door_v["ip"] or ip, door_v["port"]) if door_v else None
62
+ return HaCallMedia(
63
+ self.o,
64
+ audio,
65
+ video,
66
+ fixed=talkback,
67
+ mic_feed=getattr(self.o, "ha_mic_feed", None),
68
+ on_audio=getattr(self.o, "ha_on_audio", None),
69
+ )
70
+
71
+ def _ha_answer_sdp(self, call, talkback):
72
+ if talkback:
73
+ return sdp_answer_talkback(self.o.serial, self.o.local_ip, self.o.talkback_port, opts=self.o)
74
+ return sdp_answer_firmware(self.o.username, self.o.local_ip, call.local.audio_port, call.local.video_port)
75
+
76
+ def hangup_call(self, cid):
77
+ """decline a ringing call (final response clearing the registrar's busy
78
+ flag - 486 via the :5065 registrar, 487 on a direct leg) or BYE an
79
+ established one, then close it. Returns False without such a call."""
80
+ call = self.calls.get(cid)
81
+ if call is None:
82
+ return False
83
+ if call.state == "established":
84
+ self.bye_intercom(call)
85
+ call.end_reason = "bye"
86
+ else:
87
+ code = "486 Busy Here" if ":5065" in (call.invite.get("Via") or "") else "487 Request Terminated"
88
+ self.reply(call, self.in_dialog_response(call.invite, code, extra_to_tag=call.to_tag))
89
+ call.end_reason = "declined"
90
+ self._end_provider_leg(call) # stop any trunk legs still ringing
91
+ self._close_call(call, cid)
92
+ return True
@@ -0,0 +1,95 @@
1
+ """Embedded/HA mode media (vdm10-ha): queue-fed mic, no ALSA/ffplay/SIP peer.
2
+
3
+ Same two media shapes as LocalAnswerMixin._local_media:
4
+ - intercom calls (header-only offer): the caller RTSP-pulls our :554 for mic
5
+ audio; HaIntercomMedia feeds RtspServer.mic from an injected frame source.
6
+ No RtspPuller - nothing here consumes the caller's stream (the HA camera
7
+ pulls the door's RTSP itself, on demand only).
8
+ - door calls (m= lines): HaCallMedia is a LocalMediaBridge without ALSA -
9
+ door RTP audio is (optionally) tapped into a callback, and our talkback
10
+ RTP to the door is fed from the injected frame source (PCMU silence while
11
+ the queue is empty -> muted by default).
12
+ """
13
+
14
+ import logging
15
+ import socket
16
+ import threading
17
+
18
+ from metzler.media.local import LocalMediaBridge
19
+
20
+ log = logging.getLogger("indoor")
21
+
22
+ SILENCE = b"\xff" * 160 # one 20 ms PCMU frame of silence
23
+
24
+
25
+ class HaIntercomMedia:
26
+ """intercom (header-only) calls: feed the shared RtspServer's mic from an
27
+ injected frame source. Door/intercom audio+video is not consumed here."""
28
+
29
+ def __init__(self, server, mic_feed):
30
+ self.server, self.mic_feed = server, mic_feed
31
+ # attributes LocalMediaBridge exposes, kept for Call.stop()/log compat
32
+ self.door_a = self.door_v = None
33
+ self.rx = {True: 0, False: 0}
34
+ self.tx = 0
35
+
36
+ def start(self):
37
+ self.server.mic = self.mic_frame
38
+
39
+ def mic_frame(self):
40
+ """called by RtspServer.stream - one 160B/20ms ulaw frame"""
41
+ frame = self.mic_feed() if self.mic_feed else None
42
+ if frame is None:
43
+ return SILENCE
44
+ self.tx += 1
45
+ return frame
46
+
47
+ def stop(self):
48
+ if self.server and self.server.mic == self.mic_frame:
49
+ self.server.mic = None
50
+
51
+
52
+ class HaCallMedia(LocalMediaBridge):
53
+ """door calls (negotiated m= lines): LocalMediaBridge without ALSA. Mic
54
+ frames come from an injected callable instead of arecord; door audio is
55
+ tapped into an optional callback instead of aplay; video frames are dropped.
56
+ Socket setup, the 20 ms RTP tx loop, and peer latching are the parent's."""
57
+
58
+ def __init__(self, o, door_a, door_v, fixed=False, mic_feed=None, on_audio=None):
59
+ super().__init__(o, door_a, door_v, fixed=fixed)
60
+ self.mic_feed = mic_feed
61
+ self.on_audio_cb = on_audio
62
+
63
+ def start(self):
64
+ """same sockets as the parent, but never spawns aplay/arecord/ffplay"""
65
+ threading.Thread(target=self.rx_loop, daemon=True).start()
66
+ threading.Thread(target=self.tx_loop, daemon=True).start()
67
+
68
+ def _mic_frame(self):
69
+ """one 160B PCMU frame from the HA mic queue; silence while muted"""
70
+ frame = self.mic_feed() if self.mic_feed else None
71
+ return frame if frame is not None else SILENCE
72
+
73
+ def _play_audio(self, pt, payload, addr):
74
+ """keep the parent's peer latching; tap PCMU into the callback"""
75
+ if self.door_a is None or (self.fixed and self.rx[True] == 1 and addr != self.door_a):
76
+ self.door_a = addr
77
+ if self.on_audio_cb is not None:
78
+ self.on_audio_cb(payload)
79
+
80
+ def _play_video(self, payload, addr):
81
+ if self.door_v is None and not self.fixed:
82
+ self.door_v = addr # keep peer latching; frames are dropped
83
+
84
+ def stop(self):
85
+ # shutdown() before close: close() alone does not wake rx_loop's recvfrom
86
+ for sock in (self.audio_sock, self.video_sock):
87
+ try:
88
+ sock and sock.shutdown(socket.SHUT_RDWR)
89
+ except OSError:
90
+ pass
91
+ super().stop()
92
+ try:
93
+ self.rtcp_sock and self.rtcp_sock.close()
94
+ except OSError:
95
+ pass
@@ -0,0 +1,90 @@
1
+ """Inbound provider call (the SIP app dials us) -> outbound intercom call.
2
+
3
+ The reverse of ProviderBridgeMixin: the app's INVITE rings --inbound-target
4
+ on the intercom; when it answers, a SipIntercomMedia bridges the legs
5
+ (pull the callee's :554 -> app RTP, app RTP -> our :554 mic the callee pulls).
6
+ """
7
+
8
+ import logging
9
+ import threading
10
+
11
+ from metzler.media.intercom import SipIntercomMedia
12
+ from metzler.media.srtp import SrtpSession, srtp_available
13
+ from metzler.sip.sdp import media_addr, parse_sdp
14
+ from metzler.station.call import Call
15
+
16
+ log = logging.getLogger("indoor")
17
+
18
+
19
+ class InboundCallMixin:
20
+ """Inbound provider call (the SIP app dials us) -> outbound intercom call."""
21
+
22
+ def inbound_provider_call(self, pkt, addr, trunk):
23
+ """a call from the SIP side (someone dialed the provider account or
24
+ the fritz extension): ring --inbound-target on the intercom and bridge
25
+ both legs when it answers. Without a target we must decline -
26
+ bridging it back to the SIP side would loop."""
27
+ if not self.o.inbound_target or self.local_mode:
28
+ log.info("declining inbound %s call from %s", trunk.label, pkt.get("From"))
29
+ self.send(self.in_dialog_response(pkt, "486 Busy Here"), addr)
30
+ return
31
+ self.send(self.in_dialog_response(pkt, "100 Trying"), addr)
32
+ call = Call(self, pkt, addr)
33
+ call.inbound = True
34
+ call.trunk = trunk # the SIP leg this call came from
35
+ call.kind = "intercom"
36
+ self.calls[call.id] = call
37
+ # the inbound leg is the session HA surfaces ("ringing the indoor"):
38
+ # call_out's intercom leg is an implementation detail, like a trunk leg
39
+ self._fire_event("ring", call)
40
+ self.reply(call, self.in_dialog_response(pkt, "180 Ringing", extra_to_tag=call.to_tag))
41
+ log.info("inbound %s call %s -> ringing intercom %s", trunk.label, pkt.get("From"), self.o.inbound_target)
42
+ if self.registered.is_set():
43
+ return self._place_inbound_call(call)
44
+ threading.Thread(target=self._place_inbound_call, args=(call,), daemon=True).start()
45
+
46
+ def _place_inbound_call(self, call):
47
+ """dial the intercom target; call_out blocks until REGISTERED, so it
48
+ may run on a thread. Failing that, tell the app instead of leaving
49
+ it ringing forever."""
50
+ if not self.call_out(self.o.inbound_target, bridged=call):
51
+ self.reply(call, self.in_dialog_response(call.invite, "503 Service Unavailable", extra_to_tag=call.to_tag))
52
+ self._close_call(call, call.id)
53
+ elif call.id not in self.calls:
54
+ # the app hung up while we were still waiting for registration -
55
+ # drop the just-placed intercom call instead of ghost-ringing it
56
+ self.bye_outbound(call.out_cid)
57
+
58
+ def inbound_bridged_answered(self, out, resp_sdp, addr):
59
+ """the intercom callee answered our --inbound-target call: bind a
60
+ SipIntercomMedia to it and 200 OK the app (offer/answer SDP, SRTP
61
+ only when the app offered it)"""
62
+ call = out["bridged"]
63
+ offer = parse_sdp(call.invite.body)
64
+ media = SipIntercomMedia(self.o, self.rtsp, resp_sdp["ip"] or addr[0])
65
+ offer_a = media_addr(offer, "audio")
66
+ if offer_a:
67
+ media.set_provider(offer_a)
68
+ media.srtp = self._inbound_srtp(call, offer)
69
+ call.media = media
70
+ ok = self.in_dialog_response(call.invite, "200 OK", ctype="application/sdp", extra_to_tag=call.to_tag)
71
+ ok.body = call.trunk.answer_sdp(offer, media)
72
+ self.reply(call, ok)
73
+ call.state = "established"
74
+ self._fire_event("answered", call)
75
+ media.start()
76
+ log.info(
77
+ "inbound call established: SIP app <-> intercom %s (peer audio %s, protection %s)",
78
+ out["num"],
79
+ offer_a,
80
+ "srtp" if media.srtp else "rtp",
81
+ )
82
+
83
+ def _inbound_srtp(self, call, offer):
84
+ """SDES session for the inbound SIP leg when the caller's audio offer
85
+ is RTP/SAVP and the trunk encrypts (fritz never does); None = plain RTP"""
86
+ m = next((x for x in offer["media"] if x["type"] == "audio"), None)
87
+ if not (call.trunk.o.sip_srtp and srtp_available() and m and "SAVP" in m.get("proto", "")):
88
+ return None
89
+ s = SrtpSession()
90
+ return s if s.accept_answer(m) else None
@@ -0,0 +1,97 @@
1
+ """Local headset mode: answer calls on this machine."""
2
+
3
+ import logging
4
+ import time
5
+
6
+ from metzler.media.intercom import IntercomMedia
7
+ from metzler.media.local import LocalMediaBridge
8
+ from metzler.sip.sdp import sdp_answer_firmware, sdp_answer_talkback
9
+
10
+ log = logging.getLogger("indoor")
11
+
12
+
13
+ class LocalAnswerMixin:
14
+ """Local headset mode: answer calls on this machine."""
15
+
16
+ def answer_locally(self, call, door_a, door_v, remote_sdp):
17
+ """--local-audio mode: answer the door call ourselves, media <-> headset.
18
+ Runs off the listener thread; a CANCEL/BYE during the ring delay aborts the answer
19
+ (answering a cancelled call leaves stale dialog state on the registrar).
20
+ Ring-only unless --auto-answer: the main indoor treats an answering extension as
21
+ 'call taken' and stops ringing the real stations. Policy 'extension' answers only
22
+ calls the main indoor places to us (Subject 'This is a call to extension.'), never
23
+ the doorbell legs ('This is a call to app.')."""
24
+ if not self._should_answer(call):
25
+ return
26
+ if self.o.answer_delay:
27
+ time.sleep(self.o.answer_delay)
28
+ if call.state != "early" or not self.running:
29
+ return
30
+ talkback = not remote_sdp["media"] # hicore intercom offers carry no m= lines
31
+ # Intercom calls don't use talkback RTP: the caller RTSP-pulls our :554
32
+ # (our mic) and we pull the caller's :554 (their mic) - see IntercomMedia.
33
+ # The 200 OK still carries m=audio 9654: the caller's ACK path only needs
34
+ # some m= line to accept the answer before it opens the RTSP pull.
35
+ intercom = talkback and self.rtsp
36
+ try:
37
+ call.local = self._local_media(call, door_a, door_v, remote_sdp, talkback, intercom)
38
+ except OSError as e:
39
+ # e.g. a prior call's bridge still holds the fixed talkback port —
40
+ # decline rather than leave the caller ringing forever
41
+ log.warning("media bridge init failed (%s) - declining call", e)
42
+ self.reply(call, self.in_dialog_response(call.invite, "486 Busy Here", extra_to_tag=call.to_tag))
43
+ call.state = "closed"
44
+ return
45
+ call.local.start()
46
+ if call.state != "early":
47
+ return call.local.stop()
48
+ ok = self.in_dialog_response(call.invite, "200 OK", ctype="application/sdp", extra_to_tag=call.to_tag)
49
+ ok.body = self._local_answer_sdp(call, talkback)
50
+ self.reply(call, ok)
51
+ call.state = "established"
52
+ self._fire_event("answered", call)
53
+ self._log_local_answer(call, talkback, intercom)
54
+
55
+ def _should_answer(self, call):
56
+ subject = (call.invite.get("Subject") or "").lower()
57
+ if self.o.auto_answer == "off" or (self.o.auto_answer == "extension" and "extension" not in subject):
58
+ log.info(
59
+ "ringing only (auto-answer=%s, subject=%r) - waiting for the caller to CANCEL/BYE",
60
+ self.o.auto_answer,
61
+ subject,
62
+ )
63
+ return False
64
+ return True
65
+
66
+ def _local_media(self, call, door_a, door_v, remote_sdp, talkback, intercom):
67
+ if intercom:
68
+ return IntercomMedia(self.o, self.rtsp, remote_sdp["ip"] or call.addr[0])
69
+ ip = remote_sdp["ip"]
70
+ audio = (
71
+ (door_a["ip"] or ip, door_a["port"]) if door_a else (ip, self.o.talkback_port) if talkback and ip else None
72
+ )
73
+ video = (door_v["ip"] or ip, door_v["port"]) if door_v else None
74
+ return LocalMediaBridge(self.o, audio, video, fixed=talkback)
75
+
76
+ def _local_answer_sdp(self, call, talkback):
77
+ if talkback:
78
+ return sdp_answer_talkback(self.o.serial, self.o.local_ip, self.o.talkback_port, opts=self.o)
79
+ return sdp_answer_firmware(self.o.username, self.o.local_ip, call.local.audio_port, call.local.video_port)
80
+
81
+ def _log_local_answer(self, call, talkback, intercom):
82
+ on = lambda p: "ON" if p else "OFF"
83
+ log.info(
84
+ "local call answered (%s) — speaker %s, mic %s, video %s; peer audio %s video %s",
85
+ (
86
+ f"intercom RTSP :{self.o.rtsp_port}"
87
+ if intercom
88
+ else f"talkback RTP :{self.o.talkback_port}"
89
+ if talkback
90
+ else "negotiated RTP"
91
+ ),
92
+ on(call.local.aplay),
93
+ on(call.local.arecord),
94
+ on(call.local.ffplay),
95
+ call.local.door_a,
96
+ call.local.door_v,
97
+ )
@@ -0,0 +1,137 @@
1
+ """Outbound calls to other stations (--call, mimics _client_call)."""
2
+
3
+ import logging
4
+ import time
5
+
6
+ from metzler.media.intercom import IntercomMedia
7
+ from metzler.media.local import LocalMediaBridge
8
+ from metzler.sip.message import UA, Packet, branch, call_id, uri_of
9
+ from metzler.sip.sdp import media_addr, parse_sdp, sdp_answer_talkback
10
+
11
+ log = logging.getLogger("indoor")
12
+
13
+
14
+ class OutboundCallMixin:
15
+ """Outbound calls to other stations (--call, mimics _client_call)."""
16
+
17
+ def call_out(self, num, bridged=None):
18
+ """place a call to devLongNum `num` via the registrar (request-uri :5065).
19
+ `bridged` links an inbound provider Call: its answer/ring/fail events
20
+ get forwarded to the app instead of driving local headset media."""
21
+ if not self.registered.wait(15):
22
+ log.error("not registered, cannot call")
23
+ return False
24
+ # --call accepts "num" (via registrar) or "num@ip" (direct :5060 —
25
+ # the firmware's netAltRoute path in sip_callLongNum, sip_client.c)
26
+ peer_ip = None
27
+ if "@" in num:
28
+ num, peer_ip = num.split("@", 1)
29
+ host, port = (peer_ip, 5060) if peer_ip else (self.o.server, self.o.server_port)
30
+ uri = f"sip:{num}@{host}:{port}"
31
+ p = self.base_request(
32
+ "INVITE",
33
+ uri,
34
+ to_uri=f"<sip:{num}@{host}:{port}>",
35
+ frm_uri=f"<sip:{self.o.username}@{self.o.local_ip}>;tag={self.local_tag}",
36
+ )
37
+ p.set("Call-ID", call_id())
38
+ p.set("CSeq", "1 INVITE")
39
+ p.set("Subject", "This is a call to extension.")
40
+ p.set("Content-Type", "application/sdp")
41
+ # indoor->indoor offer == the header-only answer template (no m= lines):
42
+ # media flows via the symmetric rtsp://<peer>:554 pulls opened after ACK.
43
+ p.body = sdp_answer_talkback(self.o.serial, self.o.local_ip, opts=self.o)
44
+ cid = p.get("Call-ID")
45
+ self.out_calls[cid] = {
46
+ "num": num,
47
+ "invite": p,
48
+ "local": None,
49
+ "to_tag": None,
50
+ "peer": self.server,
51
+ "bridged": bridged,
52
+ "ts": time.time(),
53
+ }
54
+ if bridged:
55
+ bridged.out_cid = cid
56
+ log.info("calling %s via %s:%d ...", num, host, port)
57
+ self.out_calls[cid]["peer"] = (host, port)
58
+ self.send(p, (host, port))
59
+ return True
60
+
61
+ def out_answered(self, out, resp, addr):
62
+ resp_sdp = parse_sdp(resp.body)
63
+ self._ack_outbound(out, resp)
64
+ out["established"] = True
65
+ if out.get("bridged"):
66
+ return self.inbound_bridged_answered(out, resp_sdp, addr)
67
+ try:
68
+ out["local"] = self._outbound_media(resp_sdp, addr)
69
+ out["local"].start()
70
+ except OSError as e:
71
+ log.warning("media start failed: %s", e)
72
+ log.info("outbound call to %s established (peer %s)", out["num"], resp_sdp["ip"] or addr[0])
73
+
74
+ def _ack_outbound(self, out, resp):
75
+ """ACK the callee's 200 OK at its Contact; remember the dialog for BYE"""
76
+ out["to_tag"] = resp.get("To") or ""
77
+ out["ack_uri"] = uri_of(resp.get("Contact") or out["invite"].status_line.split()[1])
78
+ ack = Packet()
79
+ ack.status_line = f"ACK {out['ack_uri']} SIP/2.0"
80
+ ack.set("Via", f"SIP/2.0/UDP {self.o.local_ip}:{self.bind_port};rport;branch={branch()}")
81
+ ack.set("Max-Forwards", "70")
82
+ ack.set("Contact", self.contact())
83
+ ack.set("To", out["to_tag"])
84
+ ack.set("From", resp.get("From"))
85
+ ack.set("Call-ID", resp.get("Call-ID"))
86
+ ack.set("CSeq", "1 ACK")
87
+ ack.set("User-Agent", UA)
88
+ self.send(ack, out["peer"])
89
+
90
+ def _outbound_media(self, resp_sdp, addr):
91
+ """door-style answer with media ports -> RTP to the headset; an
92
+ intercom (header-only) answer -> symmetric rtsp://<peer>:554 pull"""
93
+ a, v = media_addr(resp_sdp, "audio"), media_addr(resp_sdp, "video")
94
+ if a or v:
95
+ return LocalMediaBridge(self.o, a, v)
96
+ return IntercomMedia(self.o, self.rtsp, resp_sdp["ip"] or addr[0])
97
+
98
+ def bye_outbound(self, cid):
99
+ out = self.out_calls.pop(cid, None)
100
+ if not out:
101
+ return
102
+ if out.get("local"):
103
+ out["local"].stop()
104
+ if not out.get("established"): # early dialog -> CANCEL
105
+ p = Packet()
106
+ uri = out["invite"].status_line.split()[1]
107
+ p.status_line = f"CANCEL {uri} SIP/2.0"
108
+ # RFC 3261 9.1: the CANCEL only matches the INVITE transaction
109
+ # with the same Via branch and CSeq number (else a 481 and the
110
+ # callee keeps ringing)
111
+ p.set("Via", out["invite"].get("Via"))
112
+ p.set("Max-Forwards", "70")
113
+ p.set("To", out["invite"].get("To"))
114
+ p.set("From", out["invite"].get("From"))
115
+ p.set("Call-ID", cid)
116
+ p.set("CSeq", out["invite"].get("CSeq").replace("INVITE", "CANCEL"))
117
+ p.set("User-Agent", UA)
118
+ try:
119
+ self.send(p, out["peer"])
120
+ except OSError:
121
+ pass
122
+ return
123
+ p = Packet()
124
+ uri = out.get("ack_uri") or out["invite"].status_line.split()[1]
125
+ p.status_line = f"BYE {uri} SIP/2.0"
126
+ p.set("Via", f"SIP/2.0/UDP {self.o.local_ip}:{self.bind_port};rport;branch={branch()}")
127
+ p.set("Max-Forwards", "70")
128
+ p.set("Contact", self.contact())
129
+ p.set("To", out["to_tag"])
130
+ p.set("From", out["invite"].get("From"))
131
+ p.set("Call-ID", cid)
132
+ p.set("CSeq", "2 BYE")
133
+ p.set("User-Agent", UA)
134
+ try:
135
+ self.send(p, out["peer"])
136
+ except OSError:
137
+ pass
@@ -0,0 +1,167 @@
1
+ """Registration at the intercom registrar (REGISTER with the
2
+ <regXML> body, Digest retry) and the MESSAGE heartbeat."""
3
+
4
+ import logging
5
+ import queue
6
+ import re
7
+ import threading
8
+ import time
9
+
10
+ from metzler.sip.digest import digest_response
11
+ from metzler.sip.message import call_id
12
+
13
+ log = logging.getLogger("indoor")
14
+
15
+
16
+ class IntercomRegistration:
17
+ """the station's REGISTER session at the intercom registrar (regXML +
18
+ digest retry). Replies are routed by reg Call-ID in handle_datagram.
19
+
20
+ Note: the registrar's dev_reg table keys devices by serial_no OR
21
+ dev_ip - two extensions from one source IP can never coexist, so
22
+ there is only ever one registration per station."""
23
+
24
+ def __init__(self, st, o):
25
+ self.st, self.o = st, o
26
+ self.username, self.name = o.username, o.name
27
+ self.password = o.password
28
+ self.mac, self.serial = o.mac, o.serial
29
+ self.reg_call_id, self.reg_cseq = call_id(), 1
30
+ self.reg_queue = queue.Queue()
31
+ self.registered = threading.Event()
32
+
33
+ def is_reg_response(self, pkt):
34
+ return pkt.get("Call-ID") == self.reg_call_id
35
+
36
+ def reg_xml(self):
37
+ # exact firmware field order (_sip_xml_get_reg_info_xml): serial, mac, name, floorNum
38
+ return (
39
+ f"<regXML>\r\n<regDevSerial>{self.serial}</regDevSerial>\r\n"
40
+ f"<regDevMacAddr>{self.mac}</regDevMacAddr>\r\n"
41
+ f"<regDevName>{self.name}</regDevName>\r\n"
42
+ f"<floorNum>{self.o.floor_num}</floorNum>\r\n</regXML>"
43
+ )
44
+
45
+ def build_register(self, expires=None, auth=None):
46
+ st = self.st
47
+ uri = f"sip:{self.o.server}:{self.o.server_port}"
48
+ # firmware: From = sip:<devLongNum>@<localip>, To = sip:<devLongNum>@<registrar>
49
+ p = st.base_request(
50
+ "REGISTER",
51
+ uri,
52
+ to_uri=f"<sip:{self.username}@{self.o.server}:{self.o.server_port}>",
53
+ frm_uri=f'"{self.name}"<sip:{self.username}@{self.o.local_ip}>;tag={st.local_tag}',
54
+ )
55
+ p.set("Call-ID", self.reg_call_id)
56
+ p.set("CSeq", f"{self.reg_cseq} REGISTER")
57
+ expires = self.o.expires if expires is None else expires
58
+ p.set("Expires", str(expires))
59
+ p.set("Content-Type", "text/xml")
60
+ if auth:
61
+ p.set("Authorization", auth)
62
+ # regXML on the unregister too (docs/firmware/intercom-registration.md §3
63
+ # verified): the delete clause is `serial_no='<s>' or dev_ip='<src>'` -
64
+ # the body lets the serial match (stale rows of our serial on OTHER IPs),
65
+ # and the registrar only strstr()s the raw text, never parses the XML.
66
+ # The firmware's own units send an empty body; both forms were verified
67
+ # live to get 200 + delete.
68
+ p.body = self.reg_xml()
69
+ return p
70
+
71
+ def register_loop(self):
72
+ while self.st.running:
73
+ try:
74
+ self.register_once()
75
+ self.registered.set()
76
+ except (RuntimeError, OSError) as e:
77
+ log.warning("register failed: %s", e)
78
+ self.registered.clear()
79
+ if self.st._stop.wait(max(30, self.o.expires // 2)):
80
+ break
81
+
82
+ def register_once(self):
83
+ while True: # drain stale responses
84
+ try:
85
+ self.reg_queue.get_nowait()
86
+ except queue.Empty:
87
+ break
88
+ p = self.build_register()
89
+ self.st.send(p, self.st.server)
90
+ deadline = time.time() + 10
91
+ while time.time() < deadline:
92
+ try:
93
+ resp = self.reg_queue.get(timeout=max(0.1, deadline - time.time()))
94
+ except queue.Empty:
95
+ break
96
+ if resp is None: # shutdown sentinel
97
+ raise RuntimeError("stopping")
98
+ if resp.status_line.startswith(("SIP/2.0 401", "SIP/2.0 407")):
99
+ hdr = resp.get("WWW-Authenticate") or resp.get("Proxy-Authenticate")
100
+ self.reg_cseq += 1
101
+ uri = f"sip:{self.o.server}:{self.o.server_port}"
102
+ auth = digest_response(hdr, "REGISTER", uri, self.username, self.password)
103
+ self.st.send(self.build_register(auth=auth), self.st.server)
104
+ elif resp.status_line.startswith("SIP/2.0 2"):
105
+ log.info(
106
+ "REGISTERED at %s:%d as %s (expires %ds)",
107
+ self.st.server[0],
108
+ self.st.server[1],
109
+ self.username,
110
+ self.o.expires,
111
+ )
112
+ return
113
+ elif re.match(r"SIP/2\.0 [456]", resp.status_line):
114
+ raise RuntimeError(resp.status_line)
115
+ raise RuntimeError("register timeout")
116
+
117
+ def unregister(self):
118
+ """fire-and-forget Expires:0 (no reply is awaited - shutdown is
119
+ tearing the station down anyway). Repeated three times: the
120
+ registrar's post-insert sync stall drops REGISTERs for ~5-10s, and a
121
+ dropped unregister leaves our dev_reg row alive until expiry."""
122
+ for attempt in range(3):
123
+ try:
124
+ self.st.send(self.build_register(expires=0), self.st.server)
125
+ except OSError:
126
+ return # socket already gone
127
+ if attempt < 2:
128
+ time.sleep(0.4)
129
+
130
+
131
+ class RegistrationMixin:
132
+ """registration plumbing + the MESSAGE heartbeat; IntercomRegistration
133
+ instance is created by init_registrations()"""
134
+
135
+ def init_registrations(self):
136
+ self.regs = [IntercomRegistration(self, self.o)]
137
+ self.registered = self.regs[0].registered # gates outbound calls
138
+
139
+ def reg_xml(self):
140
+ return self.regs[0].reg_xml()
141
+
142
+ def build_register(self, expires=None, auth=None):
143
+ return self.regs[0].build_register(expires, auth)
144
+
145
+ def heartbeat_loop(self):
146
+ while not self.registered.is_set() and self.running and not self._stop.wait(2):
147
+ pass
148
+ while self.running:
149
+ target = self.o.heartbeat_target or self.o.username
150
+ uri = f"sip:{target}@{self.o.server}:{self.o.server_port}"
151
+ p = self.base_request("MESSAGE", uri)
152
+ p.set("Call-ID", call_id())
153
+ p.set("CSeq", "1 MESSAGE")
154
+ p.set("Content-Type", "text/xml")
155
+ # firmware format: <header>{method,action,from-ip,to-ip}</header><body>{num}
156
+ p.body = (
157
+ "<videoIntercomMsg>\r\n<header>\r\n<method>1</method>\r\n"
158
+ "<action>1</action>\r\n"
159
+ f"<from>{self.o.local_ip}</from>\r\n<to>{self.o.server}</to>\r\n"
160
+ "</header>\r\n<body>\r\n<num>1</num>\r\n</body>\r\n</videoIntercomMsg>"
161
+ )
162
+ try:
163
+ self.send(p, self.server)
164
+ except OSError:
165
+ pass
166
+ if self._stop.wait(self.o.heartbeat_interval):
167
+ break