Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2011
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.15 KB | None | 0 0
  1. #!/usr/bin/python
  2. # vim:fileencoding=utf-8
  3. #
  4. # Hacked by Phillip Berndt, www.pberndt.com
  5. #
  6. import gtk
  7. import glib
  8. import sys
  9. import serial
  10. import time
  11.  
  12. # Functions for PDU en-/decoding
  13. def pduDecode(text):
  14.     pad = lambda number: number + "0" * (8 - len(number))
  15.     data = "".join([ pad("".join(reversed(bin(ord(c))[2:]))) for c in text.decode("hex") ])
  16.     output = ""
  17.     while len(data) >= 7:
  18.         output += chr(int("".join(reversed(data[:7])), 2))
  19.         data = data[7:]
  20.     return output
  21.  
  22. def pduDecodeSMS(text):
  23.     text = text[2 + int(text[:2], 16) * 2:] # Skip SMSC
  24.     text = text[2:] # Skip info
  25.     #text = text[2:] # Skip reference
  26.     text = text[2 + (int(text[:2], 16) + int(text[:2], 16) % 2) + 2:] # Skip telephone number
  27.     text = text[2:] # Skip protocol
  28.     text = text[2:] # Skip data coding scheme
  29.     text = text[14:] # Skip date
  30.     text = text[2:] # Skip content length
  31.     return pduDecode(text)
  32.  
  33. def pduEncode(text):
  34.     pad = lambda number: number + "0" * (7 - len(number))
  35.     binrep = ""
  36.     while text:
  37.         binrep += pad("".join(reversed(bin(ord(text[0]) & ~(1<<7))[2:])))
  38.         text = text[1:]
  39.     output = ""
  40.     while len(binrep) >= 8:
  41.         output += chr(int("".join(reversed(binrep[:8])), 2)).encode("hex")
  42.         binrep = binrep[8:]
  43.     if binrep:
  44.         binrep = "".join(reversed(binrep))
  45.         output += chr(int(binrep, 2)).encode("hex")
  46.     return output.upper()
  47.  
  48. # Function to show „action pending“ message
  49. def doPendingDialog():
  50.     dlg = gtk.MessageDialog(wnd)
  51.     dlg.set_markup("Waiting for response from the dongle")
  52.     progress = gtk.ProgressBar()
  53.     dlg.vbox.add(progress)
  54.     def do_pulse(*w):
  55.         if progress.get_window() is None:
  56.             return False
  57.         progress.pulse()
  58.         return True
  59.     glib.timeout_add(100, do_pulse)
  60.     dlg.set_modal(True)
  61.     dlg.show_all()
  62.     return dlg
  63.  
  64. # Function to show error dialog
  65. def doError(message):
  66.     dlg = gtk.MessageDialog()
  67.     dlg.set_markup(message)
  68.     dlg.set_title("Error")
  69.     dlg.add_button("Ok", gtk.RESPONSE_OK)
  70.     dlg.run()
  71.     sys.exit(1)
  72.  
  73. # Function to ask for sth
  74. def doAsk(question):
  75.     dlg = gtk.MessageDialog()
  76.     dlg.set_markup(question)
  77.     dlg.set_title("Question")
  78.     entry = gtk.Entry()
  79.     dlg.vbox.add(entry)
  80.     entry.show()
  81.     dlg.add_button("Ok", gtk.RESPONSE_OK)
  82.     dlg.add_button("Cancel", gtk.RESPONSE_CANCEL)
  83.     if dlg.run() == gtk.RESPONSE_CANCEL:
  84.         dlg.destroy()
  85.         return False
  86.     retVal = entry.get_text()
  87.     dlg.destroy()
  88.     return retVal
  89.  
  90. def sendNWait(send):
  91.     usbTTY.write(send + "\r\n")
  92.     usbTTY.flush()
  93.     globals()["pending"] = doPendingDialog()
  94.  
  95. def ttyReceivedCallback(source, condition):
  96.     if condition != glib.IO_IN:
  97.         doError("Connection to dongle lost")
  98.     textInput = usbTTY.readline().strip()
  99.     print textInput
  100.  
  101.     if "cmglMode" in globals():
  102.         if textInput[0:2] == "AT": return True
  103.         if textInput == "": return True
  104.         if textInput[:5] == "+CMGL":
  105.             msgNo = textInput[7:textInput.find(",")]
  106.             appendText("Message no. " + msgNo + " follows:")
  107.             return True
  108.         if textInput == "OK":
  109.             del globals()["cmglMode"]
  110.             if "pending" in globals():
  111.                 globals()["pending"].destroy()
  112.                 del globals()["pending"]
  113.             appendText("No further messages")
  114.             appendText("")
  115.         else:
  116.             try:
  117.                 appendText(" * " + pduDecodeSMS(textInput))
  118.             except:
  119.                 appendText("Did not understand " + textInput)
  120.         return True
  121.    
  122.     if len(textInput) == 0 or textInput[0] != "+":
  123.         # Not of interest for us
  124.         return True
  125.  
  126.     if "pending" in globals():
  127.         globals()["pending"].destroy()
  128.         del globals()["pending"]
  129.  
  130.     if textInput[0:5] == "+CPIN":
  131.         result = textInput[7:]
  132.         if result != 'READY':
  133.             pin = doAsk("The card asks for " + result)
  134.             if pin == False:
  135.                 sys.exit(1)
  136.             sendNWait('AT+CPIN="' + pin + '"')
  137.             usbTTY.flush()
  138.             def send_ask_pin(*w):
  139.                 usbTTY.write("AT+CPIN?\r\n")
  140.                 return False
  141.             glib.timeout_add(300, send_ask_pin)
  142.         else:
  143.             appendText("Pin ok; dongle accessible")
  144.             usbTTY.write("AT+CNUM\r\n")
  145.             usbTTY.flush()
  146.             usbTTY.write("AT+CMGF=0\r\n")
  147.             usbTTY.flush()
  148.             usbTTY.write("AT+CNMI=1,1,0,0,0\r\n")
  149.         return True
  150.    
  151.     if textInput[0:5] == "+CUSD":
  152.         textInput = textInput[textInput.find('"') + 1:textInput.rfind('"')]
  153.         appendText(pduDecode(textInput))
  154.         appendText("")
  155.    
  156.     if textInput[:5] == "+CNUM":
  157.         textInput = textInput[10:]
  158.         textInput = textInput[textInput.find('"') + 1:textInput.rfind('"')]
  159.         appendText("Own phone number is " + textInput)
  160.         appendText("")
  161.    
  162.     if textInput[:5] == "+CMTI":
  163.         appendText("A new text message has arrived!")
  164.  
  165.     return True
  166.  
  167. # Open TTY
  168. try:
  169.     usbTTY = serial.Serial("/dev/ttyUSB3")
  170.     glib.io_add_watch(usbTTY.fileno(), glib.IO_IN | glib.IO_ERR, ttyReceivedCallback)
  171. except:
  172.     doError("Failed to upen USB-tty. Make sure to have the dongle attached, <i>/dev/ttyUSB3</i> accessible " +
  173.         "and the <i>usbserial</i> module loaded")
  174.  
  175.  
  176. # Create main window
  177. wnd = gtk.Window()
  178. wnd.set_title("USB UMTS dongle recharge tool")
  179. wnd.set_size_request(640, 240)
  180. hbox = gtk.HBox()
  181. vbox = gtk.VBox()
  182. textView = gtk.TextView()
  183. textView.set_editable(False)
  184. textView.set_cursor_visible(False)
  185. textView.set_size_request(440, 240)
  186. textView.set_wrap_mode(gtk.WRAP_WORD)
  187. buffer = textView.get_buffer()
  188. def appendText(text):
  189.     buffer.insert(buffer.get_end_iter(), text.strip() + "\n")
  190.     textView.scroll_to_iter(buffer.get_end_iter(), 0.25)
  191. checkButton = gtk.Button("Check balance")
  192. def checkAction(widget):
  193.     appendText("Sending request for balance check")
  194.     sendNWait('AT+CUSD=1,"' + pduEncode("*101#") + '",15')
  195. checkButton.connect("clicked", checkAction)
  196. rechargeButton = gtk.Button("Recharge")
  197. def rechargeAction(widget):
  198.     code = doAsk("Enter recharge code:")
  199.     if code == False: return
  200.     appendText("Sending recharge-request")
  201.     sendNWait('AT+CUSD=1,"' + pduEncode("*103*" + code + "#") + '",15')
  202. rechargeButton.connect("clicked", rechargeAction)
  203. readTextButton = gtk.Button("Read new text messages")
  204. def readTextAction(widget):
  205.     appendText("Receiving text messages")
  206.     sendNWait("AT+CMGL")
  207.     globals()["cmglMode"] = True
  208. readTextButton.connect("clicked", readTextAction)
  209. readAllTextButton = gtk.Button("Read all text messages")
  210. def readAllTextAction(widget):
  211.     appendText("Receiving text messages")
  212.     sendNWait("AT+CMGL=4")
  213.     globals()["cmglMode"] = True
  214. readAllTextButton.connect("clicked", readAllTextAction)
  215. deleteTextButton = gtk.Button("Delete a text message")
  216. def deleteTextAction(widget):
  217.     delw = doAsk("Enter message no. to be deleted")
  218.     if delw == False: return True
  219.     usbTTY.write("AT+CMGD=" + delw + "\r\n")
  220. deleteTextButton.connect("clicked", deleteTextAction)
  221. sendCusdButton = gtk.Button("Send CUSD")
  222. def sendCusdAction(widget):
  223.     cusd = doAsk("CUSD to send: (e.g. *101#)")
  224.     if cusd == False:
  225.         return
  226.     sendNWait('AT+CUSD=1,"' + pduEncode(cusd) + '",15')
  227. sendCusdButton.connect("clicked", sendCusdAction)
  228. wnd.connect("hide", lambda *f: gtk.main_quit())
  229. hbox.add(vbox)
  230. hbox.pack_end(textView, padding=5)
  231. vbox.pack_start(checkButton, False, padding=3)
  232. vbox.pack_start(rechargeButton, False, padding=3)
  233. vbox.pack_start(readTextButton, False, padding=3)
  234. vbox.pack_start(readAllTextButton, False, padding=3)
  235. vbox.pack_start(deleteTextButton, False, padding=3)
  236. vbox.pack_start(sendCusdButton, False, padding=3)
  237. wnd.add(hbox)
  238. wnd.show_all()
  239. usbTTY.write("ATZ\r\n")
  240. sendNWait("AT+CPIN?")
  241.  
  242. # Run
  243. gtk.main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement