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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
|
from pygsm import GsmModem
import time
import sys
from gluon.sql import SQLDB
from gluon.sql import SQLTable
from gluon.sql import SQLField
from gluon.validators import IS_IN_SET
from gluon.validators import IS_IN_DB
import urllib2
Field=SQLField
echo = 1
debug = 0
posturl = ""
sahanapydatabase = ""
db = ""
branch = "py"
headers = {"Content-type":"text/xml","Accept": "text/plain"}
migrate = False
def T(string):
return string
# Following are copied from msg.py
# Reusable timestamp fields
timestamp = SQLTable(None, 'timestamp',
Field('created_on', 'datetime'),
Field('modified_on', 'datetime')
)
# Reusable author fields
authorstamp = SQLTable(None, 'authorstamp',
Field('created_by'),
Field('modified_by')
)
# Reusable UUID field (needed as part of database synchronization)
import uuid
uuidstamp = SQLTable(None, 'uuidstamp',
Field('uuid', length=64,
notnull=True,
unique=True,
readable=False,
writable=False,
default=uuid.uuid4()))
# Reusable Deletion status field (needed as part of database synchronization)
# Q: Will this be moved to a separate table? (Simpler for module writers but a performance penalty)
deletion_status = SQLTable(None, 'deletion_status',
Field('deleted', 'boolean',
readable=False,
writable=False,
default=False))
"""
Database for the SMS dump
"""
smsdb = SQLDB("sqlite://smsdump.db")
"""
Table definition for the SMS dump
"""
smsdb.define_table("store",
SQLField("sender", "string", length=20),
SQLField("fileno", "integer", length=20),
SQLField("totalno", "integer", length=20),
SQLField("partno", "integer", length=20),
SQLField("message", "string", length=160),
)
smsdb.commit()
def main (argv) :
""" Init GsmModem and do the rest """
try:
port = argv[0]
baudrate = argv[1]
global debug
debug = int(argv[2])
global posturl
posturl = argv[3]
global sahanapydatabase
sahanapydatabase = argv[4]
global branch
branch = argv[5]
except IndexError:
print argv
print "Please give the appropriate parameters"
exit()
"""
Database for the SMS dump
"""
global db
db = SQLDB(sahanapydatabase)
msg_group_type_opts = {
1:'Email',
2:'SMS',
3:'Both'
}
opt_msg_group_type = SQLTable(None, 'opt_msg_group_type',
db.Field('group_type', 'integer', notnull=True,
requires = IS_IN_SET(msg_group_type_opts),
default = 1,
label = 'Type',
represent = lambda opt: opt and msg_group_type_opts[opt]))
resource = 'sms_outbox'
table = 'msg_' + resource
db.define_table('msg_group', timestamp, uuidstamp, deletion_status,
Field('name', notnull=True),
opt_msg_group_type,
Field('comments', length=256),
migrate=migrate)
group_id = SQLTable(None, 'group_id',
Field('group_id', db.msg_group,
requires = IS_IN_DB(db, 'msg_group.id', 'msg_group.name'),
represent = lambda id: (id and [db(db.msg_group.id==id).select()[0].name] or ["None"])[0],
label = T('Group'),
comment = "None",
ondelete = 'RESTRICT'
))
db.define_table(table, timestamp, authorstamp, uuidstamp, deletion_status,
#Field('phone_number', 'integer', notnull=True),
group_id,
Field('contents', length=700), # length=140 omitted to handle multi-part SMS
#Field('smsc', 'integer'),
migrate=False)
db.define_table('msg_sms_sent', timestamp, authorstamp, uuidstamp, deletion_status,
#Field('phone_number', 'integer', notnull=True),
group_id,
Field('contents', length=700), # length=140 omitted to handle multi-part SMS
#Field('smsc', 'integer'),
migrate=False)
db.define_table('msg_sms_inbox', timestamp, uuidstamp, deletion_status,
Field('phone_number', 'integer', notnull=True),
Field('contents', length=700), # length=140 omitted to handle multi-part SMS
#Field('smsc', 'integer'),
migrate=migrate)
gsm = GsmModem(
port=port,
baudrate=int(baudrate))
app = ProcessorApp(gsm)
# app.command("AT+CNMI=1,1,0,0,0")
app.serve_forever()
class ProcessorApp(object):
def __init__(self, modem):
self.modem = modem
def command(self,msg,raise_error=False):
self.modem.command(msg,raise_error)
def serve_forever(self):
"""Block forever, polling the modem for new messages every
two seconds. When a message is received, pass it on to
the _incoming_ message for handling."""
global db
if debug:
print "Waiting for messages:"
boxdata = self.modem.query('AT+CMGD=?')
if "error" in boxdata.lower():
print "Error - phone not supported"
exit()
boxsize = int(boxdata.split("(")[1].split(")")[0].split("-")[1])
if debug:
print boxsize
cleanup = True
while True:
msg = self.modem.next_message()
if msg is not None:
cleanup = True
if debug:
print "Got Message: %r" % (msg.text)
print "From: %r " % (msg.sender)
try:
data = msg.text
meta = data.split("$")[0]
data = data.lstrip(meta+"$")
file = meta.split("&")[0].split("=")[1]
part = meta.split("&")[1].split("=")[1].split(",")[0]
total = meta.split("&")[1].split("=")[1].split(",")[1]
smsdb.store.insert(sender=msg.sender,fileno=file,partno=part,totalno=total,message=data)
smsdb.commit()
except:
"""If message is not sent from the j2me client it appears
here"""
db.msg_sms_inbox.insert(phone_number=msg.sender,contents=msg.text)
db.commit()
if debug > 4:
if msg.sender == "+919935648569":
msg.respond("Up and running captain")
if cleanup:
for i in range(boxsize): # For cleaning up the read messages.
try:
temp = self.modem.command('AT+CMGR=' + str(i+1)+',1')
if debug > 5:
print str(i+1) + ": "
print temp
if "REC READ" in temp[0]:
self.modem.query('AT+CMGD=' + str(i+1))
if debug > 3:
print "Deleted :" + str(i+1)
except:
pass
cleanup = False
# Check for parts in the smsdb - if done concatenate them and send
# them over to sahanapy
for row in smsdb().select(smsdb.store.ALL):
rowdone=False
rowmessage=""
for i in range(row.totalno):
q=smsdb((smsdb.store.sender==row.sender) & (smsdb.store.fileno==row.fileno) & (smsdb.store.partno==i+1)).select(smsdb.store.message,distinct=True)
if q:
rowdone = True
for morerows in q:
rowmessage = rowmessage + morerows.message
else:
rowdone = False
continue
if rowdone:
rowmessage = rowmessage.replace("@","@")
rowmessage = rowmessage.replace("#64;","@")
if debug > 1:
print rowmessage
try:
req = urllib2.Request(posturl,rowmessage,headers)
conn = urllib2.urlopen(req)
if debug > 4:
print conn.read()
smsdb(smsdb.store.fileno==row.fileno).delete()
conn.close()
except:
print "Error posting"
smsdb.commit()
# no messages? wait a couple of seconds
# (let's not blow up the modem), and retry
time.sleep(2)
if __name__ == "__main__":
""" This process is to be started as follows
python SerialWorker.py /dev/ttyUSB0 115200 0
http://127.0.0.1:8000/sahana/xforms/post databaselocation
Where 0 is the debug level"""
sys.exit(main(sys.argv[1:]))
|