Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
70 commits
Select commit Hold shift + click to select a range
5e3ccec
Changed based on code review
phurbawl Jun 16, 2015
bfa6f06
Fixed errors
phurbawl Jun 19, 2015
4bc06ba
Added check_airplane_mode
phurbawl Jun 19, 2015
277d6a6
Added check_ringer_silent_mode
phurbawl Jun 19, 2015
826a50c
Edited docstrings, Added modules
phurbawl Jun 19, 2015
22ff1c7
Removed duplicated get_max_media_volume func
phurbawl Jun 19, 2015
c2f4787
Changed spacing, indentation
Jun 19, 2015
d0015ce
fixed errors - cellular interface
phurbawl Jun 21, 2015
3cf9757
Merge with SensibilityTestbed/sensorlib
phurbawl Jun 23, 2015
96400a2
Merge branch 'SensibilityTestbed/master'
phurbawl Jun 23, 2015
9366d22
Merge branch 'SensibilityTestbed/master'
phurbawl Jun 24, 2015
fc22431
Merge branch 'SensibilityTestbed/master'
phurbawl Jun 24, 2015
e14bda3
changes based on test results for sensor interface
phurbawl Jun 24, 2015
daa9ac2
Merge branch 'SensibilityTestbed/master'
phurbawl Jun 30, 2015
3d3c777
added comments and docstrings
phurbawl Jun 30, 2015
45dd14b
Merge branch 'SensibilityTestbed/master'
phurbawl Jul 3, 2015
90cfeb1
reduced file downloads
phurbawl Jul 6, 2015
7a46011
changes based on comments
phurbawl Jul 6, 2015
e26f310
blur to zipped
phurbawl Jul 6, 2015
18bf4d8
improve blurring accuracy
phurbawl Jul 7, 2015
c0d51c9
update to match database changes
phurbawl Jul 7, 2015
c5da8c7
update to match database changes
phurbawl Jul 7, 2015
6d148db
Merge branch 'SensibilityTestbed/master'
phurbawl Jul 14, 2015
4ab87c9
changes to match city and state blur layers
phurbawl Jul 14, 2015
da90586
refactored common parts into blur_helper
phurbawl Jul 14, 2015
cd41777
changed name to location_blur_helper
phurbawl Jul 21, 2015
d755d5a
changes based on comments
phurbawl Jul 21, 2015
d75e072
handle get_location() returning None
phurbawl Jul 21, 2015
edf2a2f
removed try..except block, added docstrings
phurbawl Jul 25, 2015
b834885
changed "quadrilateral" to "cell" in comment
phurbawl Jul 25, 2015
bc08379
Merge branch 'SensibilityTestbed/master'
phurbawl Jul 28, 2015
a820f92
getsensor conflict fix
phurbawl Jul 28, 2015
bcb0828
deleted errors due to previous commit
phurbawl Jul 28, 2015
59aba85
changes based on media interface test
phurbawl Jul 28, 2015
b27c782
Merge branch 'SensibilityTestbed/master'
phurbawl Aug 17, 2015
bad339a
removed exception checking
phurbawl Aug 17, 2015
788efdb
Removed +1 in sleep()
Aug 20, 2015
ac1a6fe
change based on code review
phurbawl Jun 16, 2015
faf8f4f
add battery calls
yyzhuang Jun 19, 2015
ec5052f
fix a typo
yyzhuang Jun 20, 2015
00c6c1b
add bluetooth call
yyzhuang Jun 20, 2015
0bb86b7
add cellular call
yyzhuang Jun 21, 2015
c8c484a
fix typos
yyzhuang Jun 22, 2015
217a61c
add settings interface
yyzhuang Jun 23, 2015
4a7f3fd
scrub unicode
yyzhuang Jun 23, 2015
eb22c94
add sensor calls
yyzhuang Jun 24, 2015
8f3ea85
adjust vibration mode
yyzhuang Jun 24, 2015
3c405cc
fix typos
yyzhuang Jun 25, 2015
561b751
add comments and docstrings
phurbawl Jun 30, 2015
f530438
add encasementlib
yyzhuang Jun 30, 2015
0d64f45
update readme
yyzhuang Jun 30, 2015
fd6fd5a
update readme with git marup
yyzhuang Jun 30, 2015
7aaaf39
remove dup code
yyzhuang Jul 1, 2015
384c094
add geocode call
yyzhuang Jul 2, 2015
599c559
change method to find closest state (reduce file downloads)
phurbawl Jul 6, 2015
1b1e462
blur to zipcode area
phurbawl Jul 6, 2015
b4dd0a3
add function to lookup by state name (improve accuracy)
phurbawl Jul 7, 2015
c01e680
change double to float in geocode
yyzhuang Jul 7, 2015
64ed85c
change to match city and state blur layers
phurbawl Jul 14, 2015
3124a4e
refactor common parts into location_blur_helper
phurbawl Jul 14, 2015
be9b9fa
order sensors alphebatically
yyzhuang Jul 25, 2015
8d79ea5
add media calls
yyzhuang Jul 27, 2015
fafacd5
fix arg type
yyzhuang Jul 28, 2015
f26effb
add TTS interface
yyzhuang Jul 31, 2015
6fdae97
add error handling in reading sensor
yyzhuang Jul 31, 2015
601e553
refactor blur to city
yyzhuang Aug 2, 2015
5e0db35
fix single arg list type
yyzhuang Aug 7, 2015
cd4085c
raise exp instead of log
yyzhuang Aug 11, 2015
b26f62a
remove exception checking
phurbawl Aug 17, 2015
317dfcc
Merge remote-tracking branch 'origin/master'
phurbawl Aug 26, 2015
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion blur_location2city.r2py
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,4 @@ CHILD_CONTEXT_DEF["get_lastknown_location"] = {


# Dispatch.
secure_dispatch_module()
secure_dispatch_module()
322 changes: 154 additions & 168 deletions blur_location2country.r2py
Original file line number Diff line number Diff line change
@@ -1,185 +1,167 @@
httpretrieve = dy_import_module("httpretrieve.r2py")
math = dy_import_module("math.r2py")
librepyfile = dy_import_module("librepyfile.r2py")

statefilename = "states.txt" # Database of states
countryfilename = "countries.txt" # Database of countries


# Downloads the required file from the server
def get_file_from_server(filename):

if filename not in listfiles(): # In case it already exists
if filename not in [statefilename, countryfilename]:
url = "http://sensibilityclearinghouse.poly.edu/data/quad/" + filename
else:
url = "http://sensibilityclearinghouse.poly.edu/data/" + filename
httpretrieve.httpretrieve_save_file(url, filename)


# Returns a dictionary containing information about the point closest to
# a given lat/lng pair, from the database.
# {"city": closest_city, "statecode": closest_state_code, "countrycode":
# closest_country_code, "coordinates": closest_point}
def find_closest_point(lat, lng):

# Find the database file with coordinates closest to the given lat/lng pair
filename = get_filename(lat, lng)
# Get the list of coordinates from that file
listofpoints = load_lat_lng_from_file(filename)

min_dist = 9999
point1 = (lat, lng)

for city in listofpoints.keys():
data = listofpoints[city]
point2 = (data[0], data[1])
dist = find_distance(point1, point2)
if dist < min_dist:
min_dist = dist
closest_point = point2
closest_city = city
closest_state_code = data[3]
closest_country_code = data[2]

closest = {"city": closest_city, "statecode": closest_state_code, "countrycode": closest_country_code, "coordinates": closest_point}

return closest


# Returns the filename in the database with coordinates closest to the given
# lat/lng pair
def get_filename(lat, lng):

# get ceiling as x/y index
x = int(math.math_ceil(lat))
y = int(math.math_ceil(lng))
filename = str(x) + '_' + str(y) + '.txt'
return filename


# Returns a dictionary containing all the cities in the given file, along with
# their corresponding data
# {city1: [lat, lng, country_code, state_code], city2: [lat, lng, country_code,
# state_code], ...}
def load_lat_lng_from_file(filename):

get_file_from_server(filename)
listofpoints = {}
fileobj = librepyfile.open(filename, "r")

while True:
try:
line = fileobj.next().strip()
except StopIteration:
break
else:
line = line.split("\t")
city_name = line[0]
lat = line[1]
lng = line[2]
country_code = line[3]
state_code = line[4]
listofpoints[city_name] = [lat, lng, country_code, state_code]
fileobj.close()
return listofpoints


# Returns the distance between two lat/lng points
def find_distance(p1, p2):

(lat1, lng1) = p1
(lat2, lng2) = p2
lat2 = float(lat2)
lng2 = float(lng2)
lat_diff = (lat1-lat2) * (lat1-lat2)
lng_diff = (lng1-lng2) * (lng1-lng2)
# return squared distance
return lat_diff + lng_diff


# To replace get_location()
def get_country_location():

try:
location_data = get_location()
except Exception: # Not able to use LocationNotFoundException here
raise Exception
"""
A security layer for the functions get_location() and get_lastknown_location()
defined in getsensor.r2py. This program blurs the latitude/longitude
coordinates, received from the location sensors of an Android device,
to the geographic center of the country to which it belongs.

The blurring is done using a database lookup method. First, we use the
get_geolocation() call to get the current address. The country code in
the address returned is then used to find a match in the database
"countries.txt", which is a list of all countries and their geodata.
This database file is located at:
http://sensibilityclearinghouse.poly.edu/data/countries.txt

Usage:
start dylink.r2py encasementlib.r2py sensor_layer.r2py \
blur_location2country.r2py user-program.r2py
"""



location_blur_helper = dy_import_module("location_blur_helper.r2py")
country_filename = "countries.txt"



def load_country_geodata(address):
"""
Loads the country (or countries) and corresponding geodata from the
given file into a dictionary.

Below is an example of a line from the file "countries.txt" with
fields - country code, country name, latitude and longitude:
US United States 39.76 -98.5

The dictionary returned has the format:
{
country1: {"latitude": latitude, "longitude": longitude},
country2: {"latitude": latitude, "longitude": longitude},
...
}

"""
# Download the file from the country database.
location_blur_helper.get_country_file_from_server(country_filename)
# Obtain the list of countries and their geodata from the file.
countries_geodata = location_blur_helper.read_data_from_file(country_filename)

country_dict = {}

# Check if we can match the country code in the given address to that
# in the database. If there is a match, return a dict with that
# country and its geodata.
for line in countries_geodata:
# Ignore the empty line at the end of the file.
if line == "":
continue
country_geodata_record = line.split("\t")
if address["country_code"] == country_geodata_record[0]:
country_name = country_geodata_record[1]
country_dict[country_name] = {
"latitude": float(country_geodata_record[2]),
"longitude": float(country_geodata_record[3])
}
return country_dict

# If no match, return a dict of all countries and their geodata to
# find the closest country.
for line in countries_geodata:
# Ignore the empty line at the end of the file.
if line == "":
continue
country_geodata_record = line.split("\t")
country_name = country_geodata_record[1]
country_dict[country_name] = {
"latitude": float(country_geodata_record[2]),
"longitude": float(country_geodata_record[3]),
}

return country_dict


def find_closest_country(lat, lon):
"""
Finds the country closest to the given latitude/longitude pair from the
dictionary of countries returned by the load_country_geodata() function,
and returns that country's geodata in the format:
{
"country_name": country name (string),
"latitude": latitude of the center of the country (float)
"longitude": longitude of the center of the country (float)
}

Note: If the load_country_geodata() function returns only one country,
which happens when the country code from the get_geolocation() call
was successfully matched with one of the countries' code in the database,
then only that country's geodata is returned in the dictionary.

"""
# Get the address for the given coordinates. Since get_geolocation()
# can possibly return more than one address, we take the first one.
address = get_geolocation(lat, lon, 1)[0]

# Load the state(s) and corresponding geodata from the file.
countries_dict = load_country_geodata(address)

return location_blur_helper.find_closest_location(lat, lon, countries_dict)

latitude = location_data["latitude"]
longitude = location_data["longitude"]

closest = find_closest_point(latitude, longitude)
country_code = closest["countrycode"]

# Download the Countries database
get_file_from_server(countryfilename)
def get_country_location():
"""
Blurring layer for the get_location() function. It replaces the exact
coordinates of the Android device with the coordinates for the
geographic center of the country to which they belong.

countryfile = librepyfile.open(countryfilename, "r")
"""
location_data = get_location()

# Look for the country corresponding to the country code
while True:
try:
line = countryfile.next().strip()
except StopIteration:
break
else:
line = line.split("\t")
if country_code == line[0]:
clat = line[2]
clng = line[3]
break
countryfile.close()
closest_country = find_closest_country(location_data["latitude"],
location_data["longitude"])

location_data["latitude"] = clat
location_data["longitude"] = clng
location_data["latitude"] = closest_country["latitude"]
location_data["longitude"] = closest_country["longitude"]

return location_data



def get_country_lastknown_location():
# to replace get_lastknown_location()
try:
location_data = get_lastknown_location()
except Exception: # Not able to use LocationNotFoundException here
raise Exception

# Get the location from the the provider
for i in range(len(location_data.keys())):
provider = location_data.keys()[i]
location = location_data[provider]
if location != None:
latitude = location["latitude"]
longitude = location["longitude"]

closest = find_closest_point(latitude, longitude)

country_code = closest["countrycode"]

# Download the Countries database
get_file_from_server(countryfilename)

countryfile = librepyfile.open(countryfilename, "r")

# Look for the country corresponding to the country code
while True:
try:
line = countryfile.next().strip()
except StopIteration:
break
else:
line = line.split("\t")
if country_code == line[0]:
clat = line[2]
clng = line[3]
break
countryfile.close()

location_data[provider]["latitude"] = clat
location_data[provider]["longitude"] = clng
"""
Blurring layer for the get_lastknown_location() function. It replaces
the last-known coordinates of the Android device with the coordinates
for the geographic center of the country to which they belong.

"""
location_data = get_lastknown_location()

# Blur the coordinates of the first non-empty location data.
for location_provider, provider_location_data in location_data.items():
# Skip this provider's data if it doesn't contain a previous
# location.
if provider_location_data is None:
continue

closest_country = find_closest_country(provider_location_data["latitude"],
provider_location_data["longitude"])

break

# Copy the blurred coordinates into all providers' location data.
for location_provider, provider_location_data in location_data.items():
# Skip blurring this provider's data if it doesn't contain a previous
# location.
if provider_location_data is None:
continue

location_data[location_provider]["latitude"] = closest_country["latitude"]
location_data[location_provider]["longitude"] = closest_country["longitude"]

return location_data



# Mapping our blurring function get_country_location to get_location.
CHILD_CONTEXT_DEF["get_location"] = {
"type": "func",
"args": None,
Expand All @@ -189,6 +171,8 @@ CHILD_CONTEXT_DEF["get_location"] = {
}


# Mapping our blurring function get_country_lastknown_location to
# get_lastknown_location.
CHILD_CONTEXT_DEF["get_lastknown_location"] = {
"type": "func",
"args": None,
Expand All @@ -197,4 +181,6 @@ CHILD_CONTEXT_DEF["get_lastknown_location"] = {
"target": get_country_lastknown_location,
}


# Dispatch.
secure_dispatch_module()
Loading