Skip to content

Instantly share code, notes, and snippets.

@JimHaughwout
Last active August 29, 2015 14:25
Show Gist options
  • Save JimHaughwout/6576e4bb4bcb86dd3249 to your computer and use it in GitHub Desktop.
Save JimHaughwout/6576e4bb4bcb86dd3249 to your computer and use it in GitHub Desktop.
Gen Cobra Polyline
#!/usr/bin/python
import sys
import json
import getopt
import webbrowser
html_header = """<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Polylines</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(38.8, -77.1),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var cobraPathCoordinates = ["""
html_footer = """
];
var cobraPath = new google.maps.Polyline({
path: cobraPathCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
cobraPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
"""
def print_usage_and_exit(msg=None):
"""
Pretty print exit on error
"""
print "\nUsage: %s [-s][-h]" % sys.argv[0]
print "\t-h Print usage help"
print "\t-s Source accumulated smurfs file - Required"
print "\t-d Device ID (IMEI) - Required"
if msg: print msg + "\n"
sys.exit(2)
def try_dict_extract(dictionary, key_list):
"""
Iterates through a list of keys to try to return a dictionary key value.
On exception, returns NoneType
"""
try:
x = dictionary
for key in key_list:
x = x[key]
return x
except:
return None
def extract_smurf(row):
"""
Check if data is in SMF2 format AND is a SMurF. If not exits with error
"""
try:
smurf = json.loads(row)
if smurf['smfMetaData']['payloadType'] != 'smf-universal-read':
print_usage_and_exit(("%r is not a SMurF" % row))
return smurf
except (ValueError, KeyError, TypeError) as e:
print_usage_and_exit(("%r is not even in SMF2 format: %s" % (row, e)))
def check_for_event(smurf_obj, event_name):
"""
Trys to determine event exists in smfPayloadData['events']
If so, returns a 1 (else None)
TODO: May make a generic list of events to return
"""
key_list = ['smfPayloadData', 'events']
key_list.append(event_name)
if try_dict_extract(smurf_obj, key_list) == None:
return None
else:
#return event_name
return 1
# Parse opts, ensure we have required opts to determine mode, source, target
device = None
infile = None
try:
opts, args = getopt.getopt(sys.argv[1:], "hd:s:")
if not opts:
print_usage_and_exit('No options supplied')
except getopt.GetoptError:
print_usage_and_exit('Could not parse options')
for opt, arg in opts:
if opt == '-h':
print_usage_and_exit()
elif opt == '-d':
device = arg
elif opt == '-s':
infile = arg
if not(device):
print_usage_and_exit('-d device IMEI not specified')
if not(infile):
print_usage_and_exit('-s source_file not specified')
outfile = device + '_path.html'
# Try to open source file and extact events
try:
source = open(infile, 'r')
reads = source.readlines()
source.closed
except IOError as e:
print_usage_and_exit(("Could not open %r to read: %s" % (infile, e)))
# Try to open target file
try:
target = open(outfile, 'w')
except IOError as e:
print_usage_and_exit(("Could not open %r to write: %s" % (outfile, e)))
# Loop through reads, parse into a data row, then write data row to CSV
read_count = 0
feature_count = 0
# Build dict to hold points
poly_line = dict()
for read in reads:
smurf = extract_smurf(read)
if device in try_dict_extract(smurf, ['smfMetaData', 'deviceId']):
feature_time = str(try_dict_extract(smurf, ['smfPayloadData', 'timestamp']))
feature_lat = float(try_dict_extract(smurf, ['smfPayloadData', 'position', 'gps', 'latitude']))
feature_lng = float(try_dict_extract(smurf, ['smfPayloadData', 'position', 'gps', 'longitude']))
google_coords = "\n new google.maps.LatLng(%f, %f)" % (feature_lat, feature_lng)
feature_count += 1
poly_line[feature_time] = google_coords
read_count += 1
target.write(html_header)
this_point = 0
point_count = len(poly_line)
for entry in sorted(poly_line.keys()):
target.write(poly_line[entry])
this_point += 1
if this_point < point_count:
target.write(',')
target.write(html_footer)
print "SUCCESS: Process %d reads. Created polyline of %d reads in %s\n" % (read_count, feature_count, outfile)
"""
# TODO
url = "file://%s" % outfile
print url
webbrowser.open(url)
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment