8
8
Uses ``nmcli`` from Linux only. Could be extended to other tools and OS.
9
9
"""
10
10
import subprocess
11
+ import logging
11
12
from io import BytesIO
12
13
import pandas
13
14
import requests
14
15
from datetime import datetime
15
16
from time import sleep
16
17
17
18
URL = 'https://location.services.mozilla.com/v1/geolocate?key=test'
19
+ NMCMD = ['nmcli' ,'-fields' ,'BSSID,FREQ,SIGNAL' ,'device' ,'wifi' ]
20
+ NMSCAN = ['nmcli' ,'device' ,'wifi' ,'rescan' ]
18
21
19
- def get_nmcli ():
20
22
21
- cmd = ['nmcli' ,'-fields' ,'BSSID,FREQ,SIGNAL' ,'device' ,'wifi' ]
22
- ret = subprocess .check_output (cmd )
23
+ def get_nmcli ():
23
24
25
+
26
+ ret = subprocess .check_output (NMCMD )
27
+ sleep (0.5 ) # nmcli crashed for less than about 0.2 sec.
28
+ try :
29
+ subprocess .check_call (NMSCAN ) # takes several seconds to update, so do it now.
30
+ except subprocess .CalledProcessError as e :
31
+ print ('consider slowing scan cadence. {}' .format (e ))
32
+
24
33
dat = pandas .read_csv (BytesIO (ret ), sep = '\s+' , index_col = False ,
25
34
header = 0 ,usecols = [0 ,1 ,3 ],
26
35
names = ['macAddress' ,'frequency' ,'signalStrength' ])
36
+ # %% JSON
27
37
jdat = dat .to_json (orient = 'records' )
28
38
jdat = '{ "wifiAccessPoints":' + jdat + '}'
29
39
# print(jdat)
30
- req = requests .post (URL , data = jdat )
31
- if req .status_code != 200 :
32
- raise RuntimeError (ret .text )
40
+ # %% cloud MLS
41
+ try :
42
+ req = requests .post (URL , data = jdat )
43
+ if req .status_code != 200 :
44
+ logging .error (ret .text )
45
+ except requests .exceptions .ConnectionError as e :
46
+ logging .error ('no network connection. {}' .format (e ))
47
+ # %% process MLS response
48
+ jres = req .json ()
49
+ loc = jres ['location' ]
50
+ loc ['accuracy' ] = jres ['accuracy' ]
51
+ loc ['N' ] = dat .shape [0 ] # number of BSSIDs used
52
+ loc ['t' ] = datetime .now ()
53
+
54
+ return loc
33
55
34
- return req .json ()
35
56
36
57
if __name__ == '__main__' :
37
58
"""
@@ -45,20 +66,20 @@ def get_nmcli():
45
66
p .add_argument ('logfile' ,help = 'logfile to append location to' ,nargs = '?' )
46
67
p = p .parse_args ()
47
68
48
- T = 60 # fastest allowed polling cadence is 1 minute
69
+ T = 25 # nmcli fastest allowed polling cadence: crashes at 20 sec. OK at 25 sec?
49
70
50
71
logfile = p .logfile
51
72
52
73
print ('updating every {} seconds' .format (T ))
53
74
while True :
54
- ret = get_nmcli ()
55
- loc = ret [ 'location' ]
56
- stat = '{} {} {} {}' .format (datetime . now () .strftime ('%xT%X' ),
57
- loc ['lat' ], loc ['lng' ], ret ['accuracy' ])
75
+ loc = get_nmcli ()
76
+
77
+ stat = '{} {} {} {} {} ' .format (loc [ 't' ] .strftime ('%xT%X' ),
78
+ loc ['lat' ], loc ['lng' ], loc ['accuracy' ], loc [ 'N ' ])
58
79
print (stat )
59
80
60
81
if logfile :
61
82
with open (logfile ,'a' ) as f :
62
83
f .write (stat + '\n ' )
63
84
64
- sleep (T )
85
+ sleep (T )
0 commit comments