summaryrefslogtreecommitdiff
path: root/umtsmodem.py
blob: b70058466a5efc3aee87bfcde59e5179be628c9c (plain)
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/usr/bin/python

import serial
import time
import sys
import re

modem_device = "/dev/ttyACM1"
apn = "web.vodafone.de"

# TODO:  AT*EGNCI  (gsm-only)
#        AT*EWNCI  (umts-only)
#        AT+COPS   (operator select)
#
# *EGNCI: "26202","026E","00000000",6,50,24
#
# *EWNCI:
#   UARFCN,PSC,RSCP,ECNO,PathLoss
#   10588 ,287,36  ,14  ,158
#
# UARFCN = Channel, RSCP = RSSI, CID = PSC
# RNCid = CID_lang / 65536   (sometimes(?) == LAC)
# CID   = CID_lang % 65536
#

def send_command(modem, cmd, text):
    modem.write(cmd)
    if text != None:
	print text + ": ",
    response = modem.readlines()
    if text != None:
	print ('ERROR\r\n' in response and "Error" or "OK")
    return response


def get_pin_state(modem):
    modem.write('AT+CPIN?\r')
    response = modem.readlines()
    if "+CPIN: SIM PIN\r\n" in response:
	return False
    elif "+CPIN: READY\r\n" in response:
	return True
    else:
	print "[get_pin_state] Unknown response",
	print response
	return False


# determine whether there is a gsm or umts connection
# -1: unknown
#  0: gsm
#  2: umts
def connection_mode(modem):
    response = send_command(modem, 'AT+COPS?\r', None)
    for line in response:
	if line.startswith('+COPS: '):
	    values = line[7:].strip().split(',')
	    if len(values) == 1:
		return -1
	    else:
		return int(values[-1])
    return -1


def cell_info(modem):
    cells = set()

    # get GSM cell information
    send_command(modem, 'AT+CFUN=5\r', None)
    while connection_mode(modem) != 0:
	time.sleep(1)

    # get connected station
    modem.write('AT+CREG=2\r')
    modem.readlines()
    modem.write('AT+CREG?\r')
    response = modem.readlines()
    modem.write('AT+CREG=0\r')
    modem.readlines()
    for line in response:
	if line.startswith('+CREG: '):
	    results = line.rstrip()[7:].split(',')
	    if len(results) == 4:
		lac = int(results[2].strip('"'), 16)
		cid = int(results[3].strip('"'), 16)
	    break

    modem.write('AT*EHNET=2\r')
    response = modem.readlines()
    for line in response:
	if line.startswith('*EHNET: '):
	    mcc = int(line[8:].rstrip().strip('"')[:3])
	    mnc = int(line[8:].rstrip().strip('"')[3:])
    cells.add((mcc, mnc, lac, cid))


    # check stations until all are known (i.e. no '???' in response)
    retry = True
    while retry:
	retry = False
	response = send_command(modem, 'AT*EGNCI\r', None)
	if 'ERROR\r\n' in response:
	    print "error"
	    retry = True
	    time.sleep(1)
	    continue

	for line in response:
	    if line.startswith('*EGNCI: '):
		values = line[8:].rstrip().split(',')
		try:
		    mcc = int(values[0].strip('"')[:3])
		    mnc = int(values[0].strip('"')[3:])
		    lac = int(values[1].strip('"'), 16)
		    cid = int(values[2].strip('"'), 16)
		    if cid == 0:
			continue
		    cells.add((mcc, mnc, lac, cid))
		except:
		    retry = True
		    print "retrying"
		    time.sleep(2)
		    break
    
    for (mcc, mnc, lac, cid) in cells:
	print "MCC: " + str(mcc) + ",  MNC: " + str(mnc) + ",  LAC: " + str(lac) + ",  CellID: " + str(cid)


#    # get UMTS cell information
#    send_command(modem, 'AT+CFUN=6\r', None)
#    time.sleep(10)
#    response = send_command(modem, 'AT*EWNCI\r', None)
#    for line in response:
#	if line.startswith('*EWNCI: '):
#	    print line.rstrip()

#    # switch back to default mode
#    send_command(modem, 'AT+CFUN=1\r', None)


def print_state(modem):
    modem.timeout = 0.1
    modem.write('AT+CSQ\r')
    response = modem.readlines()
    for line in response:
	if line.startswith('+CSQ: '):
	    signal = line.rstrip()[6:].split(',')[0]
	    print "Signal: " + signal + "/31"
	    break

    mcc, mnc, lac, cid = -1, -1, -1, -1
    modem.write('AT*EHNET=2\r')
    response = modem.readlines()
    for line in response:
	if line.startswith('*EHNET: '):
	    mcc = line[8:].rstrip().strip('"')[:3]
	    mnc = line[8:].rstrip().strip('"')[3:]
	    break

    modem.write('AT+CREG=2\r')
    modem.readlines()
    modem.write('AT+CREG?\r')
    response = modem.readlines()
    modem.write('AT+CREG=0\r')
    modem.readlines()
    for line in response:
	if line.startswith('+CREG: '):
	    results = line.rstrip()[7:].split(',')
	    if len(results) == 4:
		lac = int(results[2].strip('"'), 16)
		cid = int(results[3].strip('"'), 16) % 65536  # last 2 bytes for umts
	    break
    print "MCC: " + str(mcc) + ",  MNC: " + str(mnc) + ",  LAC: " + str(lac) + ",  CellID: " + str(cid)



def start_modem(modem):
    if not get_pin_state(modem):
	pin = raw_input("Please enter PIN: ")
	send_command(modem, 'AT+CPIN="' + pin + '"\r', "Sending PIN")
    send_command(modem, 'AT+CFUN=1\r', "Starting modem")


def connect(modem):
    send_command(modem, 'AT+CGDCONT=1,"IP","' + apn + '"\r', "Setting up")
    send_command(modem, 'AT*ENAP=1,1\r', "Connecting")


def disconnect(modem):
    send_command(modem, 'AT*ENAP=0\r', "Disconnecting")


def stop_modem(modem):
    send_command(modem, 'AT+CFUN=4\r', "Stopping")


def show_usage():
    print "Usage: " + sys.argv[0] + " <command>"
    print "\tstart:        switch on modem and unlock sim"
    print "\tstop:         switch modem to powersave state"
    print "\tconnect:      connect to internet"
    print "\tdisconnect:   disconnect from internet"
    print "\tstate:        show signal/base station info"
    print "\tcellinfo:     show info about all received cells"

if len(sys.argv) != 2:
    show_usage()
    sys.exit(0)

modem = serial.Serial(modem_device, timeout=0.5)
modem.readlines()

if sys.argv[1] == "start":
    start_modem(modem)
elif sys.argv[1] == "stop":
    stop_modem(modem)
elif sys.argv[1] == "connect":
    start_modem(modem)
    connect(modem)
elif sys.argv[1] == "disconnect":
    disconnect(modem)
    stop_modem(modem)
elif sys.argv[1] == "state":
    print_state(modem)
elif sys.argv[1] == "cellinfo":
#    start_modem(modem)
    cell_info(modem)
else:
    show_usage()


modem.close()