34,79 €
Asterisk is the leading Open Source Telephony application and PBX software solution. It represents an effective, easy-to-administer, and accessible platform for running enterprise telephony requirements. The real world, however, offers numerous hurdles when running Asterisk in the commercial environment including call routing, resilience, or integrating Asterisk with other systems. This book will show you some of the ways to overcome these problems.
As the follow-up to Packt's highly successful 2005 title Building Telephony Systems with Asterisk, this book presents the collected wisdom of Asterisk Professionals in the commercial environment.
Aimed at Administrators and Asterisk Consultants who are comfortable with the basics of Asterisk operation and installation, this book covers numerous hands-on topics such as Call Routing, Network Considerations, Scalability, and Resilience ñ all the while providing practical solutions and suggestions. It also covers more business-related areas like Billing Solutions and a Winning Sales Technique. Even if your interest or experience with Asterisk is lower level, this book will provide a deeper understanding of how Asterisk operates in the real world.
Asterisk is deployed across countless enterprises globally. Running on Linux, it has constantly demonstrated its resilience, stability, and scalability and is now the advanced communication solution of choice to many organizations and consultants.
With a foreword from Mark Spencer, the man behind Asterisk, this book presents the accumulated wisdom of three leading Asterisk Consultants and shows the reader how to get the most out of Asterisk in the commercial environment. Over the course of eleven chapters, this book introduces the reader to topics as diverse as Advanced Dial Plans, Network Considerations, and Call Routing, through to Localization, DAHDI, Speech Technology, and Working with a GUI. The book also covers the more nebulous aspects of being an Asterisk professional such as evaluating customer requirements and pitching for contracts.
This book represents the wisdom and thoughts of front line consultants. The knowledge they impart will prove informative, thought provoking and be of lasting interest to Asterisk professionals.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 401
Veröffentlichungsjahr: 2009
Copyright © 2009 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2009
Production Reference: 1030809
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847194-38-1
www.packtpub.com
Cover Image by Vinayak Chittar (<[email protected]>)
Authors
Colman Carpenter
David Duffett
Nik Middleton
Ian Plain
Reviewers
Ian Plain
Jared Smith
Philippe Lindheimer
Acquisition Editor
James Lumsden
Technical Editors
Gagandeep Singh
Charumathi Sankaran
Indexer
Rekha Nair
Editorial Team Leader
Gagandeep Singh
Project Team Leader
Lata Basantani
Project Coordinator
Neelkanth Mehta
Proofreader
Laura Booth
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Watching Asterisk move from being a personal coding project to a community of tens of thousands of programmers and millions of users has been quite the ride so far! Asterisk is only now hitting its prime, and there are so many more things that creative people are going to do with the code. The growth of the project over the years has stunned and pleased me, and it's amazing that well-written and comprehensive books like this now exist to help more advanced users navigate the waters of larger and more complex Asterisk installations. Asterisk installations are now huge, both in numbers of locations and the unimaginably large size of many of those locations—thousands or tens of thousands of users! Asterisk implementations are rarely limited by the capability of the software but more often by not knowing how to utilize it. Books like this play an important role in getting the experience of those who have already done in the hands of those who want to do.
Hopefully the knowledge here allows you to continue your adventure with Asterisk, moving from the basics of PBX construction to having the ability to quickly implement advanced call logic processes and work with the more exotic telephony and VoIP interfaces. The motto of "There's more than one way to do it!" is almost always true with Asterisk—this book seems to contain an excellent cross-section of at least one of those ways to do "it" (whatever "it" happens to be for your application) and you'll quickly think of many other ways once you've mastered the methods shown.
The authors here have really shown some excellent detailed explanations of how to use Asterisk, and I hope this provides the incentive for you, the reader, to experiment in more wide-ranging ways with Asterisk once you've understood the basics. Most of the Asterisk community has learned with hands-on experimentation, and it's great to see more encouragement of this type of learning as is contained in these pages. Kudos to the authors, especially David Duffett, who has been involved with Asterisk for so long and has taught so many people their first dialplan routines (and hopefully has left them uninjured from his famous habit of throwing candy at people who give correct answers in class or in his talks).
Soon you'll be doing least-cost-routing, integrating your instant messenger system with your mobile phone calls, controlling robots with voice commands via your phone, or dreaming up a new company based on some voice-based service that nobody has tapped into yet. And the best thing about Asterisk is that it remains open source—if you come up with a feature or enhancement that you think must be in Asterisk, then the good news is that it can be! Become a member of the Asterisk community, and your contributed code could be included. We all anxiously await your book, your product, or just your involvement with the Asterisk community.
Mark Spencer
Chairman and CTO of Digium
Colman Carpenter is the MD of Voicespan, a Kent-based company that offers Asterisk-based systems to the SME market across the UK. He is an IT professional of over 20 years standing, with experience in diverse areas such as IBM mid-range software development, Lotus Notes and Domino consultancy, Data Management, E-marketing consultancy, IT Management, Project Management, Wordpress Website Design, and lately, Asterisk consultancy. He is a qualified PRINCE2 practitioner.
Voicespan (http://www.voicespan.co.uk) offers Asterisk-based systems as the cornerstone of a holistic VoIP-telephony service for SMEs. They offer companies a one-stop shop for implementing a VoIP-capable system, encompassing Asterisk-based systems, endpoints, trunks, telephony interfaces and network equipment, and the consultancy necessary to bring it all together into a coherent whole. This is his first book.
I would like to thank my wife, Hazel, and daughters, Caiti and Fay, for their support during the writing of this book. At times it seemed like you believed more than I in my ability to do so!
David Duffett delivers Asterisk training and consultancy around the world through his own company (TeleSpeak Limited, www.telespeak.co.uk), in addition to designing and delivering training for a number of companies, including Digium, Inc.
A keen Asterisk enthusiast, David also enjoys podcasting, radio presenting, and teaching public-speaking skills. He is a Chartered Engineer with experience in fields including Air Traffic Control communications, Wireless Local Loop, Mobile Networks, VoIP, and Asterisk. David has been in the telecoms sector for nearly 20 years and has had a number of computer telephony, VoIP, and Asterisk articles published through various industry publications and web sites.
Nik Middleton has been in wide-area communications since the mid-eighties. He spent most of the nineties working in the US, where he developed a shareware Microsoft mail to SMTP/POP3 connector that sold some 287,000 copies. He spent six years working for DuPont in VA, developing remote monitoring systems for their global Lycra business. In late 2000, he returned to the UK where he held various senior positions in British Telecom, LogicaCMG, and Computer Science Corp.
In 2005, tired of working in London, he set up his own company (Noble Solutions) providing VoIP solutions in rural Devon, where he now lives with his wife Georgina and three children, Mathew, Vicky, and Isabel. A keen amateur pilot, his favorite place when not in the office is flying over the beautiful Devon countryside.
Ian Plain has worked in the telecoms industry since 1981 and has designed some of the largest PBX networks in the UK. Since the late 1990s, he has been involved with VoIP initially for links between systems, and with IP PBX systems since 1999. Since 2003, he has been running a telecoms consultancy based near Bath in the UK, working primarily on high-availability Asterisk-based solutions for corporate customers.
Ian Plain: Please see the entry in About the Authors.
Jared Smith is the Training Manager for Digium, Inc. As a long time Asterisk user, contributor, and evangelist, he has spent the last several years helping the Asterisk community. Jared is a dynamic and knowledgeable instructor with several years of experience in leading various Asterisk training classes.
He is also co-author of Asterisk: The Future of Telephony, O'Reilly Media and regularly writes other Asterisk documentation as well.
Jared holds a Bachelors of Science degree in Computer Engineering from the Utah State University and currently lives in Virginia with his wife and two children.
Philippe Lindheimer is the project leader and primary developer of FreePBX and serves as the Open Source Community Director at Bandwidth.com, the corporate sponsor of the FreePBX project (the most widely deployed Asterisk-based PBX/GUI open-source application in the world). He cofounded and runs the Open Telephony Training Seminar providing FreePBX/Asterisk technical and marketing training to resellers and end users. Originally with Hewlett Packard, he has been in the engineering industry for over two decades, working on a range of technical consulting roles with many Fortune 500 Companies.
He has a BS (Hons) in EE/CS from the University of Colorado, Boulder. He now lives in the Seattle, WA area.
This book is a sequel to Building Telephony Systems with Asterisk, which started you on a journey to the summit of Asterisk knowledge, taking you from base camp to camp two, from being a complete Asterisk newbie to a competent telephony system builder and manager. Now it's time to push to the top, to take your telephony knowledge to a point where you can build high-performance, resilient, and professional PBXs using the most popular open source telephony software in the world—Asterisk.
In that book, the focus was very much on installing and configuring Asterisk for a number of common scenarios, including both home and office use. This it achieved admirably, so you may now wonder why another book is needed. Well, there are three main reasons for writing this book. Firstly, Asterisk is such a highly-capable and configurable telephony engine that the 150-odd pages in the book necessarily had to exclude discussion of some of the more advanced features, which we now have the opportunity to explore. Secondly, Asterisk is invariably implemented as part of an IP network, and further examination of network considerations is warranted. Finally, like all popular open source software, Asterisk is constantly being updated, and while this book still assumes the version 1.4 of Asterisk is in use, we do point out any differences in version 1.6 where relevant, such as the change from Zaptel to DAHDI.
Therefore, the goal of this book is to give you enough knowledge to build and install a telephony system with Asterisk at its core, which will stand comparison with the market-leading commercial IP-enabled systems. Whether you are building such a system as a result of an internal company requirement, or you plan to offer it as an element of a commercial package to customers, this book will take you through all the areas that require consideration. On reading this book you will also be in a position to understand the real-life issues you are likely to experience when deploying such a system, both technical and otherwise.
By its very nature, Asterisk demands that much of the focus of this book be on the technical aspects of building your professional system. However, as with most IT implementations, success will also rely on "soft" issues such as managing expectations, understanding and meeting the customer's particular needs, and ensuring delivery is on time and up to the budget. Hence, where appropriate, we make mention of the non-technical aspects that may make a difference to your deployment.
To achieve our goal, this book will build on knowledge already gained by reinforcing that learning and adding extra skills covering:
If you have not already done so, it is recommended that you read Building Telephony Systems with Asterisk, or achieve a good degree of competence in building basic Asterisk PBXs through other means. These could include commercial training courses (see www.digium.com/en/training for further details) or openly available internet resources such as the excellent VoIP wiki at http://www.voip-info.org.
While most people with a day-to-day exposure to Asterisk systems should stand to gain much from this book, it has been written in the expectation that you will possess the following Asterisk skills and experience, ideally gained through text file configuration:
Once equipped with this knowledge you stand to gain the maximum from the topics covered in this book, enabling you to build professional Asterisk systems to be deployed internally, or to form the cornerstone of a commercial offering.
In this book you will, hopefully, learn many new things. At its conclusion you will have the knowledge to build and successfully implement systems that combine great performance, resilience and stability. In order to do so, we will mainly consider "pure" Asterisk systems that require a deep understanding of the dialplan and configuration files without the safety-net of a GUI in between. Think of it as learning to become a great car mechanic. You can certainly be a good mechanic earning a good living by learning how to use a laptop plugged into an engine management system. But if you want to take that extra step to being a true master of the trade then you need to understand at a very deep level just how the internal combustion engine works. So it is with Asterisk. It is perfectly feasible to put very good solutions together using GUI-based systems such as the Digium-owned Switchvox, Trixbox (formerly Asterisk@Home) or PBX in a Flash, but to construct the best systems you will need to understand what is happening "under the hood" so that you can tweak them appropriately to achieve or exceed the customers' expectations.
One advantage of eschewing the GUI approach is a potential increase in performance and scalability through the use of a highly-optimized dialplan and a reduction in applications running on the server. However, there are many situations where a GUI is at least as appropriate, particularly if the customer wishes to carry out day-to-day management tasks. Therefore, in Chapter 12 we look at the implications of choosing a GUI-based solution over a "vanilla" system.
To follow the "trusted network" of Asterisk developers please visit: www.asteriskpro.co.uk
As a result of reading this book, you can expect to build on existing knowledge and gain new skills. Each chapter covers a particular topic, but throughout there is a focus on building an Asterisk system that can form the cornerstone of a serious commercial product, capable of matching or even exceeding the performance of well-known licensed products.
Chapter 1 talks about dialplan techniques including modular implementations by using macros, contexts, and so on to both refine the dialplan and improve the security of the system. It also discusses the use of the devstate() function.
Chapter 2 discusses customer network requirements and offers some good advice about potential issues within the customer network and how to resolve them, including the use of VLANs and Quality of Service.
Chapter 3 looks at routing in general, including Least Cost Routing (local, national, and international GSM gateways), fall-back routing, alternate routing, and so on. ENUM and DUNDi are also explained within this context.
Chapter 4 considers call center requirements, including queues, agents, call distribution strategies, performance monitoring and call recording issues. An Asterisk-based call center solution, VICIDIAL, is also discussed in some detail.
Chapter 5 introduces speech technology in the form of ASR, TTS, and SVI; followed by implementation advice and examples. Both Lumenvox and Cepstral packages are explored in detail.
Chapter 6 looks at methods that can be used to implement call accounting and billing solutions for Asterisk. In particular, Asterisk-stat and A2Billing are explored.
Chapter 7 discusses resilience and stability, giving you a guide to implementing highly-available Asterisk solutions for mission-critical applications. Use of failover and load-balancing techniques are explored.
Chapter 8 explores the comprehensive localization options within Asterisk, and also suggests some easily deployed security measures.
Chapter 9 considers interfaces with traditional analogue and digital telephony, giving more in-depth explanations of Libpri and DAHDI (formerly Zaptel), and discussing implementation considerations.
Chapter 10 tackles the good and bad points of using wireless technologies with Asterisk, covering Wi-Fi, dual-mode and DECT handsets. Some suggestions on routing via cell/mobile networks are also offered.
Chapter 11 looks at the good and bad points of Asterisk Graphical User Interfaces (GUIs), focusing on one of the most popular incarnations, FreePBX.
In Appendix A we also explore some of the softer skills required when selling Asterisk-based solutions, suggesting some sales strategies that can help you in a commercial environment.
In Appendix B you will find information you might want to include in sample emails when pitching.
In Appendix C you will find a sample appointment sheet which can be used as a template.
So now our campsite has been packed away and it is time for the next part of our journey to begin, for those first purposeful steps to be taken towards the summit. We will start in Chapter 1 by looking at the heart of any Asterisk system, the dialplan. You will already have significant knowledge in this area, but we are about to show you some of the techniques that are used in systems with thousands of extensions that handle many tens of thousands of calls per day. Without these techniques, a dialplan can become an unholy mess as system size increases. However, using these techniques will ensure that complexity is avoided and performance is maintained.
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "clicking the Next button moves you to the next screen".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an email to <[email protected]>, and mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Visit http://www.packtpub.com/files/code/4381_Code.zip to directly download the example code.
The downloadable files contain instructions on how to use them.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]>with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]>if you are having a problem with any aspect of the book, and we will do our best to address it.
The dialplan is the routing core of an Asterisk server. Its sole role is to look at what is dialed, and route the call to its destination. This is the core of any telephony system and Asterisk is no different.
The dialplan is made up of three elements—extensions, contexts, and priorities. An extension is number or pattern that the dialed number is to be matched against and a context is a collection of extensions (and possibly other included contexts too). Each extension will have one or more priorities, each of which appear on a separate line, and the priority sequence always starts with the priority "1".
If you have read Building Telephony Systems with Asterisk, you will know how to use extensions, priorities, contexts, and included contexts to handle incoming and outgoing calls as well as to set up features such as:
In this chapter, we will build on this knowledge by looking at:
We will then use this knowledge to provide examples of:
The dialplan is primarily defined in the extensions.conf file. This can also include additional files that are added into it using the #include directive. For instance, systems using the FreePBX GUI will have extensions_additional.conf, extensions_custom.conf, and extensions_override_freepbx.conf as standard files, which have been added using #include into the extensions.conf file. We must also remain aware of files such as the features.conf file, as they also include numbers that can be dialed such as codes for Pickup and Call Parking, and so form part of the dialplan.
A list of standard and optional Asterisk configuration files can be found at http://www.voip-info.org/wiki/view/Asterisk+config+files.
Being familiar with Asterisk, you will have a good working understanding of extensions and contexts already. They are, of course, the very heartbeat of Asterisk, and as such they are probably subject to the most change from version to version, as Asterisk evolves to cater for new hardware, software, and more complex working practices. So let's have a quick review of extensions and contexts, pointing out significant changes in versions 1.4 and 1.6, before we proceed to the more advanced techniques and uses.
Within the dialplan, matching can be either direct or partial against a pattern. Normally in a PBX, these patterns are numeric. But with Asterisk, they can also be alphanumeric or even just alpha. For example 2000, DID01234123456, and Main_number are all valid extensions. As very few phones contain alphabetic keys, the last two are typically only used for incoming DID channels. For the majority of this chapter, we will stick to numeric patterns.
Let's start to explore pattern matching by looking at an extremely simple dialplan:
In this dialplan, when a user with a context of context_1 dials 123, they will hear 999 and their caller ID will be read back to them.
Now let's look at a slightly more complex context:
You might expect that 123 would match against the _1X. extension, as that appears first in the context. However, the way Asterisk orders the dialplan when loading means that exact matches are checked for before pattern matches. Hence if you dial 123, it matches against the 123 pattern first and not the _1X. pattern. This pattern would only route the call if an exact match did not exist in the context.
It is sensible not to use the pattern _. as a catch-all pattern, as this will catch the Asterisk special extensions like i, t, h as well. It is far better to use the _X pattern.
Once understood, pattern matching is pretty straightforward and does what we expect. However, if you introduce included contexts into the mix, things may work in a way you did not expect and the order needs to be thought through carefully. In particular, it's crucial to understand that Asterisk only checks included contexts after checking for exact matches and pattern matches in the local context. The following example illustrates this:
The above dialplan is sorted internally by Asterisk shown as follows, and you can see that though the included contexts are at the top and in the middle, the local context is read first, then the included contexts are read in the order that they were added. Hence, in this case, a dial string of 122 would be matched by the _1X. pattern before the included contexts are searched.
If you have a catch-all pattern in your dialplan, consider putting it into a separate context. You can then use the include directive to append that context to the end of the active context, thus ensuring that all of the other pattern matching is attempted first.
One of the most powerful tools you will use on the Asterisk command line is dialplan show <exten>@<context>. For example:
This will show you the matching order that Asterisk will use for the given extension in the specified context, and if there are matches in any included contexts, those contexts will be explicitly identified.
Finally, in a context you may have a switch statement, which includes the dialplan of an external system into the local dialplan. In essence, it's an include for remote systems. Though typing dialplan show will always show the switch statement at the bottom, the defined context on the remote system is searched after the local context on your system and before any local included contexts! So again, you have to be very careful as to what is the context on the remote system as this will be searched before your included contexts.
The syntax of the switch state is as follows:
The user and key are defined in the called server's iax.conf file, and the context is, of course, in the server's dialplan.
In our examples so far we could have achieved the desired results very easily without the use of multiple contexts. The simple functionality we have looked at could be carried out in a single, all-encompassing context. In practice, this approach could be applicable for systems with a very limited number of users and trunks, and with very restricted functionality, as there may not be a need to restrict the calling habits of a subset of users.
Use of contexts becomes desirable when we need to offer different options to different users. This is likely to be most applicable in medium and large companies, where you may have "users" ranging from the CEO down to an emergency phone in a lift. However, it can also be the case in smaller companies, where you might want to restrict home workers from making international calls for instance. When you get many different types of users, writing a distinct dialplan for each becomes problematic. The sheer size and complexity of the dialplan will make code management very complicated.
To simplify things, we first need to think about what makes the dialplan for each extension different. Then we need to think about what remains the same for each extension, as this needs to be made to work as well. What we often find is that most of these differences can be stored and called in two main ways:
We will come to variables shortly, but the grouping of extensions into contexts allows us to separate concise and distinct functions from each other. In doing so, we can control very tightly which contexts are used in each scenario, and also implement one "master" copy of each distinct function, aiding maintenance of the code.
To illustrate, let's expand our context a bit and use call barring as an example. We will initially have three levels for this example— local, national, and international.
These are defined as follows:
This is a simplified example, and uses the UK format of dial prefixes.
We have in this example three contexts—local_num, national_num and international_num. These would correspond to the levels of access we have decided on for our users. For example, an executive phone would be allowed access to all numbers whereas a phone on the shop floor may only be allowed access to local numbers.
We will create the three contexts shown as follows. All we are doing in our example is reading back 1, 2, or 3 to indicate the pattern that has been matched followed by the number dialed ${EXTEN}.
For each context we could write an ordered list to cover all patterns, but it is much neater to create a master context for each user. For example:
Therefore, in the previous example, a user with the national context can dial a normal national number, but not an international number. A user with the international context has the ability to dial both numbers.
This is a pretty simple example with just three level of access, but the modular nature due to the use of contexts allows us to expand it very quickly and easily. For example, we have a user 1000 (our CEO) and he can dial internationally. We also have 1098 and 1099, which are users on the shop floor, and can dial reception and the emergency services.
In this example, we give our CEO a context of [supauser],while the shop floor has a context of [emergencyuser].
The [supauser] context has to be able to dial everything, so it looks like this:
The shop floor just has the following context:
As you can see, we can mix and match these contexts to cover many different types of extensions. Although you may be asking, "Will this really save me time?" well, let's look at two examples. Firstly, our supplier reduces the cost of UK 0870 numbers to free in the evenings as has happened in the UK with BT(British Telecom). Secondly, we also want the shop floor phone (1099) to be able to dial extensions and toll free calls, but not change the dialplan for 1098.
We will deal with the simplest of these extensions (1099) first. All we need to do is change the context associated with this user to a new context called [freeuser]:
This is a fast and easy change, which will have no effect on other shop floor users.
And to the change to 0870 numbers, this once again can be put into effect very simply. The only change is that evening and weekend calls are now free. Therefore, we could put it into a [free] context. Although, it isn't always free. It is free only at weekends which would not be suitable. Hence, for this we use the GotoIfTime application, which sets the context, extension, and priority in the channel based on the system time, day, date, and month supplied by the OS.
By adding the following to the free context, users can now dial 0870 numbers at the defined times.
In this case, we have made a change for all users who also have a context allowing both local and free calls (as their context includes the free context).
The GotoIfTime() application can introduce some powerful functionality into your dialplan if used properly. An example that follows is for a support company where calls are routed to the call centre or staff member on call at a specific time. The customer had centers round the globe and we routed the calls to whichever center was open at that time of day.
This can be expanded to include public holidays, if required. It can be possible to handle many years' public holidays in one line. For example, between the years 2009 and 2016, the UK's summer public holiday falls on the dates between the 25th and 31st of August and is always a Monday. Therefore, we have something like this:
This will catch all UK summer public holidays, and as there are no other Mondays in August clashing with these dates, it's a set-and-forget for many years (just don't forget to change it after 2016!). The same goes for the majority of other public holidays except for Easter.
For these variable dates, we can resort back to the internal database to store the details and then use the GotoIf() application to check if the date is a holiday.
Variables are key to making the dialplan and system work in a manner that a user expects. The user would expect the system to know everything they have set on their extension, and not have to enter codes or dial special access numbers.
There are a number of places in which variables can be stored including the dialplan, sip.conf, iax.conf, chan_DAHDI.conf (in version1.6), and the Asterisk database (AstDB). For example, if we have a number of static dial strings we wish to store for each type of call and carrier we use, and then use them in a number of sections, the [globals] section of the extensions.conf file is the obvious place to declare them. If we wish to set a variable when a call is initiated from a SIP device, external caller ID or account codes are a good example, the setvar command in the sip.conf file is ideal for that purpose. Just remember that it won't work for calls sent to that device just when the calls are made. Finally, the AstDB is great for variables that are more transient in nature, such as call counts.
On occasion, when using complicated dialplans you may wish for a variable's value to be kept as the call progresses. This is achieved by adding a _ [underscore] or a __ [double underscore] before the variable name.
A single _ will cause that variable to be inherited into the channel that started from the original channel, for example:
If you want the variable to be inherited to all child channels indefinitely, then add __ before the variable name. For example:
This should not be confused with setting the variable with the g option, as this sets it as a global variable. Doing so makes the variable available to all channels globally.
So, you may ask "why might we store dial strings as a variable?" The simple reason is that it allows a minimal amount of code for dialing all numbers, but still allows for different classes of restriction, by which we mean allowing different users to have different restrictions in what they can and cannot dial.
To pass these variables we will use a macro. Macros are like a template that we can use for repeated tasks, and they allow the passing of variables in an ordered fashion to the macro context. The call will jump to the s extension. The calling extension, context, and priority are stored in ${MACRO_EXTEN}, ${MACRO_CONTEXT}, and ${MACRO_PRIORITY} respectively. Arguments passed are accessed as ${ARG1}, ${ARG2}, and so on within the Macro. While a Macro is being executed, it becomes the context, so you must be able to handle the h, i, and t extensions if required within that context.
Let's build our small macro dialplan. We have a variable defined in the globals section of the extensions.conf file as follows:
In the context that we use for dialing, we have:
Here, we have defined the macro we are going to pass the call to, along with a single variable we defined in the globals section (the value of the calling extension can be retrieved within the macro by using ${MACRO_EXTEN}).
The macro context looks like this:
This is the same as the dial string:
We have seen that we can pass one dial string, but let's now pass other variables to the Dial() application, such as a backup route for outgoing calls, and the caller ID we want to use for the call.
Now it's time to bring some .conf file variables into the mix. Using the setvar facility in the sip.conf, iax.conf and chan_dahdi.conf files, we can set variables specific for every user such as unique caller ID, call limits, whether we want to record the call, account codes. Basically, anything that will help you handle calls more efficiently.
One problem using .conf files is that the relevant channel module needs to be reloaded after a change, and in the case of DAHDI, Asterisk would need to be restarted. This isn't too much of an issue but the need can be removed by using the AstDB for storing commonly changed settings, such as caller ID and recordings.
You may think that all this variable use is over-complicated, but consider a system that supports multiple tenants. Using these techniques, you will only need one dialplan for multiple tenants instead of one per tenant. Simply set the tenantID in the relevant .conf file and then store the tenants' features in the globals section of the dialplan and in the AstDB, and all calls will go out as that tenant group. The concept is the same for other scenarios, such as departments that require cross charging of telephone costs.
Setting and retrieving variables in the AstDB is very simple and achieved through the use of the Set() application. Variables can exist in splendid isolation or be grouped into families. The syntax for setting a variable is:
Retrieving the variable's value is equally as simple:
So, let's have a look at how we can implement a simple multi-tenant dialplan using multiple variable stores:
As we can see, we have been able to cut down the amount of code and make it universal for different types of users and systems. Using a macro lets us pass an ordered list of arguments. It is easiest to think of macro arguments as a list of variables since they are handled the same way.
Due to the way macro is implemented, it executes the priorities contained within it via a sub-engine, and a fixed per-thread memory stack allowance. Macros are limited to seven levels of nesting. It can be possible that stack-intensive applications in deeply-nested macros could cause Asterisk to crash. Take this into account and be very careful when nesting macros.
