|
| 1 | +import subprocess |
| 2 | +import logging |
| 3 | +from io import StringIO |
| 4 | +import pandas |
| 5 | +import requests |
| 6 | +from datetime import datetime |
| 7 | +from time import sleep |
| 8 | +from pathlib import Path |
| 9 | +# |
| 10 | +URL='https://location.services.mozilla.com/v1/geolocate?key=test' |
| 11 | +NMCMD = ['nmcli','-g','SSID,BSSID,FREQ,SIGNAL','device','wifi'] # Debian stretch, Ubuntu 17.10 |
| 12 | +NMLEG = ['nmcli','-t','-f','SSID,BSSID,FREQ,SIGNAL','device','wifi'] # ubuntu 16.04 |
| 13 | +NMSCAN = ['nmcli','device','wifi','rescan'] |
| 14 | +HEADER='time lat lon accuracy NumBSSIDs' |
| 15 | + |
| 16 | + |
| 17 | +def logwifiloc(T:float, logfile:Path): |
| 18 | + |
| 19 | + if logfile: |
| 20 | + logfile = Path(logfile).expanduser() |
| 21 | + with logfile.open('a') as f: |
| 22 | + f.write(HEADER+'\n') |
| 23 | + |
| 24 | + |
| 25 | + print(f'updating every {T} seconds') |
| 26 | + print(HEADER) |
| 27 | + while True: |
| 28 | + loc = get_nmcli() |
| 29 | + if loc is None: |
| 30 | + sleep(T) |
| 31 | + continue |
| 32 | + |
| 33 | + stat = f'{loc["t"].strftime("%xT%X")} {loc["lat"]} {loc["lng"]} {loc["accuracy"]:.1f} {loc["N"]:02d}' |
| 34 | + print(stat) |
| 35 | + |
| 36 | + if logfile: |
| 37 | + with logfile.open('a') as f: |
| 38 | + f.write(stat+'\n') |
| 39 | + |
| 40 | + sleep(T) |
| 41 | + |
| 42 | + |
| 43 | +def get_nmcli(): |
| 44 | + |
| 45 | + |
| 46 | + ret = subprocess.check_output(NMLEG, universal_newlines=True) |
| 47 | + sleep(0.5) # nmcli crashed for less than about 0.2 sec. |
| 48 | + try: |
| 49 | + subprocess.check_call(NMSCAN) # takes several seconds to update, so do it now. |
| 50 | + except subprocess.CalledProcessError as e: |
| 51 | + logging.error(f'consider slowing scan cadence. {e}') |
| 52 | + |
| 53 | + dat = pandas.read_csv(StringIO(ret), sep=r'(?<!\\):', index_col=False, |
| 54 | + header=0, encoding='utf8', engine='python', |
| 55 | + dtype=str, usecols=[0,1,3], |
| 56 | + names=['ssid','macAddress','signalStrength']) |
| 57 | +# %% optout |
| 58 | + dat = dat[~dat['ssid'].str.endswith('_nomap')] |
| 59 | +# %% cleanup |
| 60 | + dat['ssid'] = dat['ssid'].str.replace('nan','') |
| 61 | + dat['macAddress'] = dat['macAddress'].str.replace(r'\\:',':') |
| 62 | +# %% JSON |
| 63 | + jdat = dat.to_json(orient='records') |
| 64 | + jdat = '{ "wifiAccessPoints":' + jdat + '}' |
| 65 | +# print(jdat) |
| 66 | +# %% cloud MLS |
| 67 | + try: |
| 68 | + req = requests.post(URL, data=jdat) |
| 69 | + if req.status_code != 200: |
| 70 | + logging.error(req.text) |
| 71 | + return |
| 72 | + except requests.exceptions.ConnectionError as e: |
| 73 | + logging.error(f'no network connection. {e}') |
| 74 | + return |
| 75 | +# %% process MLS response |
| 76 | + jres = req.json() |
| 77 | + loc = jres['location'] |
| 78 | + loc['accuracy'] = jres['accuracy'] |
| 79 | + loc['N'] = dat.shape[0] # number of BSSIDs used |
| 80 | + loc['t'] = datetime.now() |
| 81 | + |
| 82 | + return loc |
| 83 | +# %% |
| 84 | + |
| 85 | +def csv2kml(csvfn:Path, kmlfn:Path): |
| 86 | + from simplekml import Kml |
| 87 | + |
| 88 | + """ |
| 89 | + write KML track/positions |
| 90 | +
|
| 91 | + t: vector of times |
| 92 | + lonLatAlt: longitude, latitude, altitude or just lon,lat |
| 93 | + ofn: KML filename to create |
| 94 | + """ |
| 95 | + |
| 96 | + # lon, lat |
| 97 | + dat = pandas.read_csv(csvfn, sep=' ', index_col=0, header=0) |
| 98 | + |
| 99 | + t = dat.index.tolist() |
| 100 | + lla = dat.loc[:,['lon','lat']].values |
| 101 | +# %% write KML |
| 102 | + """ |
| 103 | + http://simplekml.readthedocs.io/en/latest/geometries.html#gxtrack |
| 104 | + """ |
| 105 | + kml = Kml(name='My Kml',open=1) |
| 106 | + |
| 107 | + |
| 108 | + doc = kml.newdocument(name='Mozilla Location Services') |
| 109 | + fol = doc.newfolder(name='Tracks') |
| 110 | + trk = fol.newgxtrack(name='My Track') |
| 111 | + trk.newwhen(t) # list of times |
| 112 | + trk.newgxcoord(lla.tolist()) #list of lon,lat,alt, NOT ndarray! |
| 113 | + |
| 114 | +# just a bunch of points |
| 115 | +# for i,p in enumerate(lla): # iterate over rows |
| 116 | +# kml.newpoint(name=str(i), coords=[p]) |
| 117 | + |
| 118 | + print('writing', kmlfn) |
| 119 | + kml.save(kmlfn) |
0 commit comments