More robust and stable
[ussd-widget] / ussd-common / src / usr / bin / ussdquery.py
index c67de52..e374680 100755 (executable)
@@ -10,41 +10,66 @@ import pexpect
 import time
 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();
-
-# Check if we need to decode answer
-# Compressed messages are not supported yet
-if encoding == '86':
-    reply = reply.decode("hex")
-elif encoding == '72':
-    reply = reply.decode("hex")
-    p = Popen(['iconv', '-f', 'UCS-2BE', '-t', 'UTF8'], stdin=PIPE, stdout=PIPE);
-    reply = p.communicate(reply)[0]
-
-print reply;
+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