Asterisk, or home telephony for (pro) advanced users

    This story began two long years ago when during a business trip to the USA I was suddenly left without mobile communications: I changed my phone with a fool before the trip, and he turned out to be a “dual-band” ... Yes, and roaming is not cheap ... The
    result was the discovery of SIP- telephony.

    And a few months ago, from articles on Habré, I find out that other people’s uncles can not be paid for long-distance, if you need to call from somewhere in their hometown via the Internet! It is enough to install a VoIP server and configure it the way you need it!

    And so, picking up Asterisk, I started an operation to combat the excessive greed of OpSoSov ...


    • This topic is a compilation of some solutions that I applied for myself. Someone can implement something differently or better - I will listen with pleasure and, possibly, improve something at home.
    • It is assumed that the reader of the topic understands at the initial level in the question. If not, at the end I provided a link to download the tutorial.


    There was a 2-core server on ubuntu (10.04), which, in principle, performs the duties of a file archive for me, but in practice it most often is idle.
    It was necessary to simplify my life with telephone conversations.
    In particular, the following tasks were set:
    • If I am not at home - I must not miss incoming calls to MGTS number
    • If I am on a business trip - through the Internet I should be able to make calls around the city
    • Again - on a business trip, ideally, I should not spend money on roaming, but at the same time receive calls made to my number
    • Ideally, protect yourself from Akada-type dialers that simply got
    • Simplification of calls, taking into account the fact that it was planned to transfer the PBX to code 499
    • Usability of all this

    Having outlined the circle of tasks - we proceed to the purchase of hardware for this business.


    D-Link DVG-7111S - GTS-VoIP Adapter

    I chose it for a relatively "cheap" price - in Moscow it costs from 2,152 to 2,610 rubles, which is slightly cheaper than the Linkus, which also needs to be found.
    Essentially, it makes two SIP clients that connect to the Asterisk from the city line and phone.
    We make the settings like this Makar

    One subtlety is connected with CallerID - to transmit it correctly, you must skip one call, so that the adapter can determine the number:
    HOT LINE-> Ring count before FXO pick up = 1

    If necessary, you can update the firmware, but unlike from routers and other DLinkovskie devices - here it is a rather extraordinary process ...

    Sometimes the definition of the signal “Busy” fools at the adapter. To do this, you need to configure the duration of these signals.There is an instruction on how to get them , but I haven’t done it myself yet - it’s only the second day that this problem started after changing the equipment to the exchange.

    For a call from Asterisk to a city number, the following format is used for Dial in Dialplan:
    Dial (SIP / channel number FXO / phone)
    For a phone call:
    Dial (SIP / channel number FXS)

    To simplify life with insanity from MGTS I made myself dial all Moscow numbers in the same way "8-code-7 digits", and with the dialing rules - the server will figure it out:

    Below are two configuration options. The first option is for those with a number in the 495 code, and the second is in 499. Both options allow you to call both the phones in the 495 code and the 499.

    For numbers in the 495 code For numbers in the 499 code
    ; 495 - только семь цифр
    exten => _8495XXXXXXX,1,Dial(SIP/701/${EXTEN:4})
    exten => _8495XXXXXXX,n,Hangup()
    ; 499 - через восьмёрку
    exten => _8499XXXXXXX,1,Dial(SIP/701/${EXTEN:0}) ; Тут не испытывал - знакомых в 499 коде нет, но подозреваю, что на старых АТС надо как-то по-другому, через паузу после 8...
    exten => _8499XXXXXXX,n,Hangup()

    ; 495 - с "восьмёркой"
    exten => _8495XXXXXXX,1,Dial(SIP/701/${EXTEN:0})
    exten => _8495XXXXXXX,n,Hangup()
    ; 499 - без "восьмёрки"
    exten => _8499XXXXXXX,1,Dial(SIP/701/${EXTEN:1})
    exten => _8499XXXXXXX,n,Hangup()


    Initially, I used the Panasonic radio handset connected to the adapter’s FXS port as a phone, but quickly became disappointed: its clumsy display only managed digital CallerID. Therefore, the Siemens Gigaset C470 IP + was purchased an additional handset for it Siemens Gigaset C47H .
    I laid out five thousand for them and do not regret it: The main charm of the unit is that it supports simultaneous work with 6 handsets (main + 5 additional).
    “And what's the point? There is only one line! ”You say and ... You will be fundamentally wrong!
    In addition to 6 handsets, the base station also supports 6 sip accounts! Each of which can be attached to its pipe !!!
    Those. - if you put a radio tube in each room in the apartment, then it will be completely different sip-users who can easily talk at the same time!

    A few words about the setting:
    Whatever they say in the instructions - dynamic allocation of the address on the phone does not occur. Therefore, there are two options - drive the correct one from the handset or by short pressing the button on the base - determine the current one and configure the network on it.
    You can change the PIN code ONLY from the handset - there is no such item in the web panel: so it’s better to change it right away until some thread is a clever hacker!

    GSM adapter

    Then I took the path of least resistance and bought the MTS modem Huawei E1550.
    Why MTS?
    Firstly - 770 rubles, and not 1,500 for “not locked”
    . Secondly - Bi and Mega have voice functions in general.
    Thirdly, I needed a modem for Auchanov’s A-Mobile tariff, which didn’t have to be re-flashed on the MTS network.
    Who does not know - A-Mobile allows you to make 15 minutes of free calls per day to another A-Mobile, after which - a nominal fee of 90 cents per minute. I needed it as a backup channel to my home network and the tariff, IMHO, was the most pleasant!
    Device settings are dreary , but nothing complicated.

    + Now I received a message from Habrapost from Angel2S2 :
    “By the way, about unlocking huawei modems ... If you're interested, you can take a look at me - . I unlocked the E160G and E1550 from a megaphone and MTS, you can also call :) “
    MB will help someone!

    Uchkuduk two modems ...

    I’ll add a few words ... I put on the system a second modem for incoming with AlloIncognito and then he came in the most ... Well, who: the modems themselves changed places better than acrobats in the circus! When you disconnect one - the second strove to move to its ports, etc. etc.

    And since the dialplanes for them are fundamentally different - it was necessary to somehow solve ...
    The solution is quite justified for Linux: you can assign a fixed “link” to the port!
    Those. - set for modem 1 - the ports are not ttyUSB1 and 2, but hv0 and hi0 (HuaweiVoice and HuaweiInfo)!
    Disconnect both modems from the computer, insert the first.
    We give the dmesg command from the root in the terminal. A
    bunch of everything falls out in response, but at the end there are treasured lines: “Who is hu”: After the option, there is a port identifier.
    [291015.913221] option 1-2:1.0: GSM modem (1-port) converter detected
    [291015.913364] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB0
    [291015.913926] option 1-2:1.1: GSM modem (1-port) converter detected
    [291015.914026] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB1
    [291015.916678] option 1-2:1.2: GSM modem (1-port) converter detected
    [291015.916812] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB2

    1-2 - the first USB host, the second device
    : 1.1 - the first port on this device.
    In the next line - infa on the topic of what port this has become our internal.
    We are interested in the pre-last and last - 1 and 2 in this case.
    1 - port for voice, 2 - for data.
    Now open the file /etc/udev/rules.d/huawei.rules from under the root for editing - here the rules for all Huawei devices in the system are written. Most likely it will be empty.
    We drive in the lines: “All devices on this particular port are henceforth and also called hv0, and on this - hi0! Save, Amen! ”
    KERNEL=="ttyUSB[0-9]*", ID=="1-2:1.1", NAME="%k", SYMLINK+="hv0", GROUP="root", MODE="0666"
    KERNEL=="ttyUSB[0-9]*", ID=="1-2:1.2", NAME="%k", SYMLINK+="hi0", GROUP="root", MODE="0666"

    We repeat the process starting from sticking in for the second modem - there will appear two more lines in the file, in which there are already ports from the second modem and hv1 and hi1 ... You can add the third one, and one hundred and thirty-fifth ...

    Now if you pull out the modems and insert, then to the command ls -1 / dev / hv * or ls -1 / dev / hi * - ALWAYS give the right device, the main thing is not to confuse the connector on the computer!

    /etc/asterisk/datacard.conf also changes - instead of faceless Appear Now we restart the Asterisk and cheers - there will be no more confusion! That's all with iron for now.
    audio=/dev/ttyUSB1 ; tty for audio connection
    data=/dev/ttyUSB2 ; tty for AT commands

    audio=/dev/hv0 ; tty for audio connection
    data=/dev/hi0 ; tty for AT commands

    SIP operators

    In principle, with the existing equipment, we already have a city + mobile line, but I want additional opportunities, and I need to somehow call between the long-distance cities!


    Multifon is a service from the Moscow Megaphone. The trick is that this is not just Internet telephony! This is Internet telephony tied to your Megaphone number!
    Translated into Russian: if someone calls your number, both cellular and SIP clients will work if configured appropriately!
    The configuration of Asterisk for this case was described quite well on Habré , I can only add instructions on how to bind a few MULTIPHONES to the server - some points are debatable there and it didn’t work because of incompatibility on the codecs, but maybe this is a bug of my config ?!
    UPD Native Multifon instructions for setting up in Asterisk

    A couple of words on the points common to all SIP operators: if you are going to ONLY call from a SIP account, then register is not needed, but if you intend to accept ...
    By the way, only Megaphone has register with such a furious syntax: the rest it is more standard ...


    SIP-telephony service from Euroset. In plus - the lion's share of Russian cities goes at a rate of 49 kopecks. There are incoming numbers in Moscow and a heap of cities, so if you are not too lazy to drive in a number + your number in the Europhone, you can accept incoming numbers from there ...
    Potentially - if you do not particularly need an incoming city number, but do not call too much, it may turn out to be more profitable than monthly 155 rubles from MGTS “for the line” ...

    For registration - you need to buy a telephony card from Euroset. Login-password - will be indicated on the card, in the future this account can be replenished. Registration without a card - simply no.

    Calls to all Russian numbers - at a ruble per minute.
    I took it as a “supplement” to the Europhone: calls to mobiles are cheaper in it, but I’m silent about one and a half rubles for outgoing calls in the Multiphone! If you want to hide your number - that’s it.


    Nothing special, but many prefer it.

    DID, or Direct Phone Number

    This service consists in the fact that you can get a phone number in one of the cities of a country and receive calls to this number through Asterisk.
    The plus is that if you move often, this will allow you to always keep your number, minus - unlike 155 rubles per month at MGTS, the prices for Moscow numbers from operators start at 250 rubles, approximately. (For comparison, a US number costs about $ 3.5 per month).


    According to the people who used it, a direct Moscow number costs 250 rubles per month. The tariffs are not clearly defined, so I can neither confirm nor deny ... Roughly - 250 per month for the number, plus the initial payment for the allocation of the number - 500 rubles for 499 or 3000 for 495 ... It makes sense to pay more if MGTS becomes available - they can here in 499 to push all ?!
    On the plus side are the fact that they provide as many as five incoming channels ... True, only when redirecting to phone numbers, but on SIP - only 2 (they overloaded in April). But the redirect to the phones is paid, but on the SIP - a freebie!
    Well and then: a two-channel phone number - IMHO, very good! More often than not, more!

    “Personal telephone number” or “Number that is always with you”

    MGTSovskaya garbage. In fact - Moscow number through SIP. There is no monthly fee in the time-based version; the price per minute is the same 36 kopecks. Connection - 8340 rubles, and the kit comes with the same Siemens 470, about which I spoke.

    Sponges rolled out? Freebie? Cool?
    Catch a lip-sealer: it works ONLY through MGTS ADSL! As explained in the support - this is only for organizing a second telephone number at home.
    Potentially - it’s obviously possible to steal into the Asterisk, but I DO NOT need such a phone tied to the main line for nothing, but I could not find happy owners of this service on the Internet.
    Just keep in mind that there is such a thing, and if at home someone periodically hangs on the phone, you can connect it to have a backup line ...


    Direct numbers in different countries.
    Registration idiotic:
    1. Go to gtalk2voip , in the corner there is a field for entering e-soap. Enter Google's soap.
    2. Connect to Jabber on your Google account, you see an invitation from the user Connect to the “conversation”
    3. Next, from this bot with the MYPAGE team you get a page through which you can register numbers and replenish the balance.


    A company with an “unprintable” name provides free phone numbers in the US with a redirect to SIP. If you don’t need it, you don’t need to occupy it with registrations: all of a sudden, someone will need it, and everything will go to the Habra effect ?!
    As for this service, I have an eternal scandal with a toad:
    - S! Cool! Free number in the USA! Wow, Wow!
    - What for? - asks the realist. - Who calls a thread from the States ?!
    - That's why they don’t call! Want Want want!
    - Learn English, Wishlist! They’ll call, and what do you say ?!
    - Hyundai-hoh? Au Wiederzane? How! What would such a dustcloth like me say nothing ?! Ha!
    - Anyway - there’s zero sense in it now!
    - So what? Halyaaaaava!

    Alloincognito: “Perfect 499”

    Ideal 499 , the tariff plan from Alyokognito, without a monthly fee for 499 ... Included is a SIM card from Megaphone, to which calls are received ... bdmalex
    threw a link . According to him, it has been used for a long time, there is really no subscription fee and, even beyond my understanding, there is no payment for re-transferring incoming calls to a mobile number !!!

    Asterisk Dialplan Chips

    With iron and operators, somehow figured out ...
    Now a few tricks related to Asterisk:

    Black list

    Sometimes I really want something to stop a person from calling a thread: a former girl, an idiot, always mistaken for a number, advertising agents, polls, etc. etc.
    For this, the Asterisk has the BLACKLIST () command. In fact - she checks the CallerID with a list in her database and if it returns 1 - then you can safely send the caller to hell!
    You can read about the “Simple” version here , but I wanted to make my life a little easier: well, it’s lazy for me to look at the number on the identifier, after which I can drive it “where necessary”!
    Let Asterisk do this himself!

    In Dialplan, when calling from the right context, we write (when calling from MGTS, I redirect to 123 - replace with what you have!): And in the dialplan of the telephone:
    exten => 123,n,Set(_From=${CALLERID(name)}) ; name, а не num потому, что вот так идиотски передаёт CallerID в Астериск адаптер от ДЛинка!
    exten => 123,n,GotoIf($[${BLACKLIST()}=1]?banned) ; Сначала - проверка на заблокированные номера - если номер уже в чёрном списке - переходим к метке banned
    exten => 123,n,Set(DB(ToMe/LastCaller)=${From}) ; Сохраняем номер последнего позвонившего
    ; Тут у нас обработка нормальных вызовов.
    exten => 123,n,Hangup()

    ; И шлём спамеров лесом!
    exten => 123,n(banned),Answer()
    exten => 123,n,Playback(файл, в котором посылающая спамеров лесом фраза)
    exten => 123,n,Hangup()

    ; По 20 - добавляем последнего позвонившего в чёрный список
    exten => 20,1,Set(tmp=${DB(ToMe/LastCaller)})
    exten => 20,n,Set(DB(blacklist/${tmp})=1)

    Now, if after the spammer’s call you pick up the phone and dial “20” - it will be added to the list of banned ones!
    How to clean the number - shown in the instructions above.

    Speed ​​dial

    All of us have numbers that we call most often: relatives, work colleagues, acquaintances ...
    Driving 10 numbers each time is lazy! Therefore, you can create a notebook directly on your PBX!
    In the dial plan for the phone: Etc. etc. Actually, I wanted to make the menu voice, but for some reason the processing of the number “s” doesn’t happen when the handset is removed ... So you can simply write out “who is hu” on the collar ... If you bought several handsets, as in my case, there may be a different one context with their "short numbers": on the phone in the room with my parents I don’t need my friends, but I need theirs ...
    exten => 1,1,Dial(SIP/701/8495......) ; Родителям
    exten => 2,1,Dial(SIP/701/8495......) ; Бабушка
    exten => 3,1,Dial(SIP/701/8495......) ; Дед
    exten => 4,1,Dial(SIP/701/8499......) ; Работа

    Greetings from the time of day

    You can add a bit of “humanity” to your ATSka, so that it gives out a different greeting, depending on the time of day (and if desired - the day of the week, month, etc., etc.). For example, in the morning she can greet the caller with a yawn, and at night she can say everything she thinks about the person who calls when all normal people are already sleeping.

    ; Прикол с временем звонка
    exten => 1200,1,Background(hello_utro) ;Запускаем приветствие "Утро"
    exten => 1200,n,Goto(123,naberite) ;К кнопкам

    exten => 1201,1,Background(hello_den) ;Запускаем приветствие "День"
    exten => 1201,n,Goto(123,naberite) ;К кнопкам

    exten => 1202,1,Background(hello_vecher) ;Запускаем приветствие "Вечер"
    exten => 1202,n,Goto(123,naberite) ;К кнопкам

    exten => 123,1,Verbose("Звонок с линии МГТС")
    exten => 123,n,Answer() ;Поднимаем трубку
    exten => 123,n,GotoIfTime(07:00-12:00|*|*|*?1200,1) ; Утро с 7 до 12
    exten => 123,n,GotoIfTime(12:01-19:00|*|*|*?1201,1) ; День - с 12 до 19
    exten => 123,n,GotoIfTime(19:01-22:00|*|*|*?1202,1) ; Вечер - с 19 до 22
    exten => 123,n,Background(hello_noch) ; Остальное - ночь: Запускаем приветствие "Ночь"

    exten => 123,n(naberite),Verbose("Голосовое меню") ; Далее идёт голосовое меню...


    If left-wing people often call you asking “Masha, Sasha or Dasha,” or even some Barakobam, the next example is yours!
    The general idea is that when you answer, it gives out a greeting in the style of "Hello, you called the apartment. If you are sure that this is Ivanov’s apartment - press 1, if Petrov - 2, Sidorov - 3! If none of the names is suitable, or you call the organization, hang up: you are not in the right place! ”
    Minus - it will also wrap up “useful” bots, such as “You forgot to pay for the phone and we’ll cut you off soon!”, But here either or ...

    exten => 123,n,Answer()
    exten => 123,n(naberite),Background(familie) ;Мессаг на тему выбора фамилии
    exten => 123,n,WaitExten() ;Ждем ввода от пользователя

    exten => 1,1,Goto(normal,s,1) ;Нажали 1 - ура, угадали! Вместо 1 может быть 2, 3 или какой там правильный ответ. "normal" - контекст обработки и общения с теми, кто знает куда позвонил.

    exten => i,1,Playback(invalid) ; Нажали не то — говорим что облом
    exten => i,n,Hangup() ; Вешаем трубку

    exten => t,1,Playback(bay) ; Время кончилось - прощаемся
    exten => t,n,Hangup() ; Вешаем трубку

    Tricky Callback

    I have a mobile phone with two SIM cards: one is for talking, the other is A-Mobaylovskaya for communication with my PBX.
    Well, the problem is that a couple of times by mistake I called from the wrong SIM card - 2.40 is not money, of course, but when you debug and periodically call the server - it’s unpleasant!
    In this connection, I slightly altered the Callback script to my needs. And this is / etc / asterisk / scripts / callback - do not forget to give it the right to execute: for half an hour I could not understand why it did not work!

    ; Обработка звонков
    exten => s,1,GotoIf($["${CALLERID(num)}" = "+7916......."]?allow) ; Номер А-Мобайл - хорошо!
    exten => s,n,GotoIf($["${CALLERID(num)}" = "+7926........"]?callback) ; Мегафон - плохо!
    exten => s,n(reject),Hangup() ; Остальным - просто вешаем трубку, ибо нефиг!
    exten => s,n(allow),Verbose("Звонок с моего А-Мобайла")
    exten => s,n,Goto (incoming_mobile,200,1) ;Редирект на голосовое меню
    exten => s,n,Hangup()
    exten => s,n(callback),Verbose("Я тормоз - позвонил с Мегафона!")
    exten => s,n,System(/etc/asterisk/scripts/callback)
    exten => s,n,Hangup()

    exten => 200,1, .... ; Сюда попадаем или при правильном телефоне, с которого звонили, или после того, как каллбек до нас дозвонился.

    exten => 601,1,Dial(Datacard/g1/+7916....) ; Мне на А-Мобайл
    exten => 601,n,Hangup()

    sleep 10
    echo "Channel: Local/601@incoming_mobile
    MaxRetries: 1
    RetryTime: 10
    WaitTime: 20
    Context: incoming_mobile
    Extension: 200
    Priority: 1
    AlwaysDelete: Yes" >/var/spool/asterisk/tmp/
    mv /var/spool/asterisk/tmp/ /var/spool/asterisk/outgoing/

    “I do not have everything at home!” Or “I am in the house!”

    This fragment is so elementary that it takes longer to describe why it is needed than the extensions themselves!
    So, you went somewhere on business, put a cell phone in your pocket, combed it to the other end of the city and suddenly someone decided to call you at home! Moreover, “your call is important to us,” but you can’t answer ... Or can you? The second piece will be of interest to the owners of the Multifon. I, and many of my friends, have a “disease”: forget the mobile phone in your trouser pocket or bag and stuff this “storage” into the closet ... As a result, the stifled squeak of the phone can hardly be heard, and the call could be important !!! To combat this, I paralleled the radio tube in my room to Megaphone-Multifon. It becomes stupid in 2.5 lines:
    ; Входящий с МГТС или DID
    exten => 123,n,Dial("sip/702",10) ; 10 секунд пинаем только домашний телефонный аппарат - можно задать и большее время и меньшее...
    exten => 123,n,Verbose("Скорее всего меня нет дома - редирект на мобилу, ну и продолжаем пинать трубку!")
    exten => 123,n,Dial("sip/702"&"Datacard/g1/+7916....",20) ; И секунд двадцать будут звонить уже совместно...
    exten => 123,n,Hangup()

    exten => 7926.......,1,Verbose("Звонок на мой Мегафон!")
    exten => 7926.......,n,Dial("SIP/702")
    exten => 7926.......,n,Hangup()


    Unlike home web FTP servers, a home PBX poses a rather serious threat to your well-being: bad radishes, gaining access to your telephone network, can talk so long across the city that Beeline’s bill for a tourist for communication in the amount of half a million can seem penny!
    I recommend reading an article about protecting Asterisk , a note on Habré about the Cuban Epidemic ...
    Well, simple tips:
    1. If calls from a city line go only to city numbers, block the dialing of any other numbers at the extension level.
    2. To enter the intercity - create a separate context for the intercity, the entrance to which will be through the "password" - the number that must be entered.
    3. For accounts of local telephones - drive in sip.conf for each “locale” its fixed IP address, in the worst case - a local sub-grid, since SIP phones and adapters most often have the ability to set a fixed IP.


    This is only a small part of what can be done with Asterisk. I just couldn’t remember some more things - I fall asleep corny on the go.
    All this, if desired, can be supplemented and corrected by readers: write wishes in the comments!


    O`Reilly, Asterisk: The Future of Telephony - Must Have! Bible!
    Asterisk and Linux - the mission of IP-telephony, part 1
    Asterisk and Linux - the mission of IP-telephony, part 2
    Asterisk and Linux - the mission of IP-telephony, part 3
    Making money on the stars
    Voice menu in Asterisk

    PS “A head in the mouth byak .... "- I will sleep off and add more about the protection of all this, a few words about NAT and some other examples.

    PPS Some places in dialplans “cut by the living” - can glitch slightly: write - I’ll clarify and correct!

    Also popular now: