Sunday, August 22, 2010

How I read the balance information from a 3G/GPRS data connection

For last few months I am using BSNL 3G internet connection. I am using a prepaid connection through USB 3G device. So, before and after every internet session I need to know the remaining balance of my sim card, but the device have no LCD screen/keypad. That is why every time I have to insert the sim card into a mobile to get the balance of the sim card.

Recently I have solve this problem. I have wrote a python code to get the balance of the sim card directly through USB 3G device. I have wrote a supporting shell script also to create GUI interface for that python code.

The only dependencies to run the code are Python and Zenity.

I have wrote the code for my BSNL 3G connection, and have to customise for other connection.
import sys
import serial
serial_device = serial.Serial(sys.argv[1],timeout=8)
except IndexError:
print "\nMobile Balance\n\nSyntax: /dev/ttyUSB[2..5]\n"
except serial.serialutil.SerialException:
print "\nUnable to open port",sys.argv[1],"\n"
while (1):
text_output = serial_device.readline()
if text_output.find('+CUSD')==0:
text_output = text_output.lstrip('+CUSD: 0,"')
print text_output.rstrip('",15\r\n')

PreviousBalance=`cat /tmp/mobile_balance.tmp`
python `echo $0 | sed 's/.sh/.py'/` `ls /dev/ttyUSB{2..5} 2>/dev/null` > /tmp/mobile_balance.tmp | zenity --info --text="Mobile balance calculation in progress\nClick 'OK' and\nWait for a while....."
echo -e "Current Balance\n"`cat /tmp/mobile_balance.tmp` "\n\nPrevious Balance..\n" $PreviousBalance | zenity --text-info --title="Mobile Balance" --width=250 --height=300