GSM Gateway with Huawei E220 - debian on Raspberry pi - Gammu

De Wiki de Romain RUDIGER
Aller à : navigation, rechercher

Description

Board: Raspberry Pi 1 model B revision 2

OS: Debian wheezy 7.8 3.18.11+ #781 PREEMPT Tue Apr 21 18:02:18 BST 2015 armv6l GNU/Linux

HSDPA USB dongle: ID 12d1:1003 Huawei Technologies Co., Ltd. E220 HSDPA Modem / E230/E270/E870 HSDPA/HSUPA Modem

Detection of the dongle

Check which usb device is the dongle:

$ grep HUAWEI /var/log/dmesg
[    7.223808] usb 1-1.3: Product: HUAWEI Mobile
[    7.230161] usb 1-1.3: Manufacturer: HUAWEI Technologies
[    7.903174] usb 1-1.3: Product: HUAWEI Mobile
[    7.912989] usb 1-1.3: Manufacturer: HUAWEI Technologies
[    9.049415] scsi 3:0:0:0: CD-ROM            HUAWEI   Mass Storage     2.31 PQ: 0 ANSI: 2

Grep all messages about that usb device:

$ grep "usb 1-1.3" /var/log/dmesg
[    7.053973] usb 1-1.3: new full-speed USB device number 4 using dwc_otg
[    7.179556] usb 1-1.3: New USB device found, idVendor=12d1, idProduct=1003
[    7.195063] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[    7.223808] usb 1-1.3: Product: HUAWEI Mobile
[    7.230161] usb 1-1.3: Manufacturer: HUAWEI Technologies
[    7.328875] usb 1-1.3: USB disconnect, device number 4
[    7.743931] usb 1-1.3: new full-speed USB device number 5 using dwc_otg
[    7.877992] usb 1-1.3: New USB device found, idVendor=12d1, idProduct=1003
[    7.893805] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[    7.903174] usb 1-1.3: Product: HUAWEI Mobile
[    7.912989] usb 1-1.3: Manufacturer: HUAWEI Technologies
[    8.441986] usb 1-1.3: GSM modem (1-port) converter now attached to ttyUSB0
[    8.480066] usb 1-1.3: GSM modem (1-port) converter now attached to ttyUSB1

List usb devices:

$ lsusb
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.
Bus 001 Device 005: ID 12d1:1003 Huawei Technologies Co., Ltd. E220 HSDPA Modem / E230/E270/E870 HSDPA/HSUPA Modem

Install Gammu

This will install gammu software and the python library:

$ sudo aptitude install gammu python-gammu
$ aptitude search '~igammu'
i   gammu                                                            - mobile phone management utility
i   libgammu-i18n                                                    - mobile phone management library (i18n files)
i   libgammu7                                                        - mobile phone management library
i   python-gammu                                                     - Python module to communicate with mobile phones

Configure Gammu

$ gammu-config
                                              ┌────────────────────────────────────────────────┐
                                              │ Current Gammu configuration                    │
                                              │ ┌────────────────────────────────────────────┐ │
                                              │ │   P  Port                 (/dev/ttyUSB0)   │ │
                                              │ │   C  Connection           (at19200)        │ │
                                              │ │   M  Model                (at)             │ │
                                              │ │   D  Synchronize time     (yes)            │ │
                                              │ │   F  Log file             ()               │ │
                                              │ │   O  Log format           (nothing)        │ │
                                              │ │   L  Use locking          ()               │ │
                                              │ │   G  Gammu localisation   ()               │ │
                                              │ └────────────────────────────────────────────┘ │
                                              │                                                │
                                              │                                                │
                                              ├────────────────────────────────────────────────┤
                                              │   < Edit >  < Save >  < Exit >  < Help >       │
                                              └────────────────────────────────────────────────┘
$ grep -Ev "^(#|$)" .gammurc
[gammu]
port = /dev/ttyUSB0
model = at
connection = at19200
synchronizetime = yes
logfile =
logformat = nothing
use_locking =
gammuloc =

Test the dongle on command line

Test the communication with the dongle with the gammu command line:

$ gammu identify
Device               : /dev/ttyUSB0
Manufacturer         : Huawei
Model                : E220 (E220)
Firmware             : 11.313.02.00.01
IMEI                 : 354136000000000
SIM IMSI             : 208150000000000

At that point the dongle is flashing two times in green. I need to enter a PIN code to unlock the SIM:

$ gammu getsecuritystatus
Waiting for PIN.
$ gammu entersecuritycode PIN 6666
$ gammu getsecuritystatus
Nothing to enter.

Check the network connectivity:

$ gammu monitor 1
Press Ctrl+C to break...
Entering monitor mode...

Enabling info about incoming SMS    : No error.
Enabling info about incoming CB     : No error.
Enabling info about calls           : No error.
Enabling info about USSD            : No error.
SIM phonebook        :   0 used, 250 free
Own numbers          :   1 used,   4 free
Battery level        : 0 percent
Charge state         : battery connected and is being charged
Signal strength      : -85 dBm
Network level        : 42 percent
SIM SMS status       : 0 used, 0 unread, 50 locations
Phone SMS status     : 0 used, 0 unread, 255 locations
Network state        : roaming network
Network              : 208 01 (Orange, France), LAC 421, CID 1DE18E0
Name in phone        : "Orange F"
Packet network state : roaming network
Packet network       : 208 01 (Orange, France), LAC 421, CID 1DE18E0
Name in phone        : "Orange F"
GPRS                 : attached

Leaving monitor mode...

Try to send an SMS:

$ echo "Miam Miam Miam" | gammu --sendsms TEXT +33620000000
If you want break, press Ctrl+C...
Sending SMS 1/1....waiting for network answer..OK, message reference=114

Read an SMS:

$ gammu monitor 1 | grep SMS
Press Ctrl+C to break...
Enabling info about incoming SMS    : No error.
SIM SMS status       : 1 used, 0 unread, 50 locations
Phone SMS status     : 0 used, 0 unread, 255 locations

$ gammu getsmsfolders
1. "                         Inbox", SIM memory, Inbox folder
2. "                        Outbox", SIM memory, Outbox folder
3. "                         Inbox", phone memory, Inbox folder
4. "                        Outbox", phone memory, Outbox folder

$ gammu getallsms
Location 0, folder "Inbox", SIM memory, Inbox folder
SMS message
SMSC number          : "+33695000659"
Sent                 : Fri 14 Aug 2015 20:20:54  +0200
Coding               : Default GSM alphabet (no compression)
Remote number        : "+33620000000"
Status               : UnRead

Grrr



1 SMS parts in 1 SMS sequences

$ gammu monitor 1 | grep SMS
Press Ctrl+C to break...
Enabling info about incoming SMS    : No error.
SIM SMS status       : 1 used, 0 unread, 50 locations
Phone SMS status     : 0 used, 0 unread, 255 locations

To reset the dongle:

gammu --reset HARD

Test of the python library

The code gammu_test_sms.py:

"""Program to test gammu

This program offers basic functionalities:
  -check the network status
  -check the battery
  -unlock SIM card with PIN code
  -get the number of SMS
  -display and delete the SMS
  -send an SMS

Example command line:
  gammu_test_sms.py

Invocation summary:
  gammu_test_sms.py
"""

import gammu
import logging
import sys
import time


def display_network_info(state_mach):
  """Display network informations
  Args:
    state_mach: gammu state machine object

  Returns:
    nothing.
  """
  # Reads network information from phone
  netinfo = state_mach.GetNetworkInfo()

  # Print information
  logging.info(
      'Network name: %s, code: %s, LAC: %s, CID: %s.',
      netinfo['NetworkName'], netinfo['NetworkCode'],
      netinfo['LAC'], netinfo['CID'])


def display_config(state_mach):
  """Display configuration
  Args:
    state_mach: gammu state machine object

  Returns:
    nothing.
  """
  config = state_mach.GetConfig()
  logging.info('Device: %s', config['Device'])
  logging.info('Connection: %s', config['Connection'])


def display_battery(state_mach):
  """Display battery status
  Args:
    state_mach: gammu state machine object

  Returns:
    nothing.
  """
  battery = state_mach.GetBatteryCharge()
  if not battery:
    logging.error('Can\'t get the battery status.')
  elif battery['ChargeState'] == 'BatteryPowered':
    logging.warning('The GSM is on battery, remaining power=%i%%.',
        battery['BatteryPercent'])
  elif battery['ChargeState'] == 'BatteryConnected':
    logging.info('The GSM is connected to the charger.')


def display_signal_status(state_mach):
  """Display signal level
  Args:
    state_mach: gammu state machine object

  Returns:
    nothing.
  """
  signal = state_mach.GetSignalQuality()
  if not signal:
    logging.error('Can\'t get the signal status.')
  else:
    logging.info('Signal status: %i%% (%idBm).',
        signal['SignalPercent'], signal['SignalStrength'])


def display_sms_status(state_mach):
  """Display the number of SMS stored in the SIM
  Args:
    state_mach: gammu state machine object

  Returns:
    nothing.
  """
  status = state_mach.GetSMSStatus()
  logging.info('SMS on SIM: %i', status['SIMUsed'])


def send_sms(state_mach, text, number):
  """send an SMS
  Args:
    state_mach: gammu state machine object
    text: text message
    number: international phone number

  Returns:
    sms[] a table of SMS objects
  """
  message = {
      'Text': text,
      'SMSC': {'Location': 1,
              'Number': '+33695000695"',
              'Format': 'Text',
              'Validity': 'Max'},
      'Number': number,
  }
  return state_mach.SendSMS(message)


def read_sms(state_mach):
  """Read, print and delete all the SMS
  Args:
    state_mach: gammu state machine object

  Returns:
    sms[] a table of SMS objects
  """
  number_of_sms = state_mach.GetSMSStatus()['SIMUsed']
  sms = []
  first = True
  while number_of_sms > 0:
    if first:
      smspos = state_mach.GetNextSMS(Start = True, Folder = 0)
      first = False
    else:
      smspos = state_mach.GetNextSMS(
          Location = smspos[0]['Location'], Folder = 0)

    for pos in range(len(smspos)):
      state_mach.DeleteSMS(smspos[pos]['Folder'], smspos[pos]['Location'])
    number_of_sms = number_of_sms - len(smspos)
    sms.append(smspos)
  for msg in sms:
    logging.info(
        'SMS from %s at %s: %s',
        msg[0]['Number'], msg[0]['DateTime'], msg[0]['Text'])


def main(unused_argv):
  """Main function.
  Args:
    unused_argv: Sequence of command line arguments.  Not used.

  Returns:
    0 on success.
  """
  logging.basicConfig(level=logging.DEBUG)

  # Create state machine object
  state_mach = gammu.StateMachine()

  # Read ~/.gammurc
  state_mach.ReadConfig()

  # Connect
  state_mach.Init()

  # Check security statue
  status = state_mach.GetSecurityStatus()
  logging.info('Checking secutiry status.')
  while status:
    logging.info('Security code required: %s', status)
    if status == 'PIN':
      # Enter PIN code
      logging.info('Enetring PIN code...')
      state_mach.EnterSecurityCode('PIN','6666')
    status = state_mach.GetSecurityStatus()

  display_config(state_mach)
  #display_battery(state_mach)
  display_network_info(state_mach)
  display_signal_status(state_mach)

  # Send an SMS
  send_sms(state_mach, 'hello :)', '+33652520000')

  # Wait 5 seconds to get the SMS
  time.sleep(5)

  # Read the SMS
  display_sms_status(state_mach)
  read_sms(state_mach)

if __name__ == '__main__':
  main(sys.argv[1:])

Test:

$ python
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gammu_test_sms
>>> gammu_test_sms.main('')
INFO:root:Checking secutiry status.
INFO:root:Device: /dev/ttyUSB0
INFO:root:Connection: at19200
INFO:root:Network name: , code: 208 01, LAC: 421, CID: 1DE18E0.
INFO:root:Signal status: 51% (-79dBm).
INFO:root:SMS on SIM: 1
INFO:root:SMS from +33652520000 at 2015-08-15 13:50:43: hello :)
>>> quit()

gammu-smsd

Installation/configuration

With apt to install the daemon smsd, sqlite and sqlite DBI driver:

$ sudo aptitude install gammu-smsd sqlite3 libdbd-sqlite3

Configure sqlite:

$ gammu-smsd --version | grep "smsd version"
Gammu-smsd version 1.31.90
$ wget https://github.com/gammu/gammu/raw/1.31.90/docs/sql/sqlite.sql
$ sudo mkdir /var/spool/gammu/db
$ sudo chown gammu:gammu /var/spool/gammu/db
$ sudo chmod 770 /var/spool/gammu/db
$ sudo -u gammu sqlite3 /var/spool/gammu/db/gammu.sqlite
SQLite version 3.7.13 2012-06-11 02:05:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .read sqlite.sql

sqlite> .tables
daemons           outbox            pbk_groups
gammu             outbox_multipart  phones
inbox             pbk               sentitems
sqlite> .databases
seq  name             file
---  ---------------  ----------------------------------------------------------
0    main             /var/spool/gammu/gammu.sqlite
sqlite> SELECT * FROM gammu;
13
sqlite> SELECT * FROM inbox;
sqlite> SELECT * FROM phones;
sqlite> .quit

Configure gammu-smsd:

$ cat /etc/gammu-smsdrc
# Configuration file for Gammu SMS Daemon

# Gammu library configuration, see gammurc(5)
[gammu]
port = /dev/ttyUSB0
connection = at
# Debugging
#logformat = textall

# SMSD configuration, see gammu-smsdrc(5)
[smsd]
# Backend mysql
service = sql
driver = sqlite3
host = localhost
database = gammu.sqlite
dbdir = /var/spool/gammu/db/
# PIN code
pin = 6666
# Log facility
logfile = syslog
# Log level 0=none 1=basic 2=SQL 4, 255=debug
debuglevel = 1
# Hangup incomming calls
hangupcalls = 1
# USB modem as no battery
checkbattery = 0
# Delivery report as log entry
deliveryreport = log
# SMSC number
smsc = +33695000695

First startup

Start the daemon with sudo service gammu-smsd restart

$ tail -f /var/log/syslog
Aug 15 13:24:35 sms gammu-smsd[4978]: Using SQL service
Aug 15 13:24:35 sms gammu-smsd[4978]: Configuring Gammu SMSD...
Aug 15 13:24:35 sms gammu-smsd[4978]: SHM token: 0xffffffffce022a3e (-838718914)
Aug 15 13:24:35 sms gammu-smsd[4978]: PIN code is "6666"
Aug 15 13:24:35 sms gammu-smsd[4978]: CommTimeout=30, SendTimeout=30, ReceiveFrequency=0, ResetFrequency=0, HardResetFrequency=0
Aug 15 13:24:35 sms gammu-smsd[4978]: checks: CheckSecurity=1, CheckBattery=0, CheckSignal=1
Aug 15 13:24:35 sms gammu-smsd[4978]: mode: Send=1, Receive=1
Aug 15 13:24:35 sms gammu-smsd[4978]: deliveryreport = sms
Aug 15 13:24:35 sms gammu-smsd[4978]: phoneid =
Aug 15 13:24:35 sms gammu-smsd[4979]: Using DBI driver 'sqlite3'
Aug 15 13:24:35 sms gammu-smsd[4979]: Execute SQL: SELECT  ID FROM outbox LIMIT 1
Aug 15 13:24:35 sms gammu-smsd[4979]: Execute SQL: SELECT  ID FROM outbox_multipart LIMIT 1
Aug 15 13:24:35 sms gammu-smsd[4979]: Execute SQL: SELECT  ID FROM sentitems LIMIT 1
Aug 15 13:24:35 sms gammu-smsd[4979]: Execute SQL: SELECT  ID FROM inbox LIMIT 1
Aug 15 13:24:35 sms gammu-smsd[4979]: Execute SQL: SELECT Version FROM gammu
Aug 15 13:24:35 sms gammu-smsd[4979]: Database structures version: 13, SMSD current version: 13
Aug 15 13:24:35 sms gammu-smsd[4979]: Connected to Database sqlite3: gammu.sqlite on localhost
Aug 15 13:24:35 sms gammu-smsd[4979]: Created POSIX RW shared memory at 0xb6eda000
Aug 15 13:24:35 sms gammu-smsd[4979]: Starting phone communication...
Aug 15 13:24:43 sms gammu-smsd[4979]: Execute SQL: DELETE FROM phones WHERE IMEI = '354136020000000'
Aug 15 13:24:43 sms gammu-smsd[4979]: Inserting phone info
Aug 15 13:24:43 sms gammu-smsd[4979]: Execute SQL: INSERT INTO phones (IMEI, ID, Send, Receive, InsertIntoDB, TimeOut, Client, Battery, Signal) VALUES ('354136020000000', '', 'yes', 'yes', datetime('now'), datetime('now', '+10 seconds'),
Aug 15 13:24:44 sms gammu-smsd[4979]: Execute SQL: SELECT ID, InsertIntoDB, SendingDateTime, SenderID FROM outbox WHERE SendingDateTime < datetime('now') AND SendingTimeOut < datetime('now') AND SendBefore >= time('now') AND SendAfter <=
Aug 15 13:24:44 sms gammu-smsd[4979]: Execute SQL: UPDATE phones SET TimeOut= datetime('now', '+10 seconds'), Battery = 0, Signal = 48 WHERE IMEI = '354136020000000'

Send SMS and check status

To send an SMS:

$ sudo -u gammu gammu-smsd-inject TEXT +33652000000 -text "test $(date)"

In the logs:

Aug 15 13:28:15 sms gammu-smsd[4979]: Execute SQL: UPDATE outbox SET SendingTimeOut = datetime('now', '+60 seconds') WHERE ID = '1' AND (SendingTimeOut < datetime('now') OR SendingTimeOut IS NULL)
Aug 15 13:28:16 sms gammu-smsd[4979]: SMS sent on device: "/dev/ttyUSB0" status=0, reference=128
Aug 15 13:28:16 sms gammu-smsd[4979]: Transmitted 1 (total: 1) to +33652000000
Aug 15 13:28:16 sms gammu-smsd[4979]: Execute SQL: INSERT INTO sentitems (CreatorID, ID, SequencePosition, Status, SendingDateTime, SMSCNumber, TPMR, SenderID, Text, DestinationNumber, Coding, UDH, Class, TextDecoded, InsertIntoDB, RelativeValidity)  VALUES ('Gammu 1.31.90', '1', 1, 'SendingOK', datetime('now'), '+33695000695', 128, '', '007400650073007400200053006100740020004100750067002000310035002000310033003A00320038003A00300038002000550054004300200032003000310035', '+33652000000', 'Default_No_Compression', '', -1, 'test Sat Aug 15 13:28:08 UTC 2015', '2015-08-15 13:28:08', 255)
Aug 15 13:28:16 sms gammu-smsd[4979]: Execute SQL: UPDATE phones SET Sent= Sent + 1 WHERE IMEI = '354136020000000'
Aug 15 13:28:16 sms gammu-smsd[4979]: Execute SQL: DELETE FROM outbox WHERE ID='1'
Aug 15 13:28:16 sms gammu-smsd[4979]: Execute SQL: DELETE FROM outbox_multipart WHERE ID='1'

Same but delivered:

Aug 15 13:39:20 sms gammu-smsd[4979]: SMS sent on device: "/dev/ttyUSB0" status=0, reference=129
Aug 15 13:39:20 sms gammu-smsd[4979]: Transmitted 2 (total: 1) to +33652000000
Aug 15 13:39:20 sms gammu-smsd[4979]: Execute SQL: INSERT INTO sentitems (CreatorID, ID, SequencePosition, Status, SendingDateTime, SMSCNumber, TPMR, SenderID, Text, DestinationNumber, Coding, UDH, Class, TextDecoded, InsertIntoDB, RelativeValidity)  VALUES ('Gammu 1.31.90', '2', 1, 'SendingOK', datetime('now'), '+33695000695', 129, '', '007400650073007400200053006100740020004100750067002000310035002000310033003A00330039003A00300031002000550054004300200032003000310035', '+33652000000', 'Default_No_Compression', '', -1, 'test Sat Aug 15 13:39:01 UTC 2015', '2015-08-15 13:39:01', 255)
Aug 15 13:39:20 sms gammu-smsd[4979]: Execute SQL: UPDATE phones SET Sent= Sent + 1 WHERE IMEI = '354136020000000'
Aug 15 13:39:20 sms gammu-smsd[4979]: Execute SQL: DELETE FROM outbox WHERE ID='2'
Aug 15 13:39:20 sms gammu-smsd[4979]: Execute SQL: DELETE FROM outbox_multipart WHERE ID='2'
Aug 15 13:39:22 sms gammu-smsd[4979]: Received message from: +33652000000
Aug 15 13:39:22 sms gammu-smsd[4979]: Read 2 messages
Aug 15 13:39:22 sms gammu-smsd[4979]: Execute SQL: INSERT INTO inbox (ReceivingDateTime, Text, SenderNumber, Coding, SMSCNumber, UDH, Class, TextDecoded, RecipientID) VALUES ('2015-08-15 15:39:20', '007400650073007400200053006100740020004100750067002000310035002000310033003A00330039003A00300031002000550054004300200032003000310035', '+33652000000', 'Default_No_Compression', '+33695000659', '', -1, 'test Sat Aug 15 13:39:01 UTC 2015', '')
Aug 15 13:39:22 sms gammu-smsd[4979]: Inserted message id 1
Aug 15 13:39:22 sms gammu-smsd[4979]: Execute SQL: UPDATE phones SET Received = Received + 1 WHERE IMEI = '354136020000000'
Aug 15 13:39:22 sms gammu-smsd[4979]: Delivery report: Delivered to +33652000000
Aug 15 13:39:22 sms gammu-smsd[4979]: Execute SQL: SELECT ID, Status, SendingDateTime, DeliveryDateTime, SMSCNumber FROM sentitems WHERE DeliveryDateTime IS NULL AND SenderID = '' AND TPMR = 129 AND DestinationNumber = '+33652000000'
Aug 15 13:39:22 sms gammu-smsd[4979]: Checking for delivery report, SMSC=+33695000695, state=SendingOK

Compile from source

The doc http://wammu.eu/docs/manual/project/install.html

$ sudo aptitude install build-essential make cmake python-dev pkg-config libpq-dev libusb-1.0-0-dev libdbi0-dev libgudev-1.0-dev libglib2.0-dev unixodbc-dev
$ wget http://dl.cihar.com/gammu/releases/gammu-1.36.4.tar.gz
$ tar -xzf gammu-1.36.4.tar.gz
$ cd gammu-1.36.4/
$ mkdir build
$ cd build
$ cmake .. -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX="/usr/local" -DWITH_NOKIA_SUPPORT=OFF -DWITH_BLUETOOTH=OFF -DWITH_IRDA=OFF
$ make
$ make test
$ sudo make install
$ gammu-smsd --version
Gammu-smsd version 1.36.4
Compiled in features:
OS support:
  - SHM
  - DAEMON
  - PID
  - ALARM
  - GETOPT
  - GETOPT_LONG
  - SYSLOG
Backend services:
  - NULL
  - FILES
  - POSTGRESQL
  - DBI
  - ODBC

Links

Main contributor blog Michal Cihar: https://blog.cihar.com/archives/gammu/

Git repository: https://github.com/gammu