Проект GPSD
Глава 7 из книги «Архитектура приложений с открытым исходным кодом», том 2.
Оригинал: GPSD , глава из книги «The Architecture of Open Source Applications» том 2
Автор: Eric Raymond
Дата публикации: 2012 г.
Перевод: Н.Ромоданов
Дата перевода: июнь 2013 г.
Перевод был сделан в соответствие с лицензией Creative Commons . С русским вариантом лицензии можно ознакомиться здесь .
Проект GPSD представляет собой набор инструментальных средств для управления коллекциями устройств GPS и другими датчиками, связанными с навигацией и хранением точного времени, в том числе морских радиосистем автоматической идентификации AIS (Automatic Identification System) и цифровых компасов. Основная программа — демон сервиса, называемый gpsd , управляет набором датчиков и формирует от них всех сообщения в виде потока объектов JSON на известном порту TCP/IP. Среди других программ, имеющихся в наборе, есть примеры клиентских программ, используемых в качестве модели кода, а также различные диагностические инструментальные средства.
Проект GPSD развернут на достаточно большом количестве ноутбуков, смартфонов и автономных транспортных средств, в том числе на самоходных автомобилях и подводных лодках — роботах. Его возможности во встраиваемых системах используются для навигации, ведения точного земледелия, позиционно-чувствительной научной телеметрии и сервисов времени, имеющихся в сетях. Он даже используется в идентификационной системе «свой-чужой» боевых бронированных машин, в том числе в основном боевом танке M1 «Абрамс».
Проект GPSD является проектом среднего размера — около 43 тыс. строк кода, написанных, в основном, на C и Python, с историей нынешней лидирующей позиции начиная с 2005 года и с предысторией начиная с 1997 года. Основная стабильная группа его разработчиков состояла из трех разработчиков, с полу-регулярными вкладами приблизительно от более чем двух десятков разработчиков и обычными одноразовыми патчами от сотни других.
Исторически сложилось так, что в проекте GPSD присутствовало исключительно низкое количество ошибок, причем как измеряемое с помощью средств аудита, например, splint , valgrind и Coverity, так и оцениваемое согласно сообщениям об ошибках в собственном трекере, а также в других местах. Это не случайно; в проект очень агрессивно внедрялись технологии автоматизированного тестирования, и эти усилия окупились сторицей.
Проект GPSD достаточно хорошо делает все то, что должен делать, он вобрал в себя или эффектно уничтожил всех своих предшественников и предотвратил, по меньшей мере, одну прямую попытку конкурировать с ним. В 2010 году проект GPSD выиграл первый грант Good Code Grant альянса Alliance for Code Excellence. К тому моменту, как вы закончите читать эту главу, вы должны понять, благодаря чему.
7.1. Почему существует проект GPSD
GPSD существует из-за того, что прикладные протоколы, поставляемые с датчиками GPS и другие датчики, относящиеся к навигации, плохо спроектированы, недостаточно документированы и сильно зависят от типа и модели датчика. Подробное обсуждение смотрите по ссылке [Ray]; там, в частности, вы узнаете о капризах стандарта NMEA 0183 (варианта стандарта пакетов сообщений GPS) и о бессистемной куче плохо документированных протоколов поставщиков, которые с ним конкурируют.
Если бы приложения справлялись со всей этой сложностью самостоятельно, то результатом было бы огромное количество нестабильного и дублирующего кода, что ведет к высокой степени наличия видимых пользователю дефектов и постоянным проблемам, т. к. аппаратура постепенно становилась бы несовместимой с приложениями.
Проект GPSD изолирует приложения, обрабатывающие данные о местоположении, от деталей аппаратного интерфейса благодаря тому, что в самом проекте известно обо всех протоколах (во время написания статьи мы поддерживали около 20 различных протоколов), и благодаря такому управлению последовательными устройствами и устройствами USB, что приложениям этого делать уже не требуется, а достаточно только получать информацию от датчиков в простом и независимом от устройств формате JSON. GPSD еще больше упрощает жизнь благодаря тому, что предоставляются клиентские библиотеки и клиентским приложениям даже не нужно знать об этом формате сообщений. Вместо того, чтобы получать информацию с датчиков, достаточно просто вызвать процедуру.
Система GPSD также поддерживает хранение точного времени; она может выступать в качестве источника времени для ntpd (демона протокола сетевого сервиса времени), если в каком-нибудь из подключенных к нему датчиков имеется возможность выдавать сигналы PPS (секундные сигналы). Разработчики проекта GPSD тесно сотрудничают с проектом ntpd с целью улучшения сетевого сервиса времени.
В настоящее время (середина 2011 года) мы работаем над завершением поддержки сети AIS морских навигационных приемников. В будущем мы ожидаем, что будем поддерживать новые виды датчиков, работающие с информацией о местоположении, такие как приемники авиационных систем «запрос-ответ» второго поколения, поскольку станут доступными документация по протоколу и тестовые экземпляры устройств.
Таким образом, самым важным аспектом в проекте GPSD является сокрытие всех аппаратно-зависимых безобразий за простым клиентским интерфейсом, не требующим для получения данных никаких настроек.
Источник
Используем GPS в Ubuntu
Многим сисадминам нравится телефон нокиа Е61. Для своего времени, напичканый разными форматами связи, помимо стандартного GSM/UMTS, ИК, блютус и WiFi, (push-to-talk). QWERTY-клавиатура (полная). Большой яркий экран. Качественная сборка и металлическая спинка. Было в телефончике и несколько минусов, некоторые считают их несущественными. Итак: нет камеры, большой размер, нет FM, и нет GPS. Кроме размера, все остальные проблемы решаемы. Для GPS я приобрел nokia LD-3W.
Пользоваться картами на таком экране одно удовольствие. Спустя некоторое время, мне захотелось подключить приемник к ноутбуку Acer Aspire 5720 в котором есть встроенный блютус. На ноуте установлена убунта Intrepid Ibex (8.10). Теперь эту компанию нужно передружить.
Для начала сделаем:
sudo apt-get install bluez-utils
так как, в ноуте уже есть блютус, то при установке убунты поддержка блютуса была включена. Но добавим этот пакет все равно. По умолчанию, приемник добавить нельзя, потому что нету в нем куда вписать pin. Поэтому, продолжаем читать дальше. Включим приемник и выполним команду:
В выводе получим что-то вроде этого:
Scanning .
00:0D:B5:37:3B:A9 Nokia LD3W
Сохраним МАС-адрес (напомню, он уникален для каждого устройства). Теперь узнаем канал приемника:
sdptool browse 00:0D:B5:37:3B:A9
По умолчанию, это Channel 1. В конфиге нужно ввести эти данные по шаблону:
sudo gedit /etc/bluetooth/rfcomm.conf
rfcomm0 <
bind yes;
device 00:0D:B5:37:3B:A9;
channel 1;
comment «Serial Port»;
>
sudo rfcomm release 0
(здесь 0 если приемник — первое устройство, которое подключается, в моем случае уже было подключено несколько телефонов, поэтому нужно или удалить подключения, или менять 1, 2, 3, и т.д.).
rfcomm connect 0
После этой команды блютус-демон попросит ввести pin (только один раз), для этого приемника по умолчанию, код 0000.
Теперь нужно установить демон:
sudo apt-get install gpsd
И посмотреть на спутники:
Основной FAQ-материал находится здесь.
После удачного соединения приемника с ноутом, в частности, с убунтой, необходимо установить софт для работы с картами. Вкратце опишу несколько программ, с которыми не получилось поработать, по разным причинам. Одна из популярных — Viking — не заработала, т.к. принимала данные только от Garmin и Magellan. Поэтому, оценить функционал не удалось. Gpsdrive получил данные от приемника и показал координаты, но отсутствие карт привело в уныние.
Хотя настройки достаточно приличные, которые включают способ передвижения: велосипед, автомобиль, пешком. Вероятно и карты можно достать, импортировать, но хочется более простой способ.
И счастье есть! Это TangoGPS.
Обратите внимание, карты на родном языке. Конечно, универсальный английский не проблема, но приятно все равно. В начале был небольшой косяк с установкой, на родном сайте стоит перенаправление на openSUSE build service, где я нашел .deb для amd64.
Окошко программы напомнило стиль Мас-софта:
Кроме карты есть общая информация о пути. Ведение журнала пройденого пути для использования с OSM (open street map):
Настройки достаточно простые, автоматическая загрузка карт, не полных, а только квадратов доступных для текущего экрана. Представление карт в виде опенстрит — карта схема с названиями улиц. Топографическая и воздушная съемка. На домашней странице можно прочитать об остальных функциях и посмотреть скриншоты разных представлений карт, а также на каких мобильных устройствах работает программа.
Привожу список программ, которые вы можете испытать сами.
В ближайшем путешествии, если будет возможность, протетстирую tangogps вплотную.
Источник
About gpsd
gpsd is a service daemon that monitors one or more GPSes or AIS receivers attached to a host computer through serial or USB ports, making all data on the location/course/velocity of the sensors available to be queried on TCP port 2947 of the host computer.
With gpsd , multiple location-aware client applications can share access to supported sensors without contention or loss of data. Also, gpsd responds to queries with a format that is substantially easier to parse than the NMEA 0183 emitted by most GPSes. The gpsd distribution includes a linkable C service library, a C++ wrapper class, and a Python module that developers of gpsd -aware applications can use to encapsulate all communication with gpsd . Third-party client bindings for Java and Perl also exist.
Besides gpsd itself, the project provides auxiliary tools for diagnostic monitoring and profiling of receivers and feeding location-aware applications GPS/AIS logs for diagnostic purposes.
GPSD is everywhere in mobile embedded systems. It underlies the map service on Android phones. It’s ubiquitous in drones, robot submarines, and driverless cars. It’s increasingly common in recent generations of manned aircraft, marine navigation systems, and military vehicles.
Applications that presently use gpsd include Kismet, GpsDrive, gpeGPS, roadmap, roadnav, navit, viking, tangogps, foxtrot, obdgpslogger, geohist, LiveGPS, geoclue, qlandkartegt, gpredict, OpenCPN, gpsd-navigator, gpsd-ais-viewer, and firefox/mozilla. In addition, the Android smartphone operating system (from version 4.0 onwards and possibly earlier; we don’t know for sure when the change happened) uses GPSD to monitor the phone’s on-board GPS, so every location-aware Android app is indirectly a GPSD client.
GPSD is also extremely widely deployed in mobile embedded systems: it’s a basic building block for navigation used by UAVs, robot submarines, and driverless cars as well as more conventional applications like marine navigation and military IFF systems.
Under Linux, gpsd normally runs with zero configuration. Binary packages for this program install hotplug scripts that do the right thing when a USB device goes active, launching gpsd if needed and telling gpsd which device to read data from. Then, gpsd deduces a baud rate and GPS/AIS type by looking at the data stream.
gpsd is high-quality, carefully-audited code; see our notes on reliability engineering. In January 2010, the GPSD project won the first Good Code Grant from the Alliance for Code Excellence.
Statistics about the code volume, commit history, and contributors associated with this project are available at OpenHUB
Our development platforms are open-source Unixes — Linux, and the *BSD family. Presently Linux, OpenBSD and NetBSD are directly supported. The code is also extremely widely deployed on Android phones. We’ll support proprietary Unixes if it’s not too much work (and it usually isn’t). Apple’s OS X is supported in a limited fashion. Some older OS X drivers are buggy and prevent gpsd from being able to read from some USB-serial devices. No, we don’t support Windows — get a better operating system.
If you represent a GPS manufacturer interested in qualifying your device for use with Linux and other open-source operating systems, we are your contact point. We’ll need (1) on-line access to interface documentation, (2) a few (as in, no more than three) eval units, and (3) an engineering contact at your firm. For more, see our page welcoming vendor cooperation.
See the FAQ for information on how to report bugs.
If you appreciate GPSD, and especially if you make money from it, please leave a remittance at Patreon.
This web page was last updated on Sun Oct 10 07:00:57 2021. Note: because of the way this website is maintained, these files reflect the state of the repository tip (development version) rather than the latest released version.
Installation & Building
Repository, Downloads and Packages
If you are using a Debian-based distribution (including Ubuntu) you can probably install gpsd through your regular package manager or by typing «sudo apt-get install gpsd» at the command line.
Support
Real Time
Some of the developers hang out regularly on IRC at channel #gpsd at irc.freenode.net, and at channel #gpsd at irc.libera.chat.
Mailing Lists
There are four project mailing lists:
- gpsd-announce is for release announcements and project news.
- gpsd-users is for questions and technical support on gpsd , including support for application builders using gpsd as a component.
- gpsd-dev is for gpsd developers.
- gpsd-commit-watch sends automatic broadcast notifications of commits to the gpsd repository.
- There are searchable archives of the old GPSD mailing lists from Berlios at MARC: gpsd-usersgpsd-dev and gpsd-commit-watch.
Issue Tracker
The gpsd project tracks issues on our issue tracker. Please read the section on Bug reporting before posting on the issue tracker.
SUPPORT information
More information on gpsd SUPPORT is available on the gpsd SUPPORT page.
Documentation
The following manual pages describe the code. Note: because of the way this website is maintained, these files will describe the state and features of the repository tip (development version) rather than the latest stable version.
gpsd.8 The gpsd daemon. gps.1 Overview of gpsd client and helper programs. cgps.1 A command line ncurses client for gpsd . gegps.1 gegps feeds your location to Google Earth for live location tracking. gps2udp.1 Feed the take from gpsd to one or more aggregation sites via UDP. gpscsv.1 The gpscsv tool for reading gpsd JSON sentences and converting them in CSV files. gpsctl.1 The gpsctl tool for tweaking GPS settings. gpscat.1 The gpscat tool dumps output from a serial device. Optionally, it can packetize the data. gpsdebuginfo.1 A shell script to dump debugging information. For you convenience gpsdebuginfo is available for direct download. gpsdecode.1 The gpsdecode packet decoder. gpsfake.1 The gpsfake test harness simulating a GPS. gpsmon.1 The gpsmon real-time packet monitor and diagnostic tool. (This replaces the sirfmon tool in older versions.) gpspipe.1 A simple client that captures GPS output and/or gpsd reports and sends it to standard output. gpsplot.1 The gpsplot program for dynamically plotting scatterplots and stripcharts of gpsd data. gpsprof.1 The gpsprof program for statically plotting spatial scatter of fixes, satellite skyview, fix latency, and other plots. gpsrinex.1 The gpsrinex program for outputting raw measurements into a RINEX 3 file. gpssubframe.1 The gpssubframe tool for reading gpsd JSON subframe sentences and decoding them. lcdgps.1 A gpsd client to display on a 4×20 LCD screen, using lcdproc . ntpshmmon.1 Monitor the NTP shared-memory segments created by GPSD. ubxtool.1 Configure and ommunicate with u-blox GPS from the command line. zerk.1 An all purpose GREIS fitting. A command line tool for JAVAD GPS. libgps.3 An interface library that manages communication with the daemon. libgpsmm.3 C++ class wrapper for the libgps C binding. libQgpsmm.3 Qt wrapper for the libgps C binding. gpsd_json.5 The JSON request/response protocol of the gpsd daemon. gpsdctl.8 Tool for sending commands to gpsd over its control socket. gpsinit.8 Initialize kernel modules for use with gpsd daemon. ppscheck.8 Tool to check a serial port for PPS.
We have a list of compatible GPSses with some technical information. We also have a list of NMEA sentences.
There is a Hacker’s Guide to the project philosophy, design, and code internals. You should read this if you want to contribute code.
We maintain a GPS Hall of Shame that describes particularly egregious vendor blunders.
White Papers
Recipes and related resources
gpsd also works with some bluetooth GPS receivers. Warning: there are serious problems with the firmware in at least one family of Bluetooth implementations shipped by Holux that may result in gpsd bricking your GPS. See this bug warning for a description of the problem.
If you have an Android phone, it is possible to access its onboard GPS by pairing it as a Bluetooth device. Directions from Vargoville (Dead link Mar 2021). There is also a GPS Tether (Dead link Mar 2021) app designed to work with GPSD, but it seems to be in early alpha.
The GPSDproxy project is a small program which reads GPS data from a running gpsd process and forwards it to a remote server via an UDP connection. GPSDproxy is intended to be run on GPS enabled mobile devices.
You can read detailed instructions on Synchronizing ntpd to a Garmin GPS 18 LVC via gpsd. This may be a useful tutorial even if your actual device isn’t a Garmin 18; many of the setup steps and caveats will be the same.
Diego Berge has written a prototype Qt-based client, basically xgps with a Qt look and feel.
Egil Möller has written agpsd, a gpsd replication and logging daemon with support for KML.
You can find Debian-unstable packages here.
gpsd is carried in the OpenBSD ports tree.
OpenStreetMap is a wiki aiming to build a freely available, world-wide streetmap.
Freedesktop.org is hosting a project called geoclue that aims to provide a location service layer for all D-Bus-using applications. It can use gpsd as a source for location info.
Other GPSDs
There used to be three Linux-based forks of gpsd in the wild, but this GPSD project reabsorbed one and the other two are now defunct for unrelated reasons. You can read a brief history of the gpsd project if you are curious.
There was a project called gps3d that ships a gpsd with similar goals to ours, but which appears to be an independent development. There haven’t been any releases since early 2002. Their website is archived at the Internet Archive.
There is a gpsd -like hack hosted under Microsoft Windows. It provides gpsd service from data in netstumbler under win32. This way programs such as JiGLE can still get GPS data from netstumbler. This program is not genetically related to gpsd .
gpsfeed+ is a program that simulates the output of a GPS in motion, and can be used for testing GPS-aware applications.
We aren’t Green Parrot Software Development, nor are we the Greenville Public School District nor the Greater Peoria Sanitary District, nor even the Greater Portland Soccer District, nor the Green Party of San Diego, nor do we have anything to do with the General Product Safety Directive, the Guiding Principles of Sustainable Design, nor the Glatt Plagiarism Self-Detection Program.
Источник