aionecpbx 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.
- aionecpbx/__init__.py +73 -0
- aionecpbx/__main__.py +111 -0
- aionecpbx/ami.py +315 -0
- aionecpbx/client.py +171 -0
- aionecpbx/py.typed +0 -0
- aionecpbx/smdr.py +331 -0
- aionecpbx-0.1.0.dist-info/METADATA +120 -0
- aionecpbx-0.1.0.dist-info/RECORD +12 -0
- aionecpbx-0.1.0.dist-info/WHEEL +4 -0
- aionecpbx-0.1.0.dist-info/entry_points.txt +2 -0
- aionecpbx-0.1.0.dist-info/licenses/LICENSE +29 -0
- aionecpbx-0.1.0.dist-info/licenses/NOTICE +6 -0
aionecpbx/__init__.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Async clients for NEC SL2100 and SV9100 phone systems.
|
|
2
|
+
|
|
3
|
+
* :class:`SmdrClient` keeps a connection to the phone system's SMDR port and
|
|
4
|
+
hands over each call-log line; :func:`parse_line` turns a line into an
|
|
5
|
+
:class:`SmdrRecord`.
|
|
6
|
+
* :class:`AmiClient` follows live calls (ringing, answered, ended) through
|
|
7
|
+
FreePBX's Asterisk Manager Interface, and turns do-not-disturb on and off.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from .ami import (
|
|
13
|
+
DEFAULT_AMI_PORT,
|
|
14
|
+
LIVE_ANSWERED,
|
|
15
|
+
LIVE_ENDED,
|
|
16
|
+
LIVE_RINGING,
|
|
17
|
+
AmiAuthError,
|
|
18
|
+
AmiClient,
|
|
19
|
+
LiveCall,
|
|
20
|
+
async_test_login,
|
|
21
|
+
parse_message,
|
|
22
|
+
)
|
|
23
|
+
from .client import DEFAULT_SMDR_PORT, SmdrClient, async_probe
|
|
24
|
+
from .smdr import (
|
|
25
|
+
DATE_AUTO,
|
|
26
|
+
DATE_DMY,
|
|
27
|
+
DATE_MDY,
|
|
28
|
+
DATE_ORDERS,
|
|
29
|
+
DIRECTION_INCOMING,
|
|
30
|
+
DIRECTION_INTERNAL,
|
|
31
|
+
DIRECTION_OUTGOING,
|
|
32
|
+
DIRECTION_UNKNOWN,
|
|
33
|
+
SmdrRecord,
|
|
34
|
+
format_mapping,
|
|
35
|
+
is_record_line,
|
|
36
|
+
lookup_name,
|
|
37
|
+
normalise_number,
|
|
38
|
+
parse_line,
|
|
39
|
+
parse_mapping,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__version__ = "0.1.0"
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"DATE_AUTO",
|
|
46
|
+
"DATE_DMY",
|
|
47
|
+
"DATE_MDY",
|
|
48
|
+
"DATE_ORDERS",
|
|
49
|
+
"DEFAULT_AMI_PORT",
|
|
50
|
+
"DEFAULT_SMDR_PORT",
|
|
51
|
+
"DIRECTION_INCOMING",
|
|
52
|
+
"DIRECTION_INTERNAL",
|
|
53
|
+
"DIRECTION_OUTGOING",
|
|
54
|
+
"DIRECTION_UNKNOWN",
|
|
55
|
+
"LIVE_ANSWERED",
|
|
56
|
+
"LIVE_ENDED",
|
|
57
|
+
"LIVE_RINGING",
|
|
58
|
+
"AmiAuthError",
|
|
59
|
+
"AmiClient",
|
|
60
|
+
"LiveCall",
|
|
61
|
+
"SmdrClient",
|
|
62
|
+
"SmdrRecord",
|
|
63
|
+
"__version__",
|
|
64
|
+
"async_probe",
|
|
65
|
+
"async_test_login",
|
|
66
|
+
"format_mapping",
|
|
67
|
+
"is_record_line",
|
|
68
|
+
"lookup_name",
|
|
69
|
+
"normalise_number",
|
|
70
|
+
"parse_line",
|
|
71
|
+
"parse_mapping",
|
|
72
|
+
"parse_message",
|
|
73
|
+
]
|
aionecpbx/__main__.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Command-line tool: ``python -m aionecpbx`` or ``aionecpbx``.
|
|
2
|
+
|
|
3
|
+
Examples::
|
|
4
|
+
|
|
5
|
+
aionecpbx parse "IC 0001 10:00 001 00:01:00 103 0491570156"
|
|
6
|
+
aionecpbx listen 192.168.0.10
|
|
7
|
+
aionecpbx ami 192.168.0.20 --username homeassistant --secret ...
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import asyncio
|
|
14
|
+
from collections.abc import Sequence
|
|
15
|
+
import contextlib
|
|
16
|
+
from datetime import datetime
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import sys
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from . import (
|
|
23
|
+
DEFAULT_AMI_PORT,
|
|
24
|
+
DEFAULT_SMDR_PORT,
|
|
25
|
+
AmiAuthError,
|
|
26
|
+
AmiClient,
|
|
27
|
+
LiveCall,
|
|
28
|
+
SmdrClient,
|
|
29
|
+
is_record_line,
|
|
30
|
+
parse_line,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _print(value: Any) -> None:
|
|
35
|
+
print(json.dumps(value, default=str), flush=True)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _record(line: str) -> dict[str, Any] | None:
|
|
39
|
+
if not is_record_line(line):
|
|
40
|
+
return None
|
|
41
|
+
record = parse_line(line, now=datetime.now())
|
|
42
|
+
return record.as_dict() if record else None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
async def _listen(host: str, port: int) -> None:
|
|
46
|
+
def on_line(line: str) -> None:
|
|
47
|
+
_print(_record(line) or {"raw": line, "record": False})
|
|
48
|
+
|
|
49
|
+
def on_state(connected: bool) -> None:
|
|
50
|
+
print(f"# {'connected to' if connected else 'lost'} {host}:{port}", file=sys.stderr)
|
|
51
|
+
|
|
52
|
+
client = SmdrClient(host, port, on_line, on_state)
|
|
53
|
+
client.start()
|
|
54
|
+
try:
|
|
55
|
+
await asyncio.Event().wait()
|
|
56
|
+
finally:
|
|
57
|
+
await client.stop()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def _ami(host: str, port: int, username: str, secret: str) -> None:
|
|
61
|
+
def on_change(call: LiveCall, what: str) -> None:
|
|
62
|
+
_print({"change": what, **call.__dict__})
|
|
63
|
+
|
|
64
|
+
client = AmiClient(host, port, username, secret, on_change)
|
|
65
|
+
client.start()
|
|
66
|
+
try:
|
|
67
|
+
# The client only gives up when FreePBX rejects the login.
|
|
68
|
+
assert client._task is not None
|
|
69
|
+
await client._task
|
|
70
|
+
raise AmiAuthError(client.last_error or "login rejected")
|
|
71
|
+
finally:
|
|
72
|
+
await client.stop()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
76
|
+
"""Run the command-line tool."""
|
|
77
|
+
parser = argparse.ArgumentParser(prog="aionecpbx", description=__doc__.splitlines()[0])
|
|
78
|
+
parser.add_argument("-v", "--verbose", action="store_true", help="debug logging")
|
|
79
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
80
|
+
|
|
81
|
+
parse = sub.add_parser("parse", help="parse one SMDR line")
|
|
82
|
+
parse.add_argument("line")
|
|
83
|
+
|
|
84
|
+
listen = sub.add_parser("listen", help="print each call as the phone system logs it")
|
|
85
|
+
listen.add_argument("host")
|
|
86
|
+
listen.add_argument("--port", type=int, default=DEFAULT_SMDR_PORT)
|
|
87
|
+
|
|
88
|
+
ami = sub.add_parser("ami", help="print live calls from FreePBX")
|
|
89
|
+
ami.add_argument("host")
|
|
90
|
+
ami.add_argument("--port", type=int, default=DEFAULT_AMI_PORT)
|
|
91
|
+
ami.add_argument("--username", required=True)
|
|
92
|
+
ami.add_argument("--secret", required=True)
|
|
93
|
+
|
|
94
|
+
args = parser.parse_args(argv)
|
|
95
|
+
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING)
|
|
96
|
+
if args.command == "parse":
|
|
97
|
+
_print(_record(args.line) or {"raw": args.line, "record": False})
|
|
98
|
+
return
|
|
99
|
+
with contextlib.suppress(KeyboardInterrupt): # pragma: no cover
|
|
100
|
+
try:
|
|
101
|
+
if args.command == "listen":
|
|
102
|
+
asyncio.run(_listen(args.host, args.port))
|
|
103
|
+
else:
|
|
104
|
+
asyncio.run(_ami(args.host, args.port, args.username, args.secret))
|
|
105
|
+
except AmiAuthError as err:
|
|
106
|
+
print(f"error: {err}", file=sys.stderr)
|
|
107
|
+
sys.exit(1)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__": # pragma: no cover
|
|
111
|
+
main()
|
aionecpbx/ami.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
"""Asterisk Manager Interface (AMI) client for live call state from FreePBX.
|
|
2
|
+
|
|
3
|
+
The NEC's call log (SMDR) only prints a line when a call ends. When calls also
|
|
4
|
+
pass through FreePBX (for example the lines bridged in with an ATA), Asterisk's
|
|
5
|
+
manager interface says the moment a phone starts ringing, is answered or hangs
|
|
6
|
+
up, and who is calling. This client logs in, listens to those events and keeps
|
|
7
|
+
a small table of live calls. It can also turn FreePBX's do-not-disturb on and
|
|
8
|
+
off per extension.
|
|
9
|
+
|
|
10
|
+
FreePBX: Settings > Asterisk Manager Users > Add Manager. Allow this Home
|
|
11
|
+
Assistant's address under "Permit", and give it at least read "call" and
|
|
12
|
+
"system" and write "system" (for do-not-disturb).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
import contextlib
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
import itertools
|
|
22
|
+
import logging
|
|
23
|
+
import time
|
|
24
|
+
|
|
25
|
+
_LOGGER = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
DEFAULT_AMI_PORT = 5038
|
|
28
|
+
_RECONNECT_MIN = 5
|
|
29
|
+
_RECONNECT_MAX = 300
|
|
30
|
+
_TIMEOUT = 10
|
|
31
|
+
|
|
32
|
+
LIVE_RINGING = "ringing"
|
|
33
|
+
LIVE_ANSWERED = "answered"
|
|
34
|
+
LIVE_ENDED = "ended"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class AmiAuthError(Exception):
|
|
38
|
+
"""FreePBX rejected the manager login."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class LiveCall:
|
|
43
|
+
"""One call in progress, as Asterisk sees it."""
|
|
44
|
+
|
|
45
|
+
uniqueid: str
|
|
46
|
+
caller_number: str | None = None
|
|
47
|
+
caller_name: str | None = None
|
|
48
|
+
extension: str | None = None # the extension or number being rung
|
|
49
|
+
state: str = LIVE_RINGING
|
|
50
|
+
started: float = field(default_factory=time.time)
|
|
51
|
+
answered: float | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def parse_message(block: str) -> dict[str, str]:
|
|
55
|
+
"""``Key: value`` lines into a dict (first value wins for repeated keys)."""
|
|
56
|
+
out: dict[str, str] = {}
|
|
57
|
+
for line in block.splitlines():
|
|
58
|
+
key, sep, value = line.partition(":")
|
|
59
|
+
if sep and key.strip() and key.strip() not in out:
|
|
60
|
+
out[key.strip()] = value.strip()
|
|
61
|
+
return out
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _clean(value: str | None) -> str | None:
|
|
65
|
+
if not value or value in ("<unknown>", "unknown", "s"):
|
|
66
|
+
return None
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class AmiClient:
|
|
71
|
+
"""Keeps an AMI connection, tracks live calls and calls back on changes."""
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
host: str,
|
|
76
|
+
port: int,
|
|
77
|
+
username: str,
|
|
78
|
+
secret: str,
|
|
79
|
+
on_change: Callable[[LiveCall, str], None],
|
|
80
|
+
on_state: Callable[[bool], None] | None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
self.host = host
|
|
83
|
+
self.port = port
|
|
84
|
+
self._username = username
|
|
85
|
+
self._secret = secret
|
|
86
|
+
self._on_change = on_change
|
|
87
|
+
self._on_state = on_state
|
|
88
|
+
self.calls: dict[str, LiveCall] = {}
|
|
89
|
+
self.connected = False
|
|
90
|
+
self.last_error: str | None = None
|
|
91
|
+
self._task: asyncio.Task[None] | None = None
|
|
92
|
+
self._writer: asyncio.StreamWriter | None = None
|
|
93
|
+
self._ids = itertools.count(1)
|
|
94
|
+
self._pending: dict[str, asyncio.Future[dict[str, str]]] = {}
|
|
95
|
+
self._auth_failed = False
|
|
96
|
+
|
|
97
|
+
# ── lifecycle ──────────────────────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
def start(self) -> None:
|
|
100
|
+
if self._task is None or self._task.done():
|
|
101
|
+
self._task = asyncio.get_running_loop().create_task(
|
|
102
|
+
self._run(), name=f"aionecpbx ami {self.host}:{self.port}"
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
async def stop(self) -> None:
|
|
106
|
+
task, self._task = self._task, None
|
|
107
|
+
if task:
|
|
108
|
+
task.cancel()
|
|
109
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
110
|
+
await task
|
|
111
|
+
await self._close()
|
|
112
|
+
self._set_connected(False)
|
|
113
|
+
|
|
114
|
+
def _set_connected(self, value: bool) -> None:
|
|
115
|
+
if value != self.connected:
|
|
116
|
+
self.connected = value
|
|
117
|
+
if self._on_state:
|
|
118
|
+
self._on_state(value)
|
|
119
|
+
|
|
120
|
+
async def _close(self) -> None:
|
|
121
|
+
writer, self._writer = self._writer, None
|
|
122
|
+
for future in self._pending.values():
|
|
123
|
+
if not future.done():
|
|
124
|
+
future.set_exception(ConnectionError("AMI connection closed"))
|
|
125
|
+
self._pending.clear()
|
|
126
|
+
if writer:
|
|
127
|
+
writer.close()
|
|
128
|
+
with contextlib.suppress(OSError, asyncio.CancelledError):
|
|
129
|
+
await writer.wait_closed()
|
|
130
|
+
|
|
131
|
+
async def _run(self) -> None:
|
|
132
|
+
delay = _RECONNECT_MIN
|
|
133
|
+
while not self._auth_failed:
|
|
134
|
+
try:
|
|
135
|
+
reader, self._writer = await asyncio.wait_for(
|
|
136
|
+
asyncio.open_connection(self.host, self.port), _TIMEOUT
|
|
137
|
+
)
|
|
138
|
+
await asyncio.wait_for(reader.readline(), _TIMEOUT) # banner
|
|
139
|
+
reader_task = asyncio.get_running_loop().create_task(self._read(reader))
|
|
140
|
+
try:
|
|
141
|
+
reply = await self.action(
|
|
142
|
+
"Login", Username=self._username, Secret=self._secret, Events="call,system"
|
|
143
|
+
)
|
|
144
|
+
if reply.get("Response", "").lower() != "success":
|
|
145
|
+
raise AmiAuthError(reply.get("Message", "login rejected"))
|
|
146
|
+
_LOGGER.info("Connected to Asterisk manager at %s:%s", self.host, self.port)
|
|
147
|
+
self.last_error = None
|
|
148
|
+
self._set_connected(True)
|
|
149
|
+
delay = _RECONNECT_MIN
|
|
150
|
+
await reader_task
|
|
151
|
+
finally:
|
|
152
|
+
reader_task.cancel()
|
|
153
|
+
with contextlib.suppress(asyncio.CancelledError, Exception):
|
|
154
|
+
await reader_task
|
|
155
|
+
except AmiAuthError as err:
|
|
156
|
+
self.last_error = f"login: {err}"
|
|
157
|
+
self._auth_failed = True # don't hammer FreePBX with a wrong password
|
|
158
|
+
_LOGGER.error("Asterisk manager login rejected: %s", err)
|
|
159
|
+
except (OSError, TimeoutError, ConnectionError, asyncio.IncompleteReadError) as err:
|
|
160
|
+
self.last_error = f"connect: {err}"
|
|
161
|
+
_LOGGER.debug("AMI %s:%s: %s", self.host, self.port, err)
|
|
162
|
+
finally:
|
|
163
|
+
await self._close()
|
|
164
|
+
self._set_connected(False)
|
|
165
|
+
self._end_all()
|
|
166
|
+
if self._auth_failed:
|
|
167
|
+
return
|
|
168
|
+
await asyncio.sleep(delay)
|
|
169
|
+
delay = min(delay * 2, _RECONNECT_MAX)
|
|
170
|
+
|
|
171
|
+
# ── protocol ───────────────────────────────────────────────────────────
|
|
172
|
+
|
|
173
|
+
async def action(self, name: str, **fields: str) -> dict[str, str]:
|
|
174
|
+
"""Send an action and wait for its response."""
|
|
175
|
+
if self._writer is None:
|
|
176
|
+
raise ConnectionError("not connected to the Asterisk manager")
|
|
177
|
+
action_id = f"ha{next(self._ids)}"
|
|
178
|
+
future: asyncio.Future[dict[str, str]] = asyncio.get_running_loop().create_future()
|
|
179
|
+
self._pending[action_id] = future
|
|
180
|
+
lines = [f"Action: {name}", f"ActionID: {action_id}"]
|
|
181
|
+
lines += [f"{key}: {value}" for key, value in fields.items()]
|
|
182
|
+
self._writer.write(("\r\n".join(lines) + "\r\n\r\n").encode())
|
|
183
|
+
await self._writer.drain()
|
|
184
|
+
try:
|
|
185
|
+
return await asyncio.wait_for(future, _TIMEOUT)
|
|
186
|
+
finally:
|
|
187
|
+
self._pending.pop(action_id, None)
|
|
188
|
+
|
|
189
|
+
async def _read(self, reader: asyncio.StreamReader) -> None:
|
|
190
|
+
buffer: list[str] = []
|
|
191
|
+
while True:
|
|
192
|
+
raw = await reader.readline()
|
|
193
|
+
if not raw:
|
|
194
|
+
raise ConnectionError("closed by the Asterisk manager")
|
|
195
|
+
line = raw.decode(errors="replace").rstrip("\r\n")
|
|
196
|
+
if line:
|
|
197
|
+
buffer.append(line)
|
|
198
|
+
continue
|
|
199
|
+
if buffer:
|
|
200
|
+
self._handle(parse_message("\n".join(buffer)))
|
|
201
|
+
buffer = []
|
|
202
|
+
|
|
203
|
+
def _handle(self, msg: dict[str, str]) -> None:
|
|
204
|
+
if "Response" in msg and "follow" in msg.get("Message", "").lower():
|
|
205
|
+
return # the answer comes in an event with the same ActionID (DBGet)
|
|
206
|
+
if "Response" in msg or ("ActionID" in msg and "Event" not in msg):
|
|
207
|
+
future = self._pending.get(msg.get("ActionID", ""))
|
|
208
|
+
if future and not future.done():
|
|
209
|
+
future.set_result(msg)
|
|
210
|
+
return
|
|
211
|
+
event = msg.get("Event")
|
|
212
|
+
if event == "DBGetResponse":
|
|
213
|
+
future = self._pending.get(msg.get("ActionID", ""))
|
|
214
|
+
if future and not future.done():
|
|
215
|
+
future.set_result(msg)
|
|
216
|
+
return
|
|
217
|
+
if event:
|
|
218
|
+
try:
|
|
219
|
+
self._call_event(event, msg)
|
|
220
|
+
except Exception: # a strange event must never drop the connection
|
|
221
|
+
_LOGGER.exception("Error handling AMI event %s", event)
|
|
222
|
+
|
|
223
|
+
def _call_event(self, event: str, msg: dict[str, str]) -> None:
|
|
224
|
+
uid = msg.get("Linkedid") or msg.get("Uniqueid")
|
|
225
|
+
if not uid:
|
|
226
|
+
return
|
|
227
|
+
call = self.calls.get(uid)
|
|
228
|
+
if event in ("Newchannel", "DialBegin") or (event == "Newstate" and call is None):
|
|
229
|
+
if call is None:
|
|
230
|
+
if event == "Newchannel" and msg.get("ChannelStateDesc") not in ("Ring", "Ringing"):
|
|
231
|
+
return # an outgoing leg or a local channel, not a call coming in
|
|
232
|
+
call = self.calls[uid] = LiveCall(uid)
|
|
233
|
+
call.caller_number = call.caller_number or _clean(msg.get("CallerIDNum"))
|
|
234
|
+
call.caller_name = call.caller_name or _clean(msg.get("CallerIDName"))
|
|
235
|
+
if event == "DialBegin":
|
|
236
|
+
call.extension = _clean(msg.get("DestCallerIDNum")) or _clean(msg.get("DialString"))
|
|
237
|
+
else:
|
|
238
|
+
call.extension = call.extension or _clean(msg.get("Exten"))
|
|
239
|
+
self._on_change(call, LIVE_RINGING)
|
|
240
|
+
elif event == "Newstate" and call is not None:
|
|
241
|
+
if (
|
|
242
|
+
msg.get("ChannelStateDesc") == "Up"
|
|
243
|
+
and call.state != LIVE_ANSWERED
|
|
244
|
+
and msg.get("Uniqueid") != uid
|
|
245
|
+
):
|
|
246
|
+
call.state, call.answered = LIVE_ANSWERED, time.time()
|
|
247
|
+
self._on_change(call, LIVE_ANSWERED)
|
|
248
|
+
elif event == "DialEnd" and call is not None:
|
|
249
|
+
if msg.get("DialStatus") == "ANSWER" and call.state != LIVE_ANSWERED:
|
|
250
|
+
call.state, call.answered = LIVE_ANSWERED, time.time()
|
|
251
|
+
call.extension = _clean(msg.get("DestCallerIDNum")) or call.extension
|
|
252
|
+
self._on_change(call, LIVE_ANSWERED)
|
|
253
|
+
elif event == "Hangup" and call is not None and msg.get("Uniqueid") == uid:
|
|
254
|
+
del self.calls[uid]
|
|
255
|
+
call.state = LIVE_ENDED
|
|
256
|
+
self._on_change(call, LIVE_ENDED)
|
|
257
|
+
|
|
258
|
+
def _end_all(self) -> None:
|
|
259
|
+
for uid in list(self.calls):
|
|
260
|
+
call = self.calls.pop(uid)
|
|
261
|
+
call.state = LIVE_ENDED
|
|
262
|
+
self._on_change(call, LIVE_ENDED)
|
|
263
|
+
|
|
264
|
+
# ── state for entities ─────────────────────────────────────────────────
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def ringing(self) -> list[LiveCall]:
|
|
268
|
+
return [c for c in self.calls.values() if c.state == LIVE_RINGING]
|
|
269
|
+
|
|
270
|
+
@property
|
|
271
|
+
def active(self) -> list[LiveCall]:
|
|
272
|
+
return [c for c in self.calls.values() if c.state == LIVE_ANSWERED]
|
|
273
|
+
|
|
274
|
+
# ── do not disturb (FreePBX keeps it in AstDB: DND/<ext> = YES) ────────
|
|
275
|
+
|
|
276
|
+
async def get_dnd(self, extension: str) -> bool:
|
|
277
|
+
reply = await self.action("DBGet", Family="DND", Key=extension)
|
|
278
|
+
return reply.get("Val", reply.get("Value", "")).upper() == "YES"
|
|
279
|
+
|
|
280
|
+
async def set_dnd(self, extension: str, on: bool) -> None:
|
|
281
|
+
if on:
|
|
282
|
+
reply = await self.action("DBPut", Family="DND", Key=extension, Val="YES")
|
|
283
|
+
else:
|
|
284
|
+
reply = await self.action("DBDel", Family="DND", Key=extension)
|
|
285
|
+
if reply.get("Response", "").lower() == "error" and on:
|
|
286
|
+
raise ConnectionError(reply.get("Message", "FreePBX refused"))
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
async def async_test_login(host: str, port: int, username: str, secret: str) -> None:
|
|
290
|
+
"""Log in once and out again. Raises OSError/TimeoutError or AmiAuthError."""
|
|
291
|
+
reader, writer = await asyncio.wait_for(asyncio.open_connection(host, port), _TIMEOUT)
|
|
292
|
+
try:
|
|
293
|
+
await asyncio.wait_for(reader.readline(), _TIMEOUT) # banner
|
|
294
|
+
login = f"Action: Login\r\nUsername: {username}\r\nSecret: {secret}\r\n"
|
|
295
|
+
writer.write((login + "Events: off\r\n\r\n").encode())
|
|
296
|
+
await writer.drain()
|
|
297
|
+
lines: list[str] = []
|
|
298
|
+
while True:
|
|
299
|
+
raw = await asyncio.wait_for(reader.readline(), _TIMEOUT)
|
|
300
|
+
if not raw:
|
|
301
|
+
raise ConnectionError("closed by the Asterisk manager")
|
|
302
|
+
line = raw.decode(errors="replace").strip()
|
|
303
|
+
if not line and lines:
|
|
304
|
+
break
|
|
305
|
+
if line:
|
|
306
|
+
lines.append(line)
|
|
307
|
+
reply = parse_message("\n".join(lines))
|
|
308
|
+
if reply.get("Response", "").lower() != "success":
|
|
309
|
+
raise AmiAuthError(reply.get("Message", "login rejected"))
|
|
310
|
+
writer.write(b"Action: Logoff\r\n\r\n")
|
|
311
|
+
await writer.drain()
|
|
312
|
+
finally:
|
|
313
|
+
writer.close()
|
|
314
|
+
with contextlib.suppress(OSError):
|
|
315
|
+
await writer.wait_closed()
|
aionecpbx/client.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""TCP client that reads the SMDR stream from an NEC SL2100 / SV9100."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections.abc import Awaitable, Callable
|
|
7
|
+
import contextlib
|
|
8
|
+
import logging
|
|
9
|
+
import socket
|
|
10
|
+
|
|
11
|
+
_LOGGER = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
#: SMDR output port on Australian SL2100s (Program 10-20, type 5).
|
|
14
|
+
DEFAULT_SMDR_PORT = 4001
|
|
15
|
+
#: Seconds between reconnect attempts: doubles from the minimum to the maximum.
|
|
16
|
+
RECONNECT_MIN = 5
|
|
17
|
+
RECONNECT_MAX = 300
|
|
18
|
+
CONNECT_TIMEOUT = 10
|
|
19
|
+
#: TCP keepalive, so a phone system that vanished is noticed within about
|
|
20
|
+
#: 90 seconds (idle, then interval x count).
|
|
21
|
+
KEEPALIVE_IDLE = 60
|
|
22
|
+
KEEPALIVE_INTERVAL = 10
|
|
23
|
+
KEEPALIVE_COUNT = 3
|
|
24
|
+
|
|
25
|
+
LineCallback = Callable[[str], Awaitable[None] | None]
|
|
26
|
+
StateCallback = Callable[[bool], None]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def async_probe(host: str, port: int, timeout: float = CONNECT_TIMEOUT) -> None:
|
|
30
|
+
"""Open and close a connection; raises OSError / TimeoutError on failure."""
|
|
31
|
+
_reader, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout)
|
|
32
|
+
writer.close()
|
|
33
|
+
with contextlib.suppress(OSError):
|
|
34
|
+
await writer.wait_closed()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _enable_keepalive(writer: asyncio.StreamWriter) -> None:
|
|
38
|
+
"""Turn on TCP keepalive so a PBX that vanished (reboot, cable, switch)
|
|
39
|
+
is noticed and the client reconnects, instead of waiting forever."""
|
|
40
|
+
sock = writer.get_extra_info("socket")
|
|
41
|
+
if sock is None:
|
|
42
|
+
return
|
|
43
|
+
with contextlib.suppress(OSError, AttributeError):
|
|
44
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
|
45
|
+
for name, value in (
|
|
46
|
+
("TCP_KEEPIDLE", KEEPALIVE_IDLE),
|
|
47
|
+
("TCP_KEEPINTVL", KEEPALIVE_INTERVAL),
|
|
48
|
+
("TCP_KEEPCNT", KEEPALIVE_COUNT),
|
|
49
|
+
):
|
|
50
|
+
if hasattr(socket, name):
|
|
51
|
+
sock.setsockopt(socket.IPPROTO_TCP, getattr(socket, name), value)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _clean(data: bytes) -> str:
|
|
55
|
+
"""Decode bytes, dropping control characters other than tab."""
|
|
56
|
+
text = data.decode("ascii", errors="replace")
|
|
57
|
+
return "".join(ch for ch in text if ch == "\t" or ch >= " ").replace("�", "")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class SmdrClient:
|
|
61
|
+
"""Keeps a connection to the PBX's SMDR port open and hands over each line.
|
|
62
|
+
|
|
63
|
+
The SL2100 is the TCP server (Program 10-20, external equipment type 5)
|
|
64
|
+
and simply prints a text line when each call ends. If the connection
|
|
65
|
+
drops, the client reconnects with back-off. Only one client can hold the
|
|
66
|
+
SMDR port at a time, so close any other call-logging software.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
host: str,
|
|
72
|
+
port: int,
|
|
73
|
+
on_line: LineCallback,
|
|
74
|
+
on_state: StateCallback | None = None,
|
|
75
|
+
) -> None:
|
|
76
|
+
self.host = host
|
|
77
|
+
self.port = port
|
|
78
|
+
self._on_line = on_line
|
|
79
|
+
self._on_state = on_state
|
|
80
|
+
self._task: asyncio.Task[None] | None = None
|
|
81
|
+
self._writer: asyncio.StreamWriter | None = None
|
|
82
|
+
self.connected = False
|
|
83
|
+
self.lines_received = 0
|
|
84
|
+
self.last_error: str | None = None
|
|
85
|
+
|
|
86
|
+
def start(self) -> None:
|
|
87
|
+
"""Start the background read loop."""
|
|
88
|
+
if self._task is None or self._task.done():
|
|
89
|
+
self._task = asyncio.get_running_loop().create_task(
|
|
90
|
+
self._run(), name=f"aionecpbx smdr {self.host}:{self.port}"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
async def stop(self) -> None:
|
|
94
|
+
"""Stop the read loop and close the socket."""
|
|
95
|
+
task, self._task = self._task, None
|
|
96
|
+
if task:
|
|
97
|
+
task.cancel()
|
|
98
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
99
|
+
await task
|
|
100
|
+
await self._close()
|
|
101
|
+
self._set_connected(False)
|
|
102
|
+
|
|
103
|
+
def _set_connected(self, value: bool) -> None:
|
|
104
|
+
if value != self.connected:
|
|
105
|
+
self.connected = value
|
|
106
|
+
if self._on_state:
|
|
107
|
+
self._on_state(value)
|
|
108
|
+
|
|
109
|
+
async def _close(self) -> None:
|
|
110
|
+
writer, self._writer = self._writer, None
|
|
111
|
+
if writer:
|
|
112
|
+
writer.close()
|
|
113
|
+
with contextlib.suppress(OSError, asyncio.CancelledError):
|
|
114
|
+
await writer.wait_closed()
|
|
115
|
+
|
|
116
|
+
async def _run(self) -> None:
|
|
117
|
+
delay = RECONNECT_MIN
|
|
118
|
+
while True:
|
|
119
|
+
try:
|
|
120
|
+
reader, writer = await asyncio.wait_for(
|
|
121
|
+
asyncio.open_connection(self.host, self.port), CONNECT_TIMEOUT
|
|
122
|
+
)
|
|
123
|
+
self._writer = writer
|
|
124
|
+
except (OSError, TimeoutError) as err:
|
|
125
|
+
self.last_error = f"connect: {err}"
|
|
126
|
+
_LOGGER.debug("SMDR connect to %s:%s failed: %s", self.host, self.port, err)
|
|
127
|
+
else:
|
|
128
|
+
_enable_keepalive(writer)
|
|
129
|
+
_LOGGER.info("Connected to SMDR at %s:%s", self.host, self.port)
|
|
130
|
+
self.last_error = None
|
|
131
|
+
self._set_connected(True)
|
|
132
|
+
delay = RECONNECT_MIN
|
|
133
|
+
try:
|
|
134
|
+
await self._read(reader)
|
|
135
|
+
except (OSError, asyncio.IncompleteReadError) as err:
|
|
136
|
+
self.last_error = f"read: {err}"
|
|
137
|
+
_LOGGER.warning("SMDR connection to %s lost: %s", self.host, err)
|
|
138
|
+
finally:
|
|
139
|
+
await self._close()
|
|
140
|
+
self._set_connected(False)
|
|
141
|
+
await asyncio.sleep(delay)
|
|
142
|
+
delay = min(delay * 2, RECONNECT_MAX)
|
|
143
|
+
|
|
144
|
+
async def _read(self, reader: asyncio.StreamReader) -> None:
|
|
145
|
+
buffer = b""
|
|
146
|
+
while True:
|
|
147
|
+
chunk = await reader.read(4096)
|
|
148
|
+
if not chunk:
|
|
149
|
+
self.last_error = "closed by PBX"
|
|
150
|
+
_LOGGER.info("SMDR connection closed by %s", self.host)
|
|
151
|
+
return
|
|
152
|
+
buffer += chunk.replace(b"\r\n", b"\n").replace(b"\r", b"\n").replace(b"\f", b"\n")
|
|
153
|
+
*lines, buffer = buffer.split(b"\n")
|
|
154
|
+
for raw in lines:
|
|
155
|
+
await self._deliver(raw)
|
|
156
|
+
if len(buffer) > 2048: # no line ending; never let it grow unbounded
|
|
157
|
+
await self._deliver(buffer)
|
|
158
|
+
buffer = b""
|
|
159
|
+
|
|
160
|
+
async def _deliver(self, raw: bytes) -> None:
|
|
161
|
+
line = _clean(raw)
|
|
162
|
+
if not line.strip():
|
|
163
|
+
return
|
|
164
|
+
self.lines_received += 1
|
|
165
|
+
_LOGGER.debug("SMDR line: %r", line)
|
|
166
|
+
try:
|
|
167
|
+
result = self._on_line(line)
|
|
168
|
+
if asyncio.iscoroutine(result):
|
|
169
|
+
await result
|
|
170
|
+
except Exception:
|
|
171
|
+
_LOGGER.exception("Error handling SMDR line %r", line)
|
aionecpbx/py.typed
ADDED
|
File without changes
|
aionecpbx/smdr.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""Parser for NEC SL2100 / SV9100 SMDR (Station Message Detail Recording) lines.
|
|
2
|
+
|
|
3
|
+
The SL2100 prints one fixed-width text line per finished call (Programming
|
|
4
|
+
Manual, Program 35-02, Table 2-11). The exact columns move about with the
|
|
5
|
+
35-01 / 35-02 options (name or number, date on or off, overseas or North
|
|
6
|
+
American format), so this parser works on tokens rather than character
|
|
7
|
+
offsets. It never raises: anything it cannot read comes back as ``None`` and
|
|
8
|
+
the raw line is always kept, so a new layout can be checked in the
|
|
9
|
+
diagnostics and added to the tests.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import asdict, dataclass, field
|
|
15
|
+
from datetime import date, datetime, time, timedelta
|
|
16
|
+
import re
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
DIRECTION_INCOMING = "incoming"
|
|
20
|
+
DIRECTION_OUTGOING = "outgoing"
|
|
21
|
+
DIRECTION_INTERNAL = "internal"
|
|
22
|
+
DIRECTION_UNKNOWN = "unknown"
|
|
23
|
+
|
|
24
|
+
# Class codes seen in NEC SMDR output (first or second column). The SV9100 /
|
|
25
|
+
# SL2100 "POT / PIN" family comes from real SV9100 output (see the ADFDiesel
|
|
26
|
+
# nec-smdr project): POT/POTA outgoing (A = with account code), PIN/IVIN
|
|
27
|
+
# incoming, PTRS a transferred trunk call, ICM internal.
|
|
28
|
+
_CLASS_DIRECTIONS: dict[str, str] = {
|
|
29
|
+
"POT": DIRECTION_OUTGOING,
|
|
30
|
+
"POTA": DIRECTION_OUTGOING,
|
|
31
|
+
"PIN": DIRECTION_INCOMING,
|
|
32
|
+
"IVIN": DIRECTION_INCOMING,
|
|
33
|
+
"PTRS": DIRECTION_INCOMING,
|
|
34
|
+
"IC": DIRECTION_INCOMING,
|
|
35
|
+
"IN": DIRECTION_INCOMING,
|
|
36
|
+
"INC": DIRECTION_INCOMING,
|
|
37
|
+
"DID": DIRECTION_INCOMING,
|
|
38
|
+
"DIL": DIRECTION_INCOMING,
|
|
39
|
+
"CLI": DIRECTION_INCOMING,
|
|
40
|
+
"OG": DIRECTION_OUTGOING,
|
|
41
|
+
"OUT": DIRECTION_OUTGOING,
|
|
42
|
+
"TR": DIRECTION_OUTGOING,
|
|
43
|
+
"TRF": DIRECTION_OUTGOING,
|
|
44
|
+
"IT": DIRECTION_INTERNAL,
|
|
45
|
+
"ICM": DIRECTION_INTERNAL,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
# Class codes that mean the call was transferred.
|
|
49
|
+
_TRANSFER_CLASSES = ("PTRS", "TRF")
|
|
50
|
+
|
|
51
|
+
DATE_AUTO = "auto"
|
|
52
|
+
DATE_DMY = "dmy"
|
|
53
|
+
DATE_MDY = "mdy"
|
|
54
|
+
DATE_ORDERS = (DATE_AUTO, DATE_DMY, DATE_MDY)
|
|
55
|
+
|
|
56
|
+
_MISSED_FLAGS = ("NO ANSWER", "NOANSWER", "ABANDON", "UNANSWERED", "LOST")
|
|
57
|
+
|
|
58
|
+
_HEADER_WORDS = ("CLSS", "STATION", "DURATION", "DIALLED", "DIALED")
|
|
59
|
+
_SUMMARY_WORDS = ("TOTAL", "SUMMARY", "DAILY", "WEEKLY", "MONTHLY", "PAGE")
|
|
60
|
+
|
|
61
|
+
_RE_DURATION = re.compile(r"(?<![\d:])(\d{1,2}):(\d{2}):(\d{2})(?![\d:])")
|
|
62
|
+
_RE_TIME = re.compile(r"(?<![\d:/])([01]?\d|2[0-3]):([0-5]\d)(?![\d:])")
|
|
63
|
+
_RE_DATE = re.compile(r"(?<![\d/])(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?(?![\d/])")
|
|
64
|
+
_RE_RING = re.compile(r"(?<![\d:])(\d{1,3}):([0-5]\d)(?![\d:])")
|
|
65
|
+
_RE_COST = re.compile(r"\$\s?[\d,]+(?:\.\d+)?")
|
|
66
|
+
# External numbers: 6+ digits, possibly ending in X where digits were hidden.
|
|
67
|
+
_RE_NUMBER = re.compile(r"(?<![\w:/])\+?\d[\d*#]{4,}[\dX]*(?![\w:/])")
|
|
68
|
+
_RE_SHORT = re.compile(r"(?<![\w:/$,.])(\d{2,5})(?![\w:/,.])")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(slots=True)
|
|
72
|
+
class SmdrRecord:
|
|
73
|
+
"""One call, as read from a single SMDR line."""
|
|
74
|
+
|
|
75
|
+
raw: str
|
|
76
|
+
direction: str = DIRECTION_UNKNOWN
|
|
77
|
+
call_class: str | None = None
|
|
78
|
+
start: datetime | None = None
|
|
79
|
+
duration: int | None = None
|
|
80
|
+
ring_time: int | None = None
|
|
81
|
+
trunk: str | None = None
|
|
82
|
+
station: str | None = None
|
|
83
|
+
station_name: str | None = None
|
|
84
|
+
number: str | None = None
|
|
85
|
+
caller_name: str | None = None
|
|
86
|
+
cost: str | None = None
|
|
87
|
+
answered: bool = True
|
|
88
|
+
flags: list[str] = field(default_factory=list)
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def missed(self) -> bool:
|
|
92
|
+
"""An incoming call that nobody answered."""
|
|
93
|
+
return self.direction == DIRECTION_INCOMING and not self.answered
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def ended(self) -> datetime | None:
|
|
97
|
+
"""When the call ended: start plus ring and talk time."""
|
|
98
|
+
if self.start is None:
|
|
99
|
+
return None
|
|
100
|
+
return self.start + timedelta(seconds=(self.ring_time or 0) + (self.duration or 0))
|
|
101
|
+
|
|
102
|
+
def is_live(self, now: datetime, window: timedelta) -> bool:
|
|
103
|
+
"""True for a call that just finished, not one replayed from the phone system's store."""
|
|
104
|
+
ended = self.ended
|
|
105
|
+
return ended is None or now - ended <= window
|
|
106
|
+
|
|
107
|
+
def as_dict(self) -> dict[str, Any]:
|
|
108
|
+
"""JSON-safe dict for events and attributes."""
|
|
109
|
+
data = asdict(self)
|
|
110
|
+
data["start"] = self.start.isoformat() if self.start else None
|
|
111
|
+
data["missed"] = self.missed
|
|
112
|
+
return data
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def is_record_line(line: str) -> bool:
|
|
116
|
+
"""True for a line that looks like a call record, not a header or blank."""
|
|
117
|
+
text = line.strip()
|
|
118
|
+
if len(text) < 8:
|
|
119
|
+
return False
|
|
120
|
+
upper = text.upper()
|
|
121
|
+
if any(word in upper for word in _HEADER_WORDS):
|
|
122
|
+
return False
|
|
123
|
+
if any(upper.startswith(word) for word in _SUMMARY_WORDS):
|
|
124
|
+
return False
|
|
125
|
+
if set(text) <= set("-=_* "):
|
|
126
|
+
return False
|
|
127
|
+
# A call record always carries a clock time or a duration.
|
|
128
|
+
return bool(_RE_DURATION.search(text) or _RE_TIME.search(text))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _seconds(h: str | int, m: str | int, s: str | int = 0) -> int:
|
|
132
|
+
return int(h) * 3600 + int(m) * 60 + int(s)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def parse_line(
|
|
136
|
+
line: str,
|
|
137
|
+
*,
|
|
138
|
+
extensions: dict[str, str] | None = None,
|
|
139
|
+
phonebook: dict[str, str] | None = None,
|
|
140
|
+
now: datetime | None = None,
|
|
141
|
+
date_order: str = DATE_AUTO,
|
|
142
|
+
) -> SmdrRecord | None:
|
|
143
|
+
"""Parse one SMDR line. Returns None for headers, summaries and blanks."""
|
|
144
|
+
raw = line.rstrip("\r\n")
|
|
145
|
+
if not is_record_line(raw):
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
extensions = extensions or {}
|
|
149
|
+
phonebook = phonebook or {}
|
|
150
|
+
now = now or datetime.now()
|
|
151
|
+
rec = SmdrRecord(raw=raw)
|
|
152
|
+
work = raw
|
|
153
|
+
|
|
154
|
+
upper = work.upper()
|
|
155
|
+
for flag in _MISSED_FLAGS:
|
|
156
|
+
if flag in upper:
|
|
157
|
+
rec.flags.append(flag.replace(" ", "_").lower())
|
|
158
|
+
rec.answered = False
|
|
159
|
+
work = re.sub(re.escape(flag), " ", work, flags=re.IGNORECASE)
|
|
160
|
+
|
|
161
|
+
cost = _RE_COST.search(work)
|
|
162
|
+
if cost:
|
|
163
|
+
rec.cost = cost.group(0).replace(" ", "")
|
|
164
|
+
work = work[: cost.start()] + " " + work[cost.end() :]
|
|
165
|
+
|
|
166
|
+
# Duration (H:MM:SS) comes before any ring time (M:SS).
|
|
167
|
+
dur = _RE_DURATION.search(work)
|
|
168
|
+
if dur:
|
|
169
|
+
rec.duration = _seconds(*dur.groups())
|
|
170
|
+
work = work[: dur.start()] + " " + work[dur.end() :]
|
|
171
|
+
|
|
172
|
+
# Class code: first alphabetic token in the first two tokens.
|
|
173
|
+
tokens = work.split()
|
|
174
|
+
for tok in tokens[:2]:
|
|
175
|
+
if tok.upper() in _CLASS_DIRECTIONS:
|
|
176
|
+
rec.call_class = tok.upper()
|
|
177
|
+
rec.direction = _CLASS_DIRECTIONS[rec.call_class]
|
|
178
|
+
if rec.call_class in _TRANSFER_CLASSES:
|
|
179
|
+
rec.flags.append("transferred")
|
|
180
|
+
break
|
|
181
|
+
|
|
182
|
+
# Clock time and optional date.
|
|
183
|
+
tm = _RE_TIME.search(work)
|
|
184
|
+
call_time: time | None = None
|
|
185
|
+
if tm:
|
|
186
|
+
call_time = time(int(tm.group(1)), int(tm.group(2)))
|
|
187
|
+
work = work[: tm.start()] + " " + work[tm.end() :]
|
|
188
|
+
dt = _RE_DATE.search(work)
|
|
189
|
+
call_date: date | None = None
|
|
190
|
+
if dt:
|
|
191
|
+
call_date = _pick_date(int(dt.group(1)), int(dt.group(2)), dt.group(3), now, date_order)
|
|
192
|
+
if call_date is not None:
|
|
193
|
+
work = work[: dt.start()] + " " + work[dt.end() :]
|
|
194
|
+
if call_time is not None:
|
|
195
|
+
when = datetime.combine(call_date or now.date(), call_time, tzinfo=now.tzinfo)
|
|
196
|
+
if call_date is None and when > now + timedelta(minutes=5):
|
|
197
|
+
when -= timedelta(days=1) # call started before midnight
|
|
198
|
+
rec.start = when
|
|
199
|
+
|
|
200
|
+
# Ring time (M:SS), usually after the number on incoming calls.
|
|
201
|
+
ring = _RE_RING.search(work)
|
|
202
|
+
if ring:
|
|
203
|
+
rec.ring_time = _seconds(0, ring.group(1), ring.group(2))
|
|
204
|
+
work = work[: ring.start()] + " " + work[ring.end() :]
|
|
205
|
+
|
|
206
|
+
# External number: the longest long digit string.
|
|
207
|
+
numbers = sorted(_RE_NUMBER.findall(work), key=len, reverse=True)
|
|
208
|
+
if numbers:
|
|
209
|
+
rec.number = numbers[0]
|
|
210
|
+
work = work.replace(numbers[0], " ", 1)
|
|
211
|
+
|
|
212
|
+
# Station: a known extension number or name wins; otherwise the first
|
|
213
|
+
# short number that is not the trunk.
|
|
214
|
+
short = _RE_SHORT.findall(work)
|
|
215
|
+
for ext, name in extensions.items():
|
|
216
|
+
if ext in short:
|
|
217
|
+
rec.station, rec.station_name = ext, name
|
|
218
|
+
short.remove(ext)
|
|
219
|
+
break
|
|
220
|
+
if name and re.search(rf"(?<!\w){re.escape(name)}(?!\w)", work, re.IGNORECASE):
|
|
221
|
+
rec.station, rec.station_name = ext, name
|
|
222
|
+
break
|
|
223
|
+
trunks = [s for s in short if len(s) == 3 and s.startswith("0")]
|
|
224
|
+
if trunks:
|
|
225
|
+
rec.trunk = trunks[0]
|
|
226
|
+
short.remove(trunks[0])
|
|
227
|
+
# Sequence numbers (1-2 digits) and zero-padded counters are never
|
|
228
|
+
# extensions.
|
|
229
|
+
short = [s for s in short if len(s) >= 3 and not s.startswith("0")]
|
|
230
|
+
if rec.station is None and short:
|
|
231
|
+
rec.station = short[0]
|
|
232
|
+
rec.station_name = extensions.get(rec.station)
|
|
233
|
+
|
|
234
|
+
# Direction fallback when there is no class code.
|
|
235
|
+
if rec.direction == DIRECTION_UNKNOWN:
|
|
236
|
+
if rec.ring_time is not None or not rec.answered:
|
|
237
|
+
rec.direction = DIRECTION_INCOMING
|
|
238
|
+
elif rec.number:
|
|
239
|
+
rec.direction = DIRECTION_OUTGOING
|
|
240
|
+
elif rec.station:
|
|
241
|
+
rec.direction = DIRECTION_INTERNAL
|
|
242
|
+
|
|
243
|
+
if rec.number:
|
|
244
|
+
rec.caller_name = lookup_name(rec.number, phonebook)
|
|
245
|
+
|
|
246
|
+
return rec
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _make_date(year: int, month: int, day: int) -> date | None:
|
|
250
|
+
try:
|
|
251
|
+
return date(year, month, day)
|
|
252
|
+
except ValueError:
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _pick_date(
|
|
257
|
+
first: int, second: int, year_text: str | None, now: datetime, order: str
|
|
258
|
+
) -> date | None:
|
|
259
|
+
"""Read a day/month pair in the configured order.
|
|
260
|
+
|
|
261
|
+
``auto`` settles it when one number is over 12; otherwise it takes the
|
|
262
|
+
reading closest to now that isn't in the future, because a call record is
|
|
263
|
+
printed when the call ends. A date with no year that would be more than a
|
|
264
|
+
day ahead is from last year.
|
|
265
|
+
"""
|
|
266
|
+
if year_text:
|
|
267
|
+
years = [int(year_text) + (2000 if len(year_text) <= 2 else 0)]
|
|
268
|
+
else:
|
|
269
|
+
years = [now.year, now.year - 1]
|
|
270
|
+
if order == DATE_DMY:
|
|
271
|
+
pairs = [(first, second)]
|
|
272
|
+
elif order == DATE_MDY:
|
|
273
|
+
pairs = [(second, first)]
|
|
274
|
+
else:
|
|
275
|
+
pairs = [(first, second), (second, first)]
|
|
276
|
+
today = now.date()
|
|
277
|
+
best: date | None = None
|
|
278
|
+
for day, month in pairs:
|
|
279
|
+
for year in years:
|
|
280
|
+
candidate = _make_date(year, month, day)
|
|
281
|
+
if candidate is None or candidate > today + timedelta(days=1):
|
|
282
|
+
continue
|
|
283
|
+
if best is None or candidate > best:
|
|
284
|
+
best = candidate
|
|
285
|
+
break # the first year that fits is the right one for this order
|
|
286
|
+
return best
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def normalise_number(number: str) -> str:
|
|
290
|
+
"""Digits only, with +61 turned into a leading 0."""
|
|
291
|
+
digits = re.sub(r"[^\d]", "", number)
|
|
292
|
+
if number.strip().startswith("+61") or (digits.startswith("61") and len(digits) == 11):
|
|
293
|
+
digits = "0" + digits[2:]
|
|
294
|
+
return digits
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def lookup_name(number: str, phonebook: dict[str, str]) -> str | None:
|
|
298
|
+
"""Find a name for a number. Masked numbers (ending in X) match on the prefix."""
|
|
299
|
+
if not number:
|
|
300
|
+
return None
|
|
301
|
+
target = normalise_number(number.rstrip("Xx"))
|
|
302
|
+
masked = number.upper().endswith("X")
|
|
303
|
+
for book_number, name in phonebook.items():
|
|
304
|
+
candidate = normalise_number(book_number)
|
|
305
|
+
if candidate == target or (masked and target and candidate.startswith(target)):
|
|
306
|
+
return name
|
|
307
|
+
return None
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def parse_mapping(text: str) -> dict[str, str]:
|
|
311
|
+
"""Parse 'key: value' or 'key=value' lines (or comma separated) into a dict."""
|
|
312
|
+
result: dict[str, str] = {}
|
|
313
|
+
for part in re.split(r"[\n,;]+", text or ""):
|
|
314
|
+
if not part.strip():
|
|
315
|
+
continue
|
|
316
|
+
key, sep, value = _split_pair(part)
|
|
317
|
+
if sep and key:
|
|
318
|
+
result[key.replace(" ", "")] = value.strip()
|
|
319
|
+
return result
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _split_pair(part: str) -> tuple[str, str, str]:
|
|
323
|
+
match = re.match(r"\s*([^:=]+?)\s*([:=])\s*(.*)$", part)
|
|
324
|
+
if not match:
|
|
325
|
+
return "", "", ""
|
|
326
|
+
return match.group(1), match.group(2), match.group(3)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def format_mapping(mapping: dict[str, str]) -> str:
|
|
330
|
+
"""Inverse of parse_mapping, one pair per line."""
|
|
331
|
+
return "\n".join(f"{key}: {value}" for key, value in mapping.items())
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: aionecpbx
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async clients for NEC SL2100 and SV9100 call logs (SMDR) and FreePBX live calls (AMI)
|
|
5
|
+
Project-URL: Homepage, https://github.com/olliemaller/aionecpbx
|
|
6
|
+
Project-URL: Issues, https://github.com/olliemaller/aionecpbx/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/olliemaller/aionecpbx/blob/main/CHANGELOG.md
|
|
8
|
+
Author: Oliver Maller
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: NOTICE
|
|
12
|
+
Keywords: asterisk,asyncio,freepbx,home-assistant,nec,sl2100,smdr,sv9100
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Communications :: Telephony
|
|
22
|
+
Classifier: Topic :: Home Automation
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.12
|
|
25
|
+
Provides-Extra: lint
|
|
26
|
+
Requires-Dist: mypy>=1.13; extra == 'lint'
|
|
27
|
+
Requires-Dist: ruff>=0.8; extra == 'lint'
|
|
28
|
+
Provides-Extra: test
|
|
29
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
|
|
30
|
+
Requires-Dist: pytest-cov>=5; extra == 'test'
|
|
31
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# aionecpbx
|
|
35
|
+
|
|
36
|
+
Async Python clients for **NEC SL2100 and SV9100** phone systems, and for live calls through **FreePBX**.
|
|
37
|
+
|
|
38
|
+
- **`SmdrClient`** keeps a connection to the phone system's SMDR (call log) port open, reconnects by itself, and hands over each line.
|
|
39
|
+
- **`parse_line`** turns an SMDR line into an `SmdrRecord`: direction, start, ring and talk time, line, extension, number, and whether it was missed. It works on tokens rather than fixed columns, so the different 35-01 and 35-02 layouts read the same way, and it never raises.
|
|
40
|
+
- **`AmiClient`** follows calls through FreePBX's Asterisk Manager Interface as they ring, are answered and end, and turns do-not-disturb on and off per extension.
|
|
41
|
+
|
|
42
|
+
Standard library only. Python 3.12 or later. It powers the [NEC PBX integration for Home Assistant](https://github.com/olliemaller/ha-nec-pbx).
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install aionecpbx
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Call log (SMDR)
|
|
51
|
+
|
|
52
|
+
Turn SMDR on in the phone system first (PC Pro or WebPro):
|
|
53
|
+
|
|
54
|
+
| Program | Setting |
|
|
55
|
+
|---|---|
|
|
56
|
+
| 10-20, type 5 | SMDR output TCP port: `4001` on Australian systems |
|
|
57
|
+
| 35-01-01 | Output port: **LAN** |
|
|
58
|
+
| 35-02-08 | Print incoming calls: **on** (or you won't see incoming or missed calls) |
|
|
59
|
+
|
|
60
|
+
Only one program can hold the SMDR port at a time.
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import asyncio
|
|
64
|
+
from aionecpbx import SmdrClient, parse_line
|
|
65
|
+
|
|
66
|
+
def on_line(line: str) -> None:
|
|
67
|
+
record = parse_line(line, extensions={"103": "Kitchen"}, phonebook={"0491570156": "Alex"})
|
|
68
|
+
if record:
|
|
69
|
+
print(record.direction, record.station_name, record.number, record.caller_name, record.missed)
|
|
70
|
+
|
|
71
|
+
async def main() -> None:
|
|
72
|
+
client = SmdrClient("192.168.0.10", 4001, on_line)
|
|
73
|
+
client.start()
|
|
74
|
+
await asyncio.sleep(3600)
|
|
75
|
+
await client.stop()
|
|
76
|
+
|
|
77
|
+
asyncio.run(main())
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
A record is only written when a call **ends**. For calls as they ring, use FreePBX below.
|
|
81
|
+
|
|
82
|
+
## Live calls (FreePBX)
|
|
83
|
+
|
|
84
|
+
In FreePBX, **Settings > Asterisk Manager Users > Add Manager**: permit your address, and give it at least read `call` and `system`, and write `system` for do-not-disturb.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from aionecpbx import AmiClient, LiveCall
|
|
88
|
+
|
|
89
|
+
def on_change(call: LiveCall, what: str) -> None:
|
|
90
|
+
print(what, call.caller_number, call.caller_name, call.extension) # ringing / answered / ended
|
|
91
|
+
|
|
92
|
+
client = AmiClient("192.168.0.20", 5038, "homeassistant", "secret", on_change)
|
|
93
|
+
client.start()
|
|
94
|
+
...
|
|
95
|
+
await client.set_dnd("103", True)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
A rejected login stops the client rather than retrying, so it can't lock the manager user out. `async_test_login()` checks a login once.
|
|
99
|
+
|
|
100
|
+
## Command line
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
aionecpbx parse "IC 0001 10:00 001 00:01:00 103 0491570156 0:08"
|
|
104
|
+
aionecpbx listen 192.168.0.10 # print each call as JSON as it ends
|
|
105
|
+
aionecpbx ami 192.168.0.20 --username homeassistant --secret ...
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Development
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
pip install -e ".[test,lint]"
|
|
112
|
+
pytest --cov=aionecpbx
|
|
113
|
+
ruff check . && ruff format --check . && mypy
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Releases are automatic: bump `__version__` in `src/aionecpbx/__init__.py`, add a `CHANGELOG.md` section, and push to `main`.
|
|
117
|
+
|
|
118
|
+
## Licence
|
|
119
|
+
|
|
120
|
+
[MIT](LICENSE). See [NOTICE](NOTICE) for trademarks.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
aionecpbx/__init__.py,sha256=bS7-2syv38Y7G8MiEICdNm-XsZzi20d9Rl1ztuVUfEw,1594
|
|
2
|
+
aionecpbx/__main__.py,sha256=YSlQTSpJwFu_LG18mYEqkoDO7wNiKCAIOyN_D6UqyKw,3462
|
|
3
|
+
aionecpbx/ami.py,sha256=irXqWtM6SxDaGO3nVMukXjL6yVsIQxPqJhBvmj8gUbo,13192
|
|
4
|
+
aionecpbx/client.py,sha256=14EeWiwsyzkzXNE-YrwCKPaagnZlsTty94rPiDQtlVY,6371
|
|
5
|
+
aionecpbx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
aionecpbx/smdr.py,sha256=LADY8Clh4kEQ7_C6Aqik3QIOt-tOMpOAEc0oblPkYWY,11949
|
|
7
|
+
aionecpbx-0.1.0.dist-info/METADATA,sha256=tlxVSvSaqimNExZuLL4S-NXjoHHqR4hXdruDpn2L3XA,4426
|
|
8
|
+
aionecpbx-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
aionecpbx-0.1.0.dist-info/entry_points.txt,sha256=RQywKm4xpWLLfrL8LOTldeIFImWMnv1zg7NvGUM2sgI,54
|
|
10
|
+
aionecpbx-0.1.0.dist-info/licenses/LICENSE,sha256=cBE3G54yi5ZUkpTOtXA7jQ8xOGOxBHkEO_My-Y73A0Q,1353
|
|
11
|
+
aionecpbx-0.1.0.dist-info/licenses/NOTICE,sha256=7zkLvbNrfxdtOy-ravQpeeJcwYsbqOT9jZnP-BYNa4w,297
|
|
12
|
+
aionecpbx-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Oliver Maller
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
Portions are derived from these MIT-licensed projects:
|
|
26
|
+
|
|
27
|
+
- escea (https://github.com/snikch/escea), Copyright (c) 2026 Oliver Maller
|
|
28
|
+
- ha-escea (https://github.com/derekclapham/ha-escea), Copyright (c) 2026
|
|
29
|
+
Derek Clapham: the web page (timers and diagnostics) request formats
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
aionecpbx
|
|
2
|
+
Copyright (c) 2026 Oliver Maller. MIT licence (see LICENSE).
|
|
3
|
+
|
|
4
|
+
"NEC", "SL2100" and "SV9100" are trademarks of their owner and are used only to
|
|
5
|
+
describe compatibility. This project is not affiliated with or endorsed by NEC.
|
|
6
|
+
"Asterisk" and "FreePBX" are trademarks of Sangoma Technologies.
|