将gpxlogger数据写入同一文件

时间:2015-03-10 00:36:56

标签: python gps gpx gpsd

我有一些非常基本的gpxlogger代码,可以很好地将所有数据写入文件。 (下同)

gpxlogger -d  -f /home/pi/Desktop/EPQ/temp_gps/gpslog

但是我希望这段代码始终写入同一个文件而不会覆盖它。因此,如果可能的话,当它开始记录时,它将转到文件的底部并开始在那里记录数据,低于已记录的数据。

谢谢, 丹。

Javascript读取xml文件

  <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA7_kD1t_m22HBF9feCaDPZxQwcATY4FXmxYwkk9LNWGtAQdNKTBS1kBsTEqrRPg2kWxuNdmf2JVCIkQ" type="text/javascript"></script>
    <script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js">   </script><script>
     var map;

     function initialize () {  
      if (GBrowserIsCompatible()) {
         map = new GMap2(document.getElementById("map_canvas"));
         map.setCenter(new GLatLng(53.423027, -1.523462), 10);  
     map.addControl(new GLargeMapControl());
         map.addControl(new GMapTypeControl());
         map.addMapType(G_PHYSICAL_MAP);
     map.setMapType(G_PHYSICAL_MAP);

     addMarkersFromXML();

      }

      }

      function addMarkersFromXML(){
       var batch = [];
       mgr = new MarkerManager(map); 

       var request = GXmlHttp.create();
       request.open('GET', 'gpslog.xml', true);
       request.onreadystatechange = function() {
       if (request.readyState == 4 && request.status == 200) {
        var xmlDoc = request.responseXML;
        var xmlrows = xmlDoc.documentElement.getElementsByTagName("trkpt");

        for (var i = 0; i < xmlrows.length; i++) {
            var xmlrow = xmlrows[i];

            var xmlcellLatitude = parseFloat(xmlrows[i].getAttribute("lat"));
          var xmlcellLongitude = parseFloat(xmlrows[i].getAttribute("lon"));
          var point = new GLatLng(xmlcellLatitude,xmlcellLongitude);

          //get the time of the pin plot
            var xmlcellplottime = xmlrow.getElementsByTagName("time")[0];
            var celltextplottime = xmlcellplottime.firstChild.data;

          //get the elevation of the pin plot
            var xmlcellplotelevation = xmlrow.getElementsByTagName("ele")[0];
            var celltextplotelevation = xmlcellplotelevation.firstChild.data;

          //get the number of satellites at the time of the pin plot
            var xmlcellplotsat = xmlrow.getElementsByTagName("sat")[0];
            var celltextplotsat = xmlcellplotsat.firstChild.data;


            var htmlString = "Time: " + celltextplottime + "<br>" + "Elevation: " + celltextplotelevation + "<br>" + "Satellites: " + celltextplotsat;
            //var htmlString = 'yes'

            var marker = createMarker(point,htmlString);
            batch.push(marker);

        }

        mgr.addMarkers(batch,10);
        mgr.refresh();

      }
        }
    request.send(null);

      }

     function createMarker(point,html) {
           var marker = new GMarker(point);
           GEvent.addListener(marker, "click", function() {
             marker.openInfoWindowHtml(html);
           });
           return marker;
     }

    </script>
  </head>
  <body onload="initialize()" onunload="GUnload()">
    <div id="map_canvas" style="width: 1350px; height: 800px"></div>
    <div id="message"></div>
  </body>
</html>

4 个答案:

答案 0 :(得分:0)

您遇到了一个守护进程的gpxlogger问题,该文件名需要-f标志,并且会覆盖该文件。你知道吗。

我看到有两种选择。 作为守护程序运行gpxlogger

gpxlogger >> /home/pi/Desktop/EPQ/temp_gps/gpslog

或将其作为守护程序运行,并将cat文件作为可附加文件运行

gpxlogger -d  -f /home/pi/Desktop/EPQ/temp_gps/gpslog & cat /home/pi/Desktop/EPQ/temp_gps/gpslog >> /home/pi/Desktop/EPQ/temp_gps/gpslog_concatenated

答案 1 :(得分:0)

另一种查看它的方法是创建顺序日志,然后将它们与gpsbable连接起来,但为了做到这一点,你需要有一个脚本和一个索引。

制作索引echo 0 > ~/.gpxfilecount

打开收藏的编辑器并创建一个包含以下内容的文件:

#! /usr/bin/bash

COUNT=`cat ~/.gpxfilecount`
echo $(($COUNT + 1 )) > ~/.gpxfilecount

filename="gpxlogfile${COUNT}.gpx"
exec  gpxlogger -d  -f $filename

标记脚本可执行文件chmod +x ~/bin/gpxer.sh(或收藏夹名称)。

每次启动gpxlogger时,都会创建一个递增的文件名。然后可以通过gpsbable gpsbabel -i geo -f gpxlogfile1.gpx -f gpxlogfile2.gpx -f gpxlogfile3.gpx -o gpx -F biglogcat.gpx将这些文件连接起来而不会流泪......或者gpsbable可以工作。

答案 2 :(得分:0)

这是另一种选择。

查看gps3.py,将其和以下脚本放入目录。

它从gpsd读取数据;如果gpx日志文件不存在,则创建它;追加&#34; trackpoint&#34;数据存在时的数据;同时保持相同的文件并附加&#34; trackpoint&#34;重启后的数据。

将两者放在同一目录中,然后让你javascript读取文件。或者将整个结构放在同一个脚本中。

#!/usr/bin/env python
# coding=utf-8
""" gpx logger to create and append a gpx formatted log of gpsd data """ 
import os
import time
import gps3
from datetime import datetime

the_connection = gps3.GPSDSocket()
the_fix = gps3.Fix()
the_log = '/tmp/gpx3.gpx'  

creation = datetime.utcnow()
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
genesis = creation.strftime(fmt)

if not os.path.isfile(the_log):
    header = ('<?xml version = "1.0" encoding = "utf-8"?>\n'
              '<gpx version = "1.1" '
              'creator = "GPSD 3.9 - http://catb.org/gpsd" '
              'client = "gps3.py - http://github.com/wadda/gps3"'
              'xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"'
              'xmlns = "http://www.topografix.com/GPX/1/1"'
              'xsi:schemaLocation = "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">\n '
              '<metadata>\n '
              '     <time>{}\n'
              '</metadata>\n').format(genesis)
    f = open(the_log, 'w')
    f.write(header)
    f.close()

try:
    for new_data in the_connection:
        if new_data:
            the_fix.refresh(new_data)
            if not isinstance(the_fix.TPV['lat'], str):  # lat determinate of when data is 'valid'                    
                latitude = the_fix.TPV['lat']
                longitude = the_fix.TPV['lon']
                altitude = the_fix.TPV['alt']
                time = the_fix.TPV['time']
                mode = the_fix.TPV['mode']
                tag = the_fix.TPV['tag']

                sats = the_fix.satellites_used()
                hdop = the_fix.SKY['hdop']
                vdop = the_fix.SKY['vdop']
                pdop = the_fix.SKY['pdop']

                trackpoint = ('<trkpt lat = {} lon = {}>\n'
                              '    <ele>{}</ele>\n'
                              '    <time>{}</time>\n'
                              '    <src>GPSD tag ="{}"</src>\n'
                              '    <fix>{}</fix >\n'
                              '    <sat>{}</sat>\n'
                              '    <hdop>{}</hdop>\n'
                              '    <vdop>{}</vdop>\n'
                              '    <pdop>{}</pdop>\n'
                              '</trkpt>\n').format(latitude, longitude, altitude, time, tag, mode, sats[1], hdop, vdop, pdop)
                addendum = open(the_log, 'a')
                addendum.write(trackpoint)
                addendum.close()


except Exception as error:
    print('Danger-Danger',error)

答案 3 :(得分:0)

我很好奇从头开始构建gpx文件看起来只使用minidom。不幸的是生活干预了,抱歉延迟......

当这个脚本(下面)gpex3.py仍然有点粗糙和低效(每秒读/写)时,它与gps3.py放在同一个目录中,它会创建一个可附加的gpx档案/tmp/gpx3.gpx

#! /usr/bin/python3
# coding=utf-8
"""banana"""
import xml.dom.minidom
import gps3
import time
from datetime import datetime, timezone, timedelta
import os
import sys

gps_connection = gps3.GPSDSocket()
gps_fix = gps3.Fix()

the_log = '/tmp/gpx3.gpx'


def start_time():
    """time in the beginning"""
    timestart = str(datetime.utcnow().replace(tzinfo=(timezone(timedelta(0)))))
    return timestart


def close(doc):
    """write file to disk and close"""
    log_write = open(the_log, "w")
    doc.writexml(log_write)
    log_write.close()


if os.path.isfile(the_log):
    doc = xml.dom.minidom.parse(the_log)  # opens the pre-existing
    gpx_element = doc.firstChild

else:
    doc = xml.dom.minidom.Document()
    gpx_element = doc.createElement("gpx")
    doc.appendChild(gpx_element)

trk_element = doc.createElement("trkseg")
trk_element.setAttribute("began", start_time())
gpx_element.appendChild(trk_element)
utc = alt = hdop = vdop = pdop = mode = sats = tag = 'n/a'
try:
    tpv_list = {'time': utc, 'ele': alt, 'tag': tag}
    sky_list = {'hdop': hdop, 'vdop': vdop, 'pdop': pdop}
    # misc_list = {'sat': sats, 'fix':mode}  # just an account
    element = {}
    x = 1  # for the 'is it working?'
    for new_data in gps_connection:
        if new_data:
            gps_fix.refresh(new_data)
        if not isinstance(gps_fix.TPV['lat'], str):
            trkpt_element = doc.createElement("trkpt")
            trk_element.appendChild(trkpt_element)
            trkpt_element.setAttribute('lat', str(gps_fix.TPV['lat']))
            trkpt_element.setAttribute('lon', str(gps_fix.TPV['lon']))

            # tpv_list[key]
            for key in tpv_list:
                if key == 'ele':
                    element[key] = '{}'.format(gps_fix.TPV['alt'])  # because consistency with labels is a horrible.
                else:
                    element[key] = '{}'.format(gps_fix.TPV[key])
            # sky_list[key]
            for key in sky_list:
                element[key] = '{}'.format(gps_fix.SKY[key])
            # Misc.
            element['sat'] = '{}'.format(gps_fix.satellites_used()[1])
            element['fix'] = '{}'.format(("ZERO", "NO_FIX", "2D", "3D")[gps_fix.TPV['mode']])

            for key in element:
                trkpt_data = doc.createElement(key)
                trkpt_element.appendChild(trkpt_data)

                new_value = doc.createTextNode(element[key])
                trkpt_data.appendChild(new_value)

            # print(doc.toprettyxml())
            close(doc)  # write to file with every trackpoint
            print('Cycle', x)  # Only an "is it working?"
            x += 1
            time.sleep(1)

except KeyboardInterrupt:
    gps_connection.close()
    print("\nTerminated by user\nGood Bye.\n")

if __name__ == '__main__':
    pass