Asterisk Tips and Tricks: Dynamic Subroutines in AGI (Updated 09/09/08))

August 28, 2008

When I set out to develop a basic service provider Perl AGI framework for Asterisk three or four years ago, I wanted to design something that would make developing additional Perl AGI apps under this framework scalable and easy to do. One of the features I wanted to have in this framework was the ability to do a database dip on a particular incoming called number to see which service I needed to execute and then to dynamically execute that subroutine from the database servers results. I could switch services or point the number to a canceled operator message by simply doing an update to that telephone number’s record in the database - instantly re-provisioning the telephone number. In addition, the idea of not having to touch the base code for anything is always a plus.

The hurdle in doing something like this was how to dynamically execute a subroutine from the results of the database query which were dumped into a variable. Thanks to Brad Watkins, I now have an updated dynamic subroutine that does arguments.

This is a simple example of dynamic subroutine execution:

#!/usr/bin/perl -w   

use strict;
use warnings;

my %sub_hash = (”subtoexec”, \&subtoexec);

sub subtoexec {
  my ($arg1, $arg2) = @_;
  print $arg1.”\n”;
  print $arg2.”\n”;
};

sub dynamic_execute {
  my ($sub, @arg) = @_;
  &$sub(@arg);
}

dynamic_execute($sub_hash{”subtoexec”}, (”arg1″, “arg2″));

Tags: , , ,



Add to netvibes

Add to Technorati Favorites

Add to Google Reader or Homepage

Subscribe in Bloglines

Add to fwicki

Subscribe in NewsGator Online

Subscribe in Rojo

2 Responses

  1. So I’m wondering why you are going to the trouble (and obfuscation) of running ‘dynamic subroutines’ when a simple if-then-else would do the trick?

    I do something similar with a ’status’ field in my DID table that controls provisioned vs. ‘inactive but held’ vs. whatever. I return that value from the initial DB lookup and take action appropriately.

    As you correctly point out it would be difficult to pass parms. to the subs in your model unless you used the same parm. list for all of them.

  2. I’ve used Asterisk mainly in a service provider model and it’s been nice to upload code to the servers and simply add an include for the new code and leave the base code untouched.

    I’ve also found a way to do arguments and will be updating the post with some new code in just a few minutes.

    Thanks for the post!

Leave a Reply