from subprocess import *
import sys
import gsmdecode
-
+#print "argh"
+#time.sleep(3000)
+#sys.exit()
if len(sys.argv) != 2:
print "Usage: ussdquery.py <ussd number>"
sys.exit()
# Operations should timeout in 30 seconds.
# I'm not shure, that readline uses timeouts
-child = pexpect.spawn('pnatd', [], 30);
-child.send('at\r');
-# Read our "at" command
-child.readline();
-# Read OK response
-child.readline();
-
-child.send('at+cusd=1,"'+(sys.argv[1])+'",15\r');
-# Read our query echoed back
-child.readline();
-
-#Read and parse reply
-replystring = child.readline();
-start = replystring.find('"');
-end = replystring.find('"', start+1);
-reply = replystring[start+1:end];
-encoding = replystring[end+2:].strip();
-
-child.sendeof();
+child = None
+response = ""
+retry = 5
+while response != "OK" and retry > 0 :
+ if child == None :
+ # OK response should be recieved shortly
+ child = pexpect.spawn('pnatd', [], 2)
+ try :
+ child.send('at\r');
+ # Read our "at" command
+ child.readline();
+ # Read OK response
+ response = child.readline().strip()
+ except pexpect.TIMEOUT:
+ child.kill(9)
+ child = None
+ response = ""
+ if response != "OK" :
+ time.sleep(0.5)
+ retry -= 1
+
+child.timeout = 30
+
+if response != "OK" :
+ print >> sys.stderr, "Couldn't init modem."
+ sys.exit (-1)
+
+try :
+ child.send('at+cusd=1,"'+(sys.argv[1])+'",15\r')
+ # Read our query echoed back
+ child.readline()
+
+ #Read and parse reply
+ replystring = child.readline()
+ child.sendeof()
+except pexpect.TIMEOUT:
+ print >> sys.stderr, "Timeout. Modem didn't reply."
+ sys.exit (-2)
+
+if replystring.strip() == "ERROR" :
+ print >> sys.stderr, "Modem returned ERROR. Query not executed."
+ sys.exit (-3)
+
+start = replystring.find('"')
+end = replystring.find('"', start+1)
+reply = replystring[start+1:end]
+encoding = replystring[end+2:].strip()
# Decoding ansver
reply = gsmdecode.decode(reply, int(encoding))
-print reply;
+print reply