It appears that you're encountering an issue where, after a successful call, when one of the parties hangs up, your AGI script doesn't continue executing the code following the Dial command. Specifically, you can't see any logs or perform any actions after the call ends. This is a common issue when handling calls in AGI scripts, and it stems from how Asterisk and AGI handle channel hangups.
Understanding the Issue
When you initiate a Dial command in your AGI script, and the call is established, control is transferred from your AGI script to the Dial application. If the caller or callee hangs up during the call, the channel associated with your AGI script is destroyed. As a result:
- AGI scripts cannot execute further commands after the channel is hung up.
- Any attempt to interact with the channel (e.g., read variables, execute commands) will fail.
- The script may terminate unexpectedly or throw exceptions.
In your logs, you can observe the following:
<SIP/7691310941-00000030>AGI Tx >> 200 result=-1
-- <SIP/7691310941-00000030>AGI Script AGI.py completed, returning 4
== Spawn extension (from-7691310941, s, 1) exited non-zero on 'SIP/7691310941-00000030'
== MixMonitor close filestream (mixed)
== End MixMonitor Recording SIP/7691310941-00000030
The line AGI Tx >> 200 result=-1 indicates that the AGI script encountered an error while executing a command after the hangup occurred. The script then completes and returns, preventing any code after the Dial command from executing.
Why It Happens
- Channel Hangup: When the channel is hung up, AGI scripts receive a hangup notification and can no longer interact with the channel.
- AGI Command Failures: After a hangup, any AGI commands that interact with the channel will fail, usually returning
-1.
- Script Termination: If not properly handled, the script may terminate immediately upon hangup.
Solutions
To resolve this issue, you'll need to adjust your AGI script and/or dial plan to handle post-call actions even after a hangup. Here are some approaches:
1. Use the 'h' Extension in the Dial Plan
The 'h' extension in Asterisk is executed when a channel is hung up. You can define the 'h' extension in your dial plan and perform any post-call actions there, including logging and clean-up.
Example Dial Plan:
[from-7691310941]
exten => s,1,AGI(AGI.py)
exten => h,1,AGI(AGI_post_call.py)
In this case, AGI_post_call.py is a separate AGI script that handles post-call activities.
2. Use DeadAGI Instead of AGI
DeadAGI is designed to work on channels that have been hung up. It allows you to execute AGI commands even after the channel is dead.
Note: Starting from Asterisk 1.6, DeadAGI behaves the same as AGI, but in earlier versions, DeadAGI was necessary for post-hangup operations.
Example Dial Plan:
[from-7691310941]
exten => s,1,AGI(AGI.py)
exten => h,1,DeadAGI(AGI.py,post_call)
In your script, detect the context (e.g., normal call flow or post-call) based on arguments or environment variables.
3. Handle Hangup Exceptions in Your AGI Script
Modify your AGI script to catch hangup exceptions and perform necessary clean-up or logging.
Example Python AGI Script Adjustment:
import sys
import signal
class HangupHandler(Exception):
pass
def signal_handler(signum, frame):
raise HangupHandler("Hangup signal received")
signal.signal(signal.SIGHUP, signal_handler)
def handle_direct_transfer(self, ivr):
try:
# Your existing code...
# Dial the number
self.agi.exec_command('Dial', f'SIP/{destination_number}@{self.dialed_number},30,m,g')
# Code after Dial...
# May not execute if channel is hung up
except HangupHandler:
self.custom_log("Hangup detected. Performing post-call actions.")
# Perform your logging and clean-up here
# Use 'HANGUPCAUSE' and other variables as needed
except Exception as e:
self.custom_log(f"Error transferring call: {e}", level=logging.ERROR)
# Handle other exceptions
Explanation:
- Signal Handler: By setting up a signal handler for
SIGHUP, you can capture the hangup event.
- Hangup Exception: Raising a custom exception allows you to handle the hangup gracefully.
- Post-Call Actions: Perform necessary actions within the
except HangupHandler block.
4. Check Return Values and Handle AGI Command Failures
After each AGI command, check the return value. If it's -1, it may indicate a hangup.
Example Adjustment:
call_result = self.agi.exec_command('Dial', f'SIP/{destination_number}@{self.dialed_number},30,m,g')
if call_result == -1:
self.custom_log("Channel hung up during Dial.")
# Perform post-call actions
else:
# Continue normally
5. Use Async AGI (ARI in Newer Asterisk Versions)
Asynchronous AGI allows your script to continue running independently of the channel state.
Note: This requires more advanced setup and is suited for complex applications.
Recommendation
Given the context of your application, I recommend using a combination of these solutions:
-
Implement a Hangup Handler in Your AGI Script:
- Allows you to catch the hangup event within your script.
- Facilitates post-call logging and clean-up.
- Minimal changes to your existing code.
-
Utilize the 'h' Extension for Post-Call Actions:
- Offloads post-call processing to the dial plan.
- Ensures that actions are taken regardless of how the call was terminated.
- Keeps your AGI script focused on call handling, while the 'h' extension handles clean-up.
Example Implementation
Dial Plan:
[from-7691310941]
exten => s,1,AGI(AGI.py)
same => n,Hangup()
exten => h,1,AGI(AGI_post_call.py)
AGI.py (Main AGI Script):
def handle_direct_transfer(self, ivr):
try:
# Your existing code up to Dial command
self.agi.exec_command('Dial', f'SIP/{destination_number}@{self.dialed_number},30,m,g')
# Since the AGI script may not continue after Dial, move post-call actions elsewhere
except Exception as e:
self.custom_log(f"Error transferring call: {e}", level=logging.ERROR)
# Handle exceptions as needed
AGI_post_call.py (Post-Call AGI Script):
def handle_post_call(self):
try:
# Retrieve variables
dialstatus = self.agi.get_variable('DIALSTATUS')
hangupcause = int(self.agi.get_variable('HANGUPCAUSE') or 0)
call_start_time = self.agi.get_variable('call_start_time')
recording_filename = self.agi.get_variable('recording_filename')
# Calculate call duration
call_end_time = time.time()
call_duration = int(call_end_time - float(call_start_time))
# Log call details
self.send_call_log(
line=self.agi.get_variable('line'),
call_duration=call_duration,
recording_filename=recording_filename
)
self.custom_log(f"DIALSTATUS: {dialstatus}, HANGUPCAUSE: {hangupcause}")
except Exception as e:
self.custom_log(f"Error in post-call handling: {e}", level=logging.ERROR)
Notes:
- Use Channel Variables: Before the Dial command, store necessary variables using
self.agi.set_variable(...) so they can be retrieved in the post-call script.
- Separation of Concerns: The main AGI script handles the call flow, while the post-call script handles logging and clean-up.
- Robustness: This approach ensures that post-call actions are executed regardless of how the call ends.
Conclusion
Your current issue arises because the AGI script cannot continue executing after a channel hangup. By adjusting your script to handle hangup events or by moving post-call actions to the dial plan's 'h' extension, you can ensure that logging and other necessary actions are performed even after the call ends. This will provide you with the visibility and control you need over the call process.
Feel free to adjust the examples provided to fit your specific application, and don't hesitate to ask if you need further assistance.