import shsettings import MDM import MDM2 def performAndWait argRequest

 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
import shsettings
import MDM
import MDM2
def performAndWait(argRequest,argExpectedAnswer): #throws ConnectionException
print 'performAndWait(' + argRequest + ',' + argExpectedAnswer + ')'
argExpectedAnswer = argExpectedAnswer
argRequest = argRequest+'\r'
MDM.send(argRequest+'\r',0)
answer=''
#waits until the modem responds something
while answer == '':
answer = MDM.receive(1)
#after the response is received, checks whether the response equals argExpectedAnswer
if answer.find(argExpectedAnswer) == -1:
print 'unexpected answer: ' + answer
raise RuntimeError
print answer
return
class shCSock:
def __init__(self):
#initializes the modem
self.initCGDCONT = 'at+cgdcont=1,"IP","' + shsettings.APN + '"'
self.connectString = 'at#sd=1,0,' + shsettings.DEFAULT_PORT + ',"' + shsettings.DEFAULT_IP + '"'
self.isConnected = 0
def manageIncoming(self): #throws EOFError
if self.isConnected == 0: raise EOFError
tstr = MDM.read()
if tstr == '': return
if tstr.find('NO C') != -1:
self.onDisconnect()
raise EOFError
print 'received :'
print len(tstr)
MDM2.send(tstr,0)
def manageOutgoing(self):
if self.isConnected == 0: raise EOFError
tstr = MDM2.read()
if tstr == '': return
MDM.send(tstr,0)
def connect(self): #throws EOFError
#if connection is already established, onDisconnect it
if self.isConnected == 1: raise RuntimeError
try:
performAndWait('at+cgatt=1','OK')
performAndWait(self.initCGDCONT,'OK')
performAndWait('at#sgact=1,1','SGACT')
performAndWait(self.connectString,'CONNECT')
self.isConnected = 1
except RuntimeError:
self.onDisconnect()
raise EOFError
def disconnect(self):
if self.isConnected == 1:
try:
performAndWait('+++','OK')
performAndWait('at#sh=1','OK')
except RuntimeError: pass
self.onDisconnect()
def onDisconnect(self):
#the gprs is detached here
try:
self.isConnected = 0
performAndWait('at+cgatt=0','OK')
except:
#if somehow the gprs connection could not be detached, raise the error that causes module restart
raise SystemError
shSock = shCSock()
while 1:
try:
shSock.connect()
while 1:
shSock.manageIncoming()
shSock.manageOutgoing()
except EOFError:
shSock.onDisconnect()