Use BSSC-BSIC as the unique cell identifier instead of the non-unique cellid.
[CellLocator.git] / gsmpos / gsmpos_server.py
blobac922c82def91ff0c4069be41e19823cb128aedb
1 #!/usr/bin/env python
2 """
3 GSM Positioning
5 (C) 2008 Gergely Imreh <imrehg@gmail.com>
6 --- using code from:
7 cell_locator: Baruch Even <baruch@ev-en.org>
9 GPLv3 or later
10 """
11 """
13 Uses input file: cellinfo.dat
14 Contain : Locations of known cells
15 Format : comma-separated values
16 Fields : mmc,mnc,cell_id,lattitude,longitude
18 """
21 import sys, os, serial, time, dbus, csv
22 from time import strftime
23 from math import *
24 import sqlite3
25 ### GPS import functions from stripped down version of cell_locator.py
26 from cell_locator_bare import Terminal
27 from cell_locator_bare import GPS
28 from gsmpos import *
30 __version__ = '0.2'
33 ###############
35 # Debugging output
36 debug = False
38 ################
41 def nmealocform(pos,padd=2):
42 """ Convert location into NMEA format """
43 if pos == '':
44 nmeapos = ''
45 else :
46 a = int(pos)
47 b = (pos-a)*60.0
48 nmeapos = str(a).zfill(padd)+'%02.5f'%b
49 return nmeapos
51 def nmeasentence(gsmpos,hdop=99):
52 """ Prepare minimal information needed for tangoGPS location display """
53 """ Shows: location, date, time, number of seen/known towers (at seen/fixed satellite fields """
54 """ for info on sentences: http://gpsd.berlios.de/NMEA.txt and check gpsd output """
56 nmeatime = strftime("%H%M%S.00")
57 nmeadate = strftime("%d%m%y")
59 lon = gsm.lon
60 lat = gsm.lat
61 numfixtower = gsm.numtower
62 numtottower = gsm.tottower
64 if (lon == None) or (lat == None):
65 ## When no GSM position: send 'Navigation device warning' and 'no fix' sentences
66 sentence = "$GPRMC,"+nmeatime+",V,,,,,0.0,0.0,"+nmeadate+",,\n"
67 sentence += '$GPGGA,'+strftime("%H%M%S.00")+',,,,,0,,,0,M,0,M,,\n'
68 sentence += "$GPGSV,1,0,,,,,,,,,,,,,,,,,\n"
69 else:
70 if (lon >= 0):
71 ew = "E"
72 printlon = nmealocform(lon,3)
73 else:
74 ew = "W"
75 printlon = nmealocform(-1*lon,3)
76 if (lat >= 0):
77 ns = "N"
78 printlat = nmealocform(lat,2)
79 else:
80 ns = "S"
81 printlat = nmealocform(-1*lat,2)
82 sentence = ''
83 sentence += "$GPRMC,"+nmeatime+",A,"+printlat+","+ns+","+printlon+","+ew+",0.0,0.0,"+nmeadate+",,\n"
84 sentence += '$GPGGA,'+strftime("%H%M%S.00")+','+printlat+','+ns+','+printlon+','+ew+',1,'+str(numfixtower)+','+str(hdop)+',0,M,0,M,,\n'
85 sentence += "$GPGSV,1,1,"+str(numtottower)+",,,,,,,,,,,,,,,,\n"
87 return sentence
89 def addtangogpsdatabase():
90 """ Adding known cell towers to tangoGPS POI database """
91 """ Tagged as Services/Other, with a common keywords field for easy fitering """
92 import sqlite3
94 cells = loadcellinfo('cellinfo.dat')
95 try:
96 conn = sqlite3.connect('/.tangogps/poi.db')
97 c = conn.cursor()
98 # First delete everything, clean start every time
99 c.execute('delete from poi where keywords like "gsmpos%"')
100 for cline in cells:
101 lat = cline['lat']
102 lon = cline['lon']
103 comment = 'MCC: '+str(cline['mcc'])+', MNC:'+str(cline['mnc'])
104 key = 'gsmpos CellID '+str(cline['cell_id'])
105 indat = (lat,lon,key,comment,1,10,6,3,0)
106 c.execute('insert into poi (lat,lon,keywords,desc,visibility,cat,subcat,price_range,extended_open) values (?,?,?,?,?,?,?,?,?)', indat)
107 except:
108 etype = sys.exc_info()[0]
109 evalue = sys.exc_info()[1]
110 etb = sys.exc_info()[2]
111 print "tangoGPS POI Add Error: ", str(etype), " : ", str(evalue) , ' : ', str(etb)
112 finally:
113 conn.commit()
114 c.close()
117 if __name__ == "__main__":
119 cells = loadcellinfo('cellinfo.dat')
121 from dbus.mainloop.glib import DBusGMainLoop
122 DBusGMainLoop(set_as_default=True)
124 import gobject
125 loop = gobject.MainLoop()
127 # Start GPS
128 gps = GPS()
129 gps.init()
131 t = Terminal()
132 t.open()
134 # Init GSM position storage
135 gsm = GSMpos()
137 # Adding known cells to tangoGPS POI database
138 addtangogpsdatabase()
140 ##################
141 # Quick and dirty server section
142 #################
143 import socket
145 ##########
146 HOST = 'localhost'
147 PORT = 2940
148 ##########
150 s = None
151 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
152 af, socktype, proto, canonname, sa = res
153 try:
154 s = socket.socket(af, socktype, proto)
155 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Important for using again after unexpected crash!
156 except socket.error, msg:
157 s = None
158 continue
159 try:
160 s.bind(sa)
161 s.listen(1)
162 except socket.error, msg:
163 s.close()
164 s = None
165 continue
166 break
168 if s is None:
169 print 'could not open socket'
170 sys.exit(1)
171 while 1:
172 print "Awaiting connection..."
173 run = 1
174 try:
175 conn, addr = s.accept()
176 except:
177 break
179 print 'Connected by', addr
180 while 1:
182 try :
183 # If manual connection, have to press a button to start, tangoGPS automatic
184 data = conn.recv(1024)
185 except:
186 conn.close()
187 run = 0
189 if data:
190 while 1:
191 try:
192 looping(t,gsm,cells)
193 nmeaout = nmeasentence(gsm)
194 print nmeaout
195 conn.send(nmeaout)
196 time.sleep(2.0)
197 except (KeyboardInterrupt, SystemExit):
198 conn.close()
199 print "KeyboardInterrupt - Clean Exit"
200 run = 0
201 break
202 except :
203 conn.close()
204 print "Exception:", sys.exc_type, ":", sys.exc_value
205 run = 0
206 break
207 else:
208 break
209 print "Level 2"
210 if run ==0 : break
211 print "Level 1"
212 if run ==0 : break
213 print "Level 0"
216 # Closing down
217 print "Closing GSM"
218 t.close()
219 print "Closing GPS - wait for it!!"
220 gps.uninit()