My task is to use mobile phone as GSM Gateway to my Asterisk with a help of chan_mobile so in case I’m unavailable on mobile people can leave a message in my voicemail box. SMS text messages arrive as emails, my replies to which are sent by SMS.
So I used my old Sony Ericsson k530i phone in pair with Asterisk by connecting it to ID 1131:1001 Integrated System Solution Corp. KY-BT100 Bluetooth Adapter USB dongle.
Asterisk support for bluetooth connections to mobile phones and headsets is accomplished through chan_mobile. Not all phones are supported, so it’s worth taking a look at voip-info.org’s page which lists the confirmed compatible dongles and phones. I am getting good results with a KY-BT100 dongle and Sony Ericsson k530i phone, Samsung Galaxy S4 phone.
Here is how to connect your mobile phone to Asterisk with chan_mobile…
Connecting mobile phone to Asterisk via bluetooth by chan_mobile
chan_mobile is an addon, so it needs to be enabled before Asterisk is compiled. On Debian, it’s pretty simple, just add a few packages:
1 |
# apt-get install bluez-utils bluez-hcidump libbluetooth-dev |
then, go to your Asterisk source directory and use make menuselect to enable chan_mobile. It’s in Add-ons -> chan_mobile:
1 2 |
# cd /usr/src/asterisk-1.8.11.0 # ./configure && make menuselect |
Whilst it compiled and installed OK, I had to make a modification to the chan_mobile source before it would recognize my phone:
1 2 3 4 5 6 7 |
# vi /usr/src/asterisk-1.8.11.0/addons/chan_mobile.c Find this: addr.rc_channel = (uint8_t) 1; Replace with: addr.rc_channel = (uint8_t) 0; |
Build Asterisk and (re)install:
1 |
# make && make install |
In order to use a bluetooth-connected phone as a GSM gateway, it’s necessary to pair the phone with the Asterisk server. In Debian, this can be accomplished painlessly through the CLI. First, make your phone discoverable and then scan for it:
1 2 3 |
# hcitool scan Scanning ... E0:1A:55:64:A2:52 k530i |
Make a note of the MAC address. In order to pair, a helper is required to handle the PIN. Run the helper in the background and begin the pairing process:
1 2 |
# bluetooth-agent 1111 & # rfcomm connect hci0 E0:1A:55:64:A2:52 |
Once the pairing has succeeded, make sure your phone is configured to automatically accept connections for this paring in future. You can verify that the paring is working at any time by running:
1 2 3 |
# hcitool con Connections: < ACL E0:1A:55:64:A2:52 handle 41 state 1 lm MASTER AUTH ENCRYPT |
Now, Asterisk needs to be configured to use the paired phone. We need to know which rfcomm channel offers the voice service. The easiest way is to use chan_mobile:
1 2 |
# rasterisk *CLI> module load chan_mobile.so |
Don’t worry about any errors loading the module, it’ll do for now:
1 2 |
*CLI> mobile search E0:1A:55:64:A2:52 k530i Yes Phone 2 |
In this case it is rfcomm channel 2. In addition, we need to know the MAC address of the bluetooth dongle installed in the Asterisk server. Exit the Asterisk CLI and use hcitool:
1 2 3 |
# hcitool dev Devices: hci0 00:81:C5:33:25:A4 |
At last we have all the information needed. Edit or create the chan_mobile configuration file:
1 2 3 4 5 6 7 8 9 10 11 |
# vi /etc/asterisk/chan_mobile.conf [Adapter] address = 00:81:C5:33:25:A4 id = pabx [k530i] address = E0:1A:55:64:A2:52 port = 2 context = from-k530i adapter = pabx |
You will need something in the dialplan to handle this, at minimum something like:
1 2 3 4 5 6 7 |
# vi /etc/asterisk/extensions.conf [from-k530i] exten => s,1,Dial(SIP/100) [my-phones] exten => *12,1,Dial(MOBILE/k530i/5433) |
When the mobile rings, you should get a call on SIP extension 100. Dialing *12 will cause the phone to dial 5433, which in my case gives me life:)’s customer services. I’m sure you get the idea.
Sending SMS with Asterisk and chan_mobile
Trickier, but there is a solution. None of the phones I had spare were supported by chan_mobile’s SMS capabilities. According to the chan_mobile wiki page, only three phones are known to support SMS: the Nokia models E51, 6021 and 6230i..
Once the phone is paired in the normal way, it will send any incoming SMS messages to Asterisk over the bluetooth connection. Asterisk looks for an ‘sms’ extension in the context you specified in chan_mobile.conf. I suggest something like this in your dialplan:
1 2 3 4 5 6 |
[from-k530i] exten => sms,1,Verbose(Incoming SMS from ${SMSSRC} ${SMSTXT}) exten => sms,n,System(echo "To: itgalaxyz@itgala.xyz" > /tmp/smsmail) exten => sms,n,System(echo "Subject: SMS from ${SMSSRC}" >> /tmp/smsmail) exten => sms,n,System(echo "${SMSTXT}" >> /tmp/smsmail) exten => sms,n,System(sendmail -t -f ${SMSSRC}@itgala.xyz < /tmp/smsmail) exten => sms,n,Hangup() |
At first, incoming messages were all arriving with a blank ${SMSSRC}, the easy solution was to apply a patch and re-compile:
1 2 3 4 |
# cd /usr/src/asterisk-1.8* # wget --no-check-certificate https://issues.asterisk.org/jira/secure/attachment/42026/sms-sender-fix.diff # patch -p0 < sms-sender-fix.diff # ./configure && make && make install |
In the latest version of chan_mobile this has to be fixed already!
Now, incoming messages are delivered to me as emails claiming to be from +MOBILENUMBER@itgala.xyz. Obviously, this requires the Asterisk system to have a working MTA, the setup of which I won’t cover here. If you don’t have an MTA at present, take a look at postfix.
Outgoing SMS messages are more work because it’s necessary to parse the contents of the email message, the format of which will be a little less predicatable than an SMS. I elected to use python to do this because it already has a library to do this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
#!/usr/bin/env python # (:? YOUR SCRIPT IS BAD AND YOU SHOULD FEEL BAD! (:? # I'M NOT A DEVELOPER AND THIS IS PROBABLY VERY, VERY BAD, but it does work. # email2sms.py James Stocks # based upon emailspeak.py by sysadminman - http://sysadminman.net # v0.0 2012-04-28 # Import libs we need import sys, time, email, email.Message, email.Errors, email.Utils, smtplib, os, socket, random, re from datetime import date from email.Iterators import typed_subpart_iterator from time import sleep # Asterisk Manager connection details HOST = '127.0.0.1' PORT = 5038 # Asterisk Manager username and password USER = 'your-ast-man-user' SECRET = 'dysmsdvsa' # Generate a random number as a string. We'll use this for file names later on callnum = str(random.randint(1, 100000000)) # Taken from here, with thanks - # http://ginstrom.com/scribbles/2007/11/19/parsing-multilingual- # email-with-python/ def get_charset(message, default="ascii"): """Get the message charset""" if message.get_content_charset(): return message.get_content_charset() if message.get_charset(): return message.get_charset() return default # Taken from here, with thanks - # http://ginstrom.com/scribbles/2007/11/19/parsing-multilingual- # email-with-python/ def get_body(message): """Get the body of the email message""" if message.is_multipart(): #get the plain text version only text_parts = [part for part in typed_subpart_iterator(message, 'text', 'plain')] body = [] for part in text_parts: charset = get_charset(part, get_charset(message)) body.append(unicode(part.get_payload(decode=True), charset, "replace")) return u"\n".join(body).strip() else: # if it is not multipart, the payload will be a string # representing the message body body = unicode(message.get_payload(decode=True), get_charset(message), "replace") return body.strip() # Read the e-mail message that has been piped to us by Postfix raw_msg = sys.stdin.read() emailmsg = email.message_from_string(raw_msg) # Extract database Fields from mail msgfrom = emailmsg['From'] msgto = emailmsg['To'] msgsubj = emailmsg['Subject'] msgbody = get_body(emailmsg) # Find the part of the 'To' field that is the phone number phonenum = re.match( r'\+?([0-9]+)', msgto, re.M) # Whose mobile is this? mobile = sys.argv[1] # Write a log file in /tmp with a record of the e-mails currtime = date.today().strftime("%B %d, %Y") logfile = open('/tmp/email2sms.log', 'a') logfile.write(currtime + "\n") logfile.write("Call Number: " + callnum + "\n") logfile.write("From: " + msgfrom + "\n") logfile.write("To: " + msgto + "\n") logfile.write("Subject: " + msgsubj + "\n") logfile.write("Body: " + msgbody + "\n\n") logfile.close() # Send the call details to the Asterisk manager interface s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) sleep(1) s.send('Action: login\r\n') s.send('Username: ' + USER + '\r\n') s.send('Secret: ' + SECRET + '\r\n\r\n') sleep(1) s.send('Action: originate\r\n') # Dummy channel - I don't actually want any phones to ring s.send('Channel: LOCAL/1@sms-dummy\r\n') s.send('Context: mobiles\r\n') s.send('Exten: ' + mobile + '\r\n') s.send('WaitTime: 30\r\n') # This is a bogus value, but the field is required s.send('CallerId: 5555\r\n') # Do not wait for response from dummy channel s.send('Async: true\r\n') s.send('Priority: 1\r\n') # The variables ${SMSTO} and ${SMSBODY} are used in the dialplan s.send('Variable: SMSTO=' + phonenum.group(1) + ',SMSBODY=\"' + msgbody + '\"\r\n\r\n') sleep(1) s.send('Action: Logoff\r\n\r\n') #Omitting this causes "ast_careful_fwrite: fwrite() returned error: Broken pipe" sleep(3) s.close() |
Copy the above script to /usr/sbin/email2sms.py and make executable:
1 |
# chmod +x /usr/sbin/email2sms.py |
The script uses the Asterisk Manager Interface, so it will need an AMI user. Append this to manager.conf
:
1 2 3 4 5 6 |
# vi /etc/asterisk/manager.conf [your-ast-man-user] secret=dysmsdvsa read=call,user,originate write=call,user,originate |
and also make sure it is enabled in the general section:
1 2 3 4 5 6 |
# vi /etc/asterisk/manager.conf [general] enabled = yes webenabled = yes port = 5038 |
You’ll note that I’m using the context ‘mobiles’. You’ll need to make sure that the extensions you’ll be using exist in this context in extensions.conf:
1 2 3 |
# vi /etc/asterisk/extensions.conf exten => itg,1,MobileSendSMS(k530i,${SMSTO},${SMSBODY}) |
Secondly, there is a dummy extension which the ‘call’ needs to connect to. A NoOp isn’t quite sufficient, I could only get it to work if the extension answered and then did something, in this case answer and wait 10 seconds:
1 2 3 4 5 6 |
# vi /etc/asterisk/extensions.conf [sms-dummy] exten => 1,1,Answer() exten => 1,n,Wait(10) exten => 1,n,Hangup() |
Reload Asterisk to pick up the changes.
So, calling email2sms.py with the argument ‘itg’ uses the k530i mobile.
You need to make sure that email for the domain you have chosen – in my case sms.itgala.xyz – is routed to the Asterisk box. This will normally be accomplished by creating an MX record or creating a transport for the domain on your mail server. Again, I’m not going to cover that part here, but I will cover how to pipe the incoming messages into the python script.
Assuming that you are using postfix, you’ll need a new transport for each mobile you want to use. In my case:
1 2 3 4 |
# vi /etc/postfix/master.cf sms-itg unix - n n - - pipe flags=FR user=itg argv=/usr/sbin/email2sms.py itg |
postfix needs to know that it must use these transports for SMS domains:
1 2 3 |
# vi /etc/postfix/transport ; postmap /etc/postfix/transport sms.itgala.xyz sms-itg |
If postfix doesn’t already have a transport_maps setting, create one. Obviously this could break any existing postfix setup you might have, but if so I’m expecting you to know what you’re doing:
1 |
# postconf -e transport_maps=hash:/etc/postfix/transport |
Restart postfix and that should be all that’s necessary.
1 |
# /etc/init.d/postfix restart |
You need to satisfy yourself that you are not allowing the entire world to relay through your SMS gateway! Understand and make use of postfix’s security features! Don’t wait until you’ve racked up a collosal SMS bill!
If things aren’t quite working, start by checking your mail log:
1 |
# tail -f /var/log/mail.log |
You can do a packet trace to see what’s happening on the Asterisk Manager Interface:
1 |
# tcpdump -A -i lo port 5038 |
Try talking to the AMI directly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$ nc localhost 5038 Action: login Username: your-ast-man-user Secret: dysmsdvsa Action: originate Channel: LOCAL/1@sms-dummy Context: mobiles Exten: itg WaitTime: 30 CallerId: 5555 Async: true Priority: 1 Variable: SMSTO=5555555555,SMSBODY="foo" Action: Logoff |
Watch out for whitespace in the AMI – exten ‘itg’ != ‘itg ‘.
Good luck.