#!/usr/bin/env python
# Copyright (C) 2012 Michael Gorven
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from csv import reader
from datetime import datetime, timedelta
from optparse import OptionParser
from sys import stdin, stdout
from dateutil.tz import tzlocal
from dateutil.parser import parse as parsedate
from lxml import etree
parser = OptionParser()
GPX_NAMESPACE = 'http://www.topografix.com/GPX/1/1'
TPX_NAMESPACE = 'http://www.garmin.com/xmlschemas/TrackPointExtension/v1'
GPX='{%s}' % GPX_NAMESPACE
TPX='{%s}' % TPX_NAMESPACE
class HeartTrack(object):
def __init__(self, name, description, samplingrate, starttime, trackpoints=[]):
self.name = name
self.description = description
self.samplingrate = samplingrate
self.starttime = starttime
self.trackpoints = trackpoints or []
def __repr__(self):
return '' % (self.name, len(self.trackpoints), self.samplingrate.total_seconds(), self.starttime.isoformat())
@classmethod
def read_csv(self, filename):
csv = reader(open(filename))
headers = True
for line in csv:
field = line[0]
value = line[1] if len(line) > 1 else None
if headers:
if field.lower() == 'name':
name = value
elif field.lower() == 'description':
description = value
elif field.lower() == 'samplingrate':
samplingrate = timedelta(seconds=int(value))
elif field.lower() == 'date':
date = value
elif field.lower() == 'time':
time = value
elif field.lower() == 'heartrate':
starttime = datetime.strptime('%s %s' % (date, time), '%m/%d/%Y %H:%M:%S').replace(tzinfo=tzlocal())
track = HeartTrack(name, description, samplingrate, starttime)
currenttime = starttime
headers = False
else:
currenttime += track.samplingrate
track.trackpoints.append(HeartTrackpoint(int(value), currenttime))
return track
class HeartTrackpoint(object):
def __init__(self, heart, time):
self.heart = int(heart)
self.time = time
def __repr__(self):
return '' % (self.heart, self.time.isoformat())
def add_heart(gpx, heart):
nsmap = gpx.getroot().nsmap
nsmap['gpxtpx'] = TPX_NAMESPACE
root = etree.Element(gpx.getroot().tag, nsmap=nsmap, version='1.1', creator='wm100gpx.py')
root[:] = gpx.getroot()[:]
for trk in root.iterfind(GPX+'trk'):
for trkseg in trk.iterfind(GPX+'trkseg'):
for trkpt in trkseg.iterfind(GPX+'trkpt'):
time = parsedate(trkpt.find(GPX+'time').text)
hrpt = None
for heartpoint in heart.trackpoints:
if heartpoint.time > time:
break
hrpt = heartpoint
if hrpt and time - hrpt.time <= heart.samplingrate:
extensions = etree.SubElement(trkpt, 'extensions')
tpe = etree.SubElement(extensions, TPX+'TrackPointExtension')
hr = etree.SubElement(tpe, TPX+'hr')
hr.text = str(hrpt.heart)
return etree.ElementTree(root)
if __name__ == '__main__':
options, args = parser.parse_args()
parser = etree.XMLParser(remove_blank_text=True)
heart = HeartTrack.read_csv(args[0])
gpx = etree.parse(stdin, parser)
merged = add_heart(gpx, heart)
merged.write(stdout, encoding='UTF-8', pretty_print=True)