2

我有一些非常基本的 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

4 回答 4

1

这是另一种选择。

查看gps3.py,把它和下面的脚本放到一个目录下。

它从 gpsd 读取数据;如果 gpx 日志文件不存在,则创建它;当数据存在时,将“trackpoint”数据附加到它;同时保持相同的文件并在重新启动后附加“跟踪点”数据。

将两者放在同一个目录中,然后让您使用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)
于 2015-03-11T10:34:00.377 回答
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
于 2015-03-10T02:39:49.907 回答
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 工作。

于 2015-03-10T13:51:09.293 回答
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
于 2015-04-01T07:07:59.250 回答