basicami 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.
basicami/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ __version__ = "0.1.0"
2
+
3
+ from .basic_ami import BasicAMI
4
+ from .marker import Marker, MarkerTrace, parse_marker
5
+
6
+ __all__ = ["BasicAMI", "Marker", "MarkerTrace", "parse_marker"]
basicami/basic_ami.py ADDED
@@ -0,0 +1,232 @@
1
+ """AsyncIO-based Asterisk Manager Interface (AMI) client.
2
+
3
+ Follows the patterns of basicagi but for AMI over TCP.
4
+ """
5
+
6
+ import asyncio
7
+ import logging
8
+ import uuid
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class AMIError(Exception):
14
+ """AMI protocol error."""
15
+
16
+
17
+ class BasicAMI:
18
+ """AsyncIO AMI client.
19
+
20
+ Usage::
21
+
22
+ ami = await BasicAMI.connect("localhost", 5038, "admin", "secret")
23
+ resp = await ami.originate(
24
+ channel="Local/100@from_sbc-173",
25
+ application="Wait",
26
+ data="30",
27
+ )
28
+ events = await ami.get_events(timeout=1.0)
29
+ await ami.close()
30
+ """
31
+
32
+ def __init__(self):
33
+ self._reader: asyncio.StreamReader | None = None
34
+ self._writer: asyncio.StreamWriter | None = None
35
+ self._event_queue: asyncio.Queue[dict[str, str]] = asyncio.Queue()
36
+ self._pending: dict[str, asyncio.Future[dict[str, str]]] = {}
37
+ self._read_task: asyncio.Task | None = None
38
+ self._connected = False
39
+
40
+ @classmethod
41
+ async def connect(
42
+ cls,
43
+ host: str,
44
+ port: int,
45
+ username: str,
46
+ secret: str,
47
+ timeout: float = 15.0,
48
+ ) -> "BasicAMI":
49
+ """Connect to AMI, login, and start the background reader."""
50
+ ami = cls()
51
+ ami._reader, ami._writer = await asyncio.wait_for(
52
+ asyncio.open_connection(host, port), timeout=timeout
53
+ )
54
+
55
+ # Read AMI greeting line
56
+ greeting = await asyncio.wait_for(ami._reader.readline(), timeout=timeout)
57
+ logger.debug("AMI greeting: %s", greeting.decode().strip())
58
+
59
+ # Start background reader before login so we can receive the response
60
+ ami._read_task = asyncio.create_task(ami._read_loop())
61
+ ami._connected = True
62
+
63
+ # Login
64
+ resp = await ami.send_action(
65
+ {"Action": "Login", "Username": username, "Secret": secret}
66
+ )
67
+ if resp.get("Response") != "Success":
68
+ await ami.close()
69
+ raise AMIError(f"Login failed: {resp.get('Message', 'unknown')}")
70
+
71
+ logger.info("AMI connected and logged in to %s:%d", host, port)
72
+ return ami
73
+
74
+ async def send_action(
75
+ self, action: dict[str, str], timeout: float = 10.0
76
+ ) -> dict[str, str]:
77
+ """Send an AMI action and wait for the response."""
78
+ action_id = action.get("ActionID", str(uuid.uuid4()))
79
+ action["ActionID"] = action_id
80
+
81
+ # Create a future for the response
82
+ loop = asyncio.get_running_loop()
83
+ future: asyncio.Future[dict[str, str]] = loop.create_future()
84
+ self._pending[action_id] = future
85
+
86
+ # Serialize and send
87
+ lines = [f"{k}: {v}" for k, v in action.items()]
88
+ payload = "\r\n".join(lines) + "\r\n\r\n"
89
+ self._writer.write(payload.encode())
90
+ await self._writer.drain()
91
+
92
+ logger.debug("Sent action: %s", action.get("Action"))
93
+
94
+ try:
95
+ return await asyncio.wait_for(future, timeout=timeout)
96
+ finally:
97
+ self._pending.pop(action_id, None)
98
+
99
+ async def originate(
100
+ self,
101
+ channel: str,
102
+ context: str | None = None,
103
+ exten: str | None = None,
104
+ priority: str | None = None,
105
+ application: str | None = None,
106
+ data: str | None = None,
107
+ caller_id: str | None = None,
108
+ timeout: int | None = None,
109
+ variables: dict[str, str] | None = None,
110
+ async_: bool = True,
111
+ ) -> dict[str, str]:
112
+ """Send an Originate action."""
113
+ action: dict[str, str] = {
114
+ "Action": "Originate",
115
+ "Channel": channel,
116
+ }
117
+ if context:
118
+ action["Context"] = context
119
+ if exten:
120
+ action["Exten"] = exten
121
+ if priority:
122
+ action["Priority"] = priority
123
+ if application:
124
+ action["Application"] = application
125
+ if data:
126
+ action["Data"] = data
127
+ if caller_id:
128
+ action["CallerID"] = caller_id
129
+ if timeout:
130
+ action["Timeout"] = str(timeout * 1000) # seconds to ms
131
+ if async_:
132
+ action["Async"] = "true"
133
+ if variables:
134
+ action["Variable"] = ",".join(f"{k}={v}" for k, v in variables.items())
135
+
136
+ return await self.send_action(action)
137
+
138
+ async def get_events(
139
+ self, timeout: float = 0.1, max_events: int = 1000
140
+ ) -> list[dict[str, str]]:
141
+ """Drain buffered events, waiting briefly for new ones."""
142
+ events: list[dict[str, str]] = []
143
+
144
+ # Drain already-queued events
145
+ while not self._event_queue.empty() and len(events) < max_events:
146
+ events.append(self._event_queue.get_nowait())
147
+
148
+ # Wait briefly for more
149
+ try:
150
+ event = await asyncio.wait_for(self._event_queue.get(), timeout=timeout)
151
+ events.append(event)
152
+ # Drain any more that arrived
153
+ while not self._event_queue.empty() and len(events) < max_events:
154
+ events.append(self._event_queue.get_nowait())
155
+ except asyncio.TimeoutError:
156
+ pass
157
+
158
+ return events
159
+
160
+ async def close(self):
161
+ """Disconnect from AMI."""
162
+ self._connected = False
163
+ if self._read_task:
164
+ self._read_task.cancel()
165
+ try:
166
+ await self._read_task
167
+ except asyncio.CancelledError:
168
+ pass
169
+ if self._writer:
170
+ try:
171
+ self._writer.close()
172
+ await self._writer.wait_closed()
173
+ except Exception:
174
+ pass
175
+ logger.debug("AMI connection closed")
176
+
177
+ async def _read_loop(self):
178
+ """Background task: read AMI packets and dispatch."""
179
+ buf = b""
180
+ try:
181
+ while self._connected:
182
+ data = await self._reader.read(4096)
183
+ if not data:
184
+ logger.warning("AMI connection closed by server")
185
+ break
186
+ buf += data
187
+
188
+ # Split on double CRLF (AMI packet delimiter)
189
+ while b"\r\n\r\n" in buf:
190
+ packet, buf = buf.split(b"\r\n\r\n", 1)
191
+ self._dispatch_packet(packet.decode("utf-8", errors="replace"))
192
+
193
+ except asyncio.CancelledError:
194
+ raise
195
+ except Exception as e:
196
+ logger.error("AMI read loop error: %s", e)
197
+ finally:
198
+ # Cancel any pending futures
199
+ for action_id, future in self._pending.items():
200
+ if not future.done():
201
+ future.set_exception(
202
+ AMIError("Connection closed while waiting for response")
203
+ )
204
+
205
+ def _dispatch_packet(self, raw: str):
206
+ """Parse an AMI packet and route to response future or event queue."""
207
+ fields: dict[str, str] = {}
208
+ for line in raw.split("\r\n"):
209
+ if ":" in line:
210
+ key, _, value = line.partition(":")
211
+ fields[key.strip()] = value.strip()
212
+
213
+ if not fields:
214
+ return
215
+
216
+ # Check if this is a response to a pending action
217
+ action_id = fields.get("ActionID", "")
218
+ if action_id in self._pending:
219
+ future = self._pending[action_id]
220
+ if not future.done():
221
+ future.set_result(fields)
222
+ return
223
+
224
+ # Otherwise it's an event — queue it
225
+ if "Event" in fields:
226
+ try:
227
+ self._event_queue.put_nowait(fields)
228
+ except asyncio.QueueFull:
229
+ logger.warning(
230
+ "Event queue full, dropping event: %s",
231
+ fields.get("Event"),
232
+ )
basicami/marker.py ADDED
@@ -0,0 +1,106 @@
1
+ """Marker parsing for Asterisk Verbose/Log dialplan markers.
2
+
3
+ Ported from the Go implementation in pbx-test collector/parser.go.
4
+ """
5
+
6
+ import re
7
+ from dataclasses import dataclass, field
8
+
9
+ # Matches structured Verbose markers.
10
+ # Format: " -- MARKER_NAME: context key=value key=value"
11
+ _MARKER_RE = re.compile(r"(?:^\s*(?:--\s*)?)?([A-Z][A-Z0-9_]+):\s+(\S+)\s*(.*)$")
12
+
13
+ # Matches individual key=value pairs.
14
+ _KV_RE = re.compile(r"(\w+)=(\S+)")
15
+
16
+ # Strips ANSI escape sequences.
17
+ _ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
18
+
19
+
20
+ @dataclass
21
+ class Marker:
22
+ """A parsed Verbose marker from the Asterisk dialplan."""
23
+
24
+ name: str # e.g. "SBC_ENTER", "INBOUND_ROUTE"
25
+ context: str # e.g. tenant ID or flow context name
26
+ kv: dict[str, str] = field(default_factory=dict)
27
+ raw: str = ""
28
+ channel: str = ""
29
+ uniqueid: str = ""
30
+
31
+
32
+ def parse_marker(line: str) -> Marker | None:
33
+ """Parse a verbose line into a Marker, or return None if not recognized."""
34
+ line = _ANSI_RE.sub("", line)
35
+
36
+ m = _MARKER_RE.match(line)
37
+ if not m:
38
+ return None
39
+
40
+ kv = {}
41
+ kv_part = m.group(3)
42
+ if kv_part:
43
+ for kv_match in _KV_RE.finditer(kv_part):
44
+ kv[kv_match.group(1)] = kv_match.group(2)
45
+
46
+ return Marker(
47
+ name=m.group(1),
48
+ context=m.group(2),
49
+ kv=kv,
50
+ raw=line,
51
+ )
52
+
53
+
54
+ class MarkerTrace:
55
+ """Ordered collection of markers for a single test call."""
56
+
57
+ def __init__(self, test_id: str = "", caller_id: str = ""):
58
+ self.test_id = test_id
59
+ self.caller_id = caller_id
60
+ self.channel: str = ""
61
+ self.uniqueid: str = ""
62
+ self.linkedid: str = ""
63
+ self.markers: list[Marker] = []
64
+
65
+ def marker_names(self) -> list[str]:
66
+ """Return list of marker names in order."""
67
+ return [m.name for m in self.markers]
68
+
69
+ def has_marker(self, name: str) -> bool:
70
+ """Check if a marker name exists in the trace."""
71
+ return any(m.name == name for m in self.markers)
72
+
73
+ def get_marker(self, name: str) -> Marker | None:
74
+ """Return the first marker with the given name, or None."""
75
+ for m in self.markers:
76
+ if m.name == name:
77
+ return m
78
+ return None
79
+
80
+ def get_marker_value(self, marker_name: str, key: str) -> str | None:
81
+ """Return a key-value from the first marker with the given name."""
82
+ m = self.get_marker(marker_name)
83
+ if m is None:
84
+ return None
85
+ return m.kv.get(key)
86
+
87
+ def contains_ordered(self, names: list[str]) -> bool:
88
+ """Check if marker names appear in order (not necessarily adjacent)."""
89
+ if not names:
90
+ return True
91
+ idx = 0
92
+ for m in self.markers:
93
+ if m.name == names[idx]:
94
+ idx += 1
95
+ if idx == len(names):
96
+ return True
97
+ return False
98
+
99
+ def __str__(self) -> str:
100
+ lines = []
101
+ for i, m in enumerate(self.markers):
102
+ parts = [f" {i}: {m.name}: {m.context}"]
103
+ for k, v in m.kv.items():
104
+ parts.append(f" {k}={v}")
105
+ lines.append("".join(parts))
106
+ return "\n".join(lines)
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: basicami
3
+ Version: 0.1.0
4
+ Summary: AsyncIO-based Asterisk Manager Interface (AMI) client for Python
5
+ Author-email: Andrius Kairiukstis <k@andrius.mobi>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/andrius/asterisk-basicami
8
+ Project-URL: Repository, https://github.com/andrius/asterisk-basicami
9
+ Project-URL: Documentation, https://github.com/andrius/asterisk-basicami/blob/main/README.md
10
+ Project-URL: Bug Reports, https://github.com/andrius/asterisk-basicami/issues
11
+ Keywords: asterisk,ami,pbx,telephony,voip,asyncio
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Telecommunications Industry
15
+ Classifier: Topic :: Communications :: Internet Phone
16
+ Classifier: Topic :: Communications :: Telephony
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Operating System :: OS Independent
24
+ Classifier: Framework :: AsyncIO
25
+ Requires-Python: >=3.11
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Dynamic: license-file
29
+
30
+ # basicami
31
+
32
+ AsyncIO-based Asterisk Manager Interface (AMI) client for Python.
33
+
34
+ Companion to [basicagi](https://github.com/andrius/asterisk-basicagi).
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install basicami
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ import asyncio
46
+ from basicami import BasicAMI
47
+
48
+ async def main():
49
+ ami = await BasicAMI.connect("localhost", 5038, "admin", "secret")
50
+
51
+ # Send any AMI action
52
+ resp = await ami.send_action({"Action": "Ping"})
53
+ print(resp)
54
+
55
+ # Originate a call
56
+ resp = await ami.originate(
57
+ channel="Local/100@from-internal",
58
+ application="Wait",
59
+ data="30",
60
+ caller_id="Test <15550099999>",
61
+ timeout=30,
62
+ )
63
+
64
+ # Collect events
65
+ events = await ami.get_events(timeout=2.0)
66
+ for event in events:
67
+ print(event)
68
+
69
+ await ami.close()
70
+
71
+ asyncio.run(main())
72
+ ```
73
+
74
+ ## Marker Parsing
75
+
76
+ Includes a marker parser for Asterisk Verbose/Log markers used in PBX testing:
77
+
78
+ ```python
79
+ from basicami import parse_marker, MarkerTrace
80
+
81
+ marker = parse_marker("SBC_ENTER: 001D tenant=001D-dev-testing")
82
+ print(marker.name) # "SBC_ENTER"
83
+ print(marker.context) # "001D"
84
+ print(marker.kv) # {"tenant": "001D-dev-testing"}
85
+ ```
86
+
87
+ ## License
88
+
89
+ MIT
@@ -0,0 +1,8 @@
1
+ basicami/__init__.py,sha256=inLUybDEF6pWGeHdsULKogmdzWbk--pot0YKc43wzIk,174
2
+ basicami/basic_ami.py,sha256=Cu0utJGlfvFxB0dlNsbj-cpyEeRFvO2QkZ8tIW4oPxk,7655
3
+ basicami/marker.py,sha256=axUBJ_hkqul-xQUu8uIZxNK4MYH-Yyck53X6Tq6b_ZM,3162
4
+ basicami-0.1.0.dist-info/licenses/LICENSE,sha256=QJt4CycI4R_o_0_QBzzqfQ1urhx8TQpkF30AHKwSJnA,1076
5
+ basicami-0.1.0.dist-info/METADATA,sha256=D0UYklBKP_0EtlO7vqZpiVphfZYRjqDflmoUSwJ88jI,2507
6
+ basicami-0.1.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
7
+ basicami-0.1.0.dist-info/top_level.txt,sha256=F5_2CastfyA0zwPBKeNHhLGQ9Em2tGAxGPDS23J84Pg,9
8
+ basicami-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrius Kairiukstis
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.
@@ -0,0 +1 @@
1
+ basicami