More robust and stable
[ussd-widget] / ussd-common / src / usr / bin / ussdquery.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 ## This program is free software; you can redistribute it and/or modify
4 ## it under the terms of the GNU General Public License as published
5 ## by the Free Software Foundation; version 2 and higer.
6 ##
7 ## Guseynov Alexey (kibergus bark-bark gmail.com) 2010
8
9 import pexpect
10 import time
11 from subprocess import *
12 import sys
13 import gsmdecode
14 #print "argh"
15 #time.sleep(3000)
16 #sys.exit()
17 if len(sys.argv) != 2:
18     print "Usage: ussdquery.py <ussd number>"
19     sys.exit()
20
21 # Operations should timeout in 30 seconds.
22 # I'm not shure, that readline uses timeouts
23 child = None
24 response = ""
25 retry = 5
26 while response != "OK" and retry > 0 :
27         if child == None :
28                 # OK response should be recieved shortly
29                 child = pexpect.spawn('pnatd', [], 2)
30         try :
31                 child.send('at\r');
32                 # Read our "at" command
33                 child.readline();
34                 # Read OK response
35                 response = child.readline().strip()
36         except pexpect.TIMEOUT:
37                 child.kill(9)
38                 child = None
39                 response = ""
40         if response != "OK" :
41                 time.sleep(0.5)
42                 retry -= 1
43
44 child.timeout = 30
45
46 if response != "OK" :
47         print >> sys.stderr, "Couldn't init modem."
48         sys.exit (-1)
49
50 try :
51         child.send('at+cusd=1,"'+(sys.argv[1])+'",15\r')
52         # Read our query echoed back
53         child.readline()
54
55         #Read and parse reply
56         replystring = child.readline()
57         child.sendeof()
58 except pexpect.TIMEOUT:
59         print >> sys.stderr, "Timeout. Modem didn't reply."
60         sys.exit (-2)
61
62 if replystring.strip() == "ERROR" :
63         print >> sys.stderr, "Modem returned ERROR. Query not executed."
64         sys.exit (-3)
65
66 start = replystring.find('"')
67 end = replystring.find('"', start+1)
68 reply = replystring[start+1:end]
69 encoding = replystring[end+2:].strip()
70
71 # Decoding ansver
72 reply = gsmdecode.decode(reply, int(encoding))
73
74 print reply
75