Location

Determining your physical location in Mobian is a fairly complex topic. There are a number of layers involved. Digging into the details takes some effort. Hopefully, this page will help you to dive in and see what is going on.

Warning: a lot of people reported in 2020 that the PinePhone GPS has poor sensitivity, see https://forum.pine64.org/showthread.php?tid=11680

Warning: The Modem Manager GPS functionality works only when an active SIM is present. (However it does not require SIM credit or a dataplan. And if you don't have a SIM card, you still can access the GPS from the modem via gpsd)

Update needed (2024-06-25): Mozilla Location Service (MLS) has been retired so the references below to MLS are obsolete

TL;DR When the Mobian first time setup wizard asks if you want to send location data to Mozilla Location Services answer "Yes." Use either Gnome Maps or install PureMaps. Run one of those apps in the background (or foreground) when you're traveling around with WiFi and Mobile Data enabled. For vehicle navigation, position your phone to have a good view of the sky when inside, and keep it in the open every once in a while for at least a few minutes so that it can find the satellites.

Source Data

Many people consider it to be the role of GPS (Global Positioning System) to provide their phone with their physical location. In reality there are a number of different sources that go into fixing your location, each with their own tradeoff in terms of reliability, speed, and accuracy.

GNSS / GPS

The Global Navigation Satellite System consists of a number of different positioning satellite constellations. The United State's GPS is the oldest and most famous, but there are others such as Galileo from the EU, GLONASS from Russia and Beidou from China. All of these constellations are supported by the EG25 modem in the ?PinePhone and are almost entirely transparent to the user.

Determining one's position using GNSS is done through a process of triangulation based on positional information about the satellites in orbit continually broadcast from space and the messages from each satellite with a very precise time. The differences between the times broadcast by different satellites and the "almanac" of satellite positions allows it to calculate your current position: latitude, longitude, altitude and a number of metrics indicating the precision of those measurements. The precision increases given the number of satellites that are detected and also other information such as bearing and speed.

Luckily, there is a standard for GNSS location and status information called NMEA (National Marine Electronics Association), which is available in most navigation equipment. In Mobian, this information can be seen directly using the mmcli (Modem Manager CLI).

$ sudo mmcli -m any --location-enable-gps-nmea --location-enable-gps-raw
successfully setup location gathering
$ sudo mmcli -m any --location-get
... Sometimes there is additional 3GPP (cell phone) location data here ...
  --------------------------
  GPS  |               nmea: $GPGSA,A,3,13,15,20,21,,,,,,,,,2.8,2.6,1.0,1*19
       |                     $GPRMC,215904.00,A,2518.123453,N,072.1111,W,0.0,21.7,310720,10.8,W,A,V*41
       |                     $GPGSV,3,1,12,05,20,084,22,10,06,272,21,13,51,059,32,15,81,123,34,1*6C
$GPGSV,3,2,12,18,67,295,28,20,35,284,29,21,08,313,29,23,,,30,1*58
$GPGSV,3,3,12,29,21,205,21,30,09,036,26,02,,,,07,,,,1*65
       |                     $GPVTG,21.7,T,32.5,M,0.0,N,0.0,K,A*23
       |                     $GPGGA,215904.00,2518.123453,N,07211.11111,W,1,04,21.1,114.4,M,-36.0,M,,*64
       |                utc: 215904.00
       |          longitude: -72.11111
       |           latitude: 25.123453
       |           altitude: 114.400000

The first time you try this, it might take a very long time to get an initial fix. Also, you'll need to give the phone a very clear view of the sky, outside of a building and clear of tall buildings. This will help ensure that it is able to locate the satellites in view and download the almanac of satellite positions. Subsequent fixes seem to be easier to achieve after there is an up-to-date almanac.

When testing the modem wtih CLI it is convenient to use the watch command to repeatedly query the current position. The -n option defines the interval in seconds, five seconds for example:

watch -n 5 mmcli -m any --location-get

When gps-nmea location is enabled in mmcli it will give you a number of NMEA fields like above can be decoded. Check out this reference guide for more information about each field. http://www.gpsinformation.org/dale/nmea.htm From this guide you will be able to see that this fix came from reading 12 satellites and overall, vertical and horizontal Dillution of Precision 2.8, 2.6 and 1.0, which is actually very good. There is alot of other data embedded there like your current bearing and speed, but that's left as an exercise to the reader to interpret those. The information about your location fix will be in the $GPGGA field or just a bunch of commas ',,' if a location cannot be determined at that point.

With GNSS it is possible to get your precise position within centimeters without the help of any other external source if the conditions are right. If you are trying to get your position "cold" it can take some time to wait for the almanac information about the satellite locations. Also, it can take more time to identify enough satellite signals to get a fix. It can take even more time to get a very precise fix. If there are any obstructions, such as buildings or tunnels or even bad weather this an take longer and become less reliable, especially on a mobile phone. This is why systems such as Mobian don't rely on a single input to pinpoint your location.

Quectel EC2SEC21 vendor documentation: https://sixfab.com/wp-content/uploads/2018/09/Quectel_EC25EC21_GNSS_AT_Commands_Manual_V1.1.pdf

Speeding up GPS fix with AGPS

As noted above, the initial GPS fix can be slow and unreliable. Downloading assistance data from the internet and sending it to the modem makes this a lot faster and more reliable. Smartphones tend to do this automatically, leading to an expectation of this level of performance. This isn't yet (20201002) the case for Mobian. There's a proof-of-concept script you can try, but proper support requires a fix to Modem Manager for its upload method to work with the Quectel modem.

Why the slow fix?

When doing a 'cold start' the GPS receiver first needs to collect enough data from the satellites' signal to work out what the GPS time is and where the satellites are. See this primer for details. The biggest data block is the almanac, and because of the low data rate it takes 12.5 minutes to send completely.

Modern smartphones don't have enough room for a good GPS antenna, and contain many potential sources of interference, so the signal to noise ratio is rather low. This makes it more likely that there will be errors or gaps in the reception of the initial data, and it won't come around again for 12.5 minutes. If you're lucky you'll get the satellites in an advantageous position, and collect enough data to get you going within a few minutes. If you're unlucky you could be waiting a _lot_ longer!

AGPS cuts all this out by downloading the almanac and ephemeris data from a web server, and setting the time from a network time server. This gives the receiver the complete set of information almost instantly, allowing a much faster and more reliable position fix. The down side is that it only works when you have a network connection, and you're making a request to a web server which some might consider a potential privacy issue.

Radio Stations

No, this is not the typical radio stations that broadcast the news or music. These are stations that generally don't move around too much, such as cellphone towers, WiFi hotspots and even bluetooth low energy beacons. If you are receiving a signal from one of these stations then you are likely to be in a specific spot on the planet within a few kilometers with cellphone towers or 100's of meters of a WiFi hotspot or bluetooth beacon.

You can use the Modem Manager to see the information about your current cellular phone (3gpp) connection information. This information uniquely identifies the single cell phone tower that you are currently connected.

$ mmcli -m any --location-get
  --------------------------
  3GPP |      operator code: 302
       |      operator name: 110
       | location area code: 0000
       | tracking area code: DAE2
       |            cell id: 086C5B39
... Potentially some GNSS NMEA Information ...

If you access mmcli directly from your phone, you don't need sudo rights, but if you access mmcli via ssh then you need sudo mmcli. Otherwise you run into something like:

error: couldn't get location from the modem: 'GDBus.Error:org.freedesktop.ModemManager1.Error.Core.Unauthorized: PolicyKit authorization failed: not authorized for 'org.freedesktop.ModemManager1.Location''

Also, you can use the NetworkManager to query for WiFi networks currently around you.

$ sudo iwlist scan
wlan0     Scan completed :
          Cell 01 - Address: 90:72:82:F2:89:36
                    ESSID:"getoffmylawn"
                    Protocol:IEEE 802.11bgn
                    Mode:Master
                    Frequency:2.412 GHz (Channel 1)
                    Encryption key:on
                    Bit Rates:300 Mb/s
                    Extra:rsn_ie=30140100000fac040100000fac040100000fac020000
                    ...
                    Quality=96/100  Signal level=-78 dBm  
                    Extra:fm=0003
           Cell 02 -
           ...

Unfortunately, none of these radio stations broadcast their specific locations on the Earth. There needs to be a database somewhere that keeps track of them and correlated their presence with rough location. Such databases already exist, some private like the ones used in Android and iOS. There's an open source (the code is available), but closed data (no data dumps of the database) one called Mozilla Location Service (MLS). The implementation and REST API is called Ichnaea. This service is the one available to Linux (Mobian) users. It goes without saying that any of these databases requires an active internet connection through WiFi or cellular data.

IP Address

As long as you have an Internet connection, you also have some sort of public IP address where your outgoing traffic goes. IP addresses can be associated with a rough geographic region, such as a city or region of a country. Note that a mobile IP (i.e. the only IP address is from your mobile carrier) location can vary widely (this author has anecdotally seen it off by 1000km). IP addresses also don't have an intrinsic geolocation, so this also requires some kind of database that will return a rough location from the address.

The Mozilla MLS service also provides an IP Address geolocation as an automatic fallback to their geolocation service. If their database doesn't know about the nearby radio stations or if your phone is unable to find any then it will use your outgoing request to their service to find your public IP Address and use a third-party provider. GeoIP locations are pretty bad and so this is definitely a fallback to use if no other source of location data can be found. But at least the lookup is very fast. This will need an active internet connection to work.

Setup gpsd

The gpsd service directly interacts with the modem, bypassing Modem Manager. It doesn't ship with mobian and needs to setup before usage. First install gpsd and its utilities:

sudo apt install gpsd gpsd-clients
scale-to-fit xgps on
scale-to-fit xgpsspeed on

Open /etc/default/gpsd and add the EG25 modem to the device list:

DEVICES="/dev/ttyUSB1"

Start the gpsd service and check its status:

sudo systemctl start gpsd.service
sudo systemctl status gpsd.service

Access the NMEA formatted GPS information directly from your EG25 modem:

gpspipe --nmea

Once you got a GPS fix, the output should look like. You can speed up the process of getting a GPS fix as explained above, with the experimental load_agps_data.py script:

$GLGSV,3,1,09,78,42,220,32,86,14,132,15,77,65,331,17,76,18,012,26,1*7F
$GLGSV,3,2,09,88,45,277,25,87,66,198,17,71,11,119,28,72,04,073,16,1*7A
$GLGSV,3,3,09,70,03,165,,1*47
$GPGSV,3,1,11,02,67,125,30,05,18,022,18,06,30,133,28,11,,,28,1*51
$GPGSV,3,2,11,12,85,039,16,24,14,337,18,25,53,230,30,29,27,261,17,1*65
$GPGSV,3,3,11,19,04,101,,20,34,039,,31,03,210,,1*55
$GPGGA,120529.00,XXX,S,YYY,E,1,03,3.8,4.9,M,-9.0,M,,*60
$GNGNS,120529.00,XXX,S,YYY,E,AAN,05,3.8,4.9,-9.0,,,V*66
$GPVTG,0.0,T,349.3,M,0.0,N,0.0,K,A*2E
$GPRMC,120529.00,A,XXX,S,YYY,E,0.0,0.0,040721,10.7,E,A,V*64
$GPGSA,A,3,02,06,25,,,,,,,,,,4.0,3.8,1.0,1*22
$GNGSA,A,3,02,06,25,,,,,,,,,,4.0,3.8,1.0,1*3C
$GNGSA,A,3,71,78,,,,,,,,,,,4.0,3.8,1.0,2*35

XXX and YYY is your exact latitude and longitude, respectively. Once, you got that GPS fix, start **xgps** app in Phosh, as it will give you a much better overview, of how many and which satellites are currently used.

Software Stack

Now that you have a sense of the different types of location sources with their advantages and disadvantages let's look at the Mobian software stack to support these different capabilities and services. You've already seen Modem Manager (mmcli) above. It is responsible for all modem interactions in areas such as GNSS and 3GPP if they are available. There is also the NetworkManager and wireless tools (iwlist) that are responsible for managing your current internet connection and detecting details of nearby WiFi endpoints.

If you are lucky enough to get a GNSS fix using the Modem Manager at the point where you need a location then that's great. However, none of these tools can gather together all the pieces of information to get you the best possible location from the MLS geolocation database when that isn't available. This is where Geo Clue comes into play. It is the piece that is capable of using all of these sources of information and providing a user application with your location and accuracy. In fact, this is the service that Gnome-Maps uses to show you your current location. You were probably wondering why the location bounces around on there sometimes. Now you know. The same is true for the ?PureMaps turn-by-turn navigation application.

If you have a favourite website that you would like to use with location information the GNOME Web browser will integrate with Geo Clue if you give it permission to do so. Note that a number of websites such as Google Maps and OpenStreetMap do not request high accuracy in the HTML5 GeoLocation API, which limits the accuracy that Geo Clue will provide and it usually falls back to IP Geolocation with its terrible accuracy, although this might be improved in a new webkit release. These and other websites can request high accuracy and Geo Clue will provide GNSS position when possible.

Building location aware applications

Using Geo Clue, one can take advantage of the best available location information. Here's a short tutorial to build a location-aware application.

https://howtotrainyourrobot.com/building-a-mobile-app-for-linux-part-4-gps-mobile-tracking/

Detailed Geo Clue Logging

Now that you have an understanding of the sources of data for your location and how Geo Clue can derive the best possible location from those sources at a given time, let's see it in action. One way to do this is to enable debug logging for the service. This will allow you to watch directly while you move around or query it for specific trips that you've made with your phone.

Change your /usr/lib/systemd/system/geoclue.service to add a special environment variable in the "[Service]" section.

Environment="G_MESSAGES_DEBUG=Geoclue"

Reload the geoclue systemd unit:

$ sudo systemctl daemon-reload

Restart the geoclue service:

$ sudo systemctl restart geoclue.service

Now you can look at the latest events (20) in geoclue with journalctl:

$ sudo journalctl -u geoclue.service -n 20

You can look back at the logs at a certain point in time like this:

$ sudo journalctl -u geoclue.service -S "2020-07-31 18:17:00"

Here's an example set of log entries. In this log you can see that some WiFi access points where discovered and added to the current set. The MLS geolocation service was successfully invoked and gave back a (very inaccurate) location. At 25km this was probably a fallback to an IP Address lookup because the WiFi AP's weren't known to MLS (see the fallback is "ipf"). Later on the WiFi AP's were no longer detected possibly because of movement that left them out of range.

Jul 20 11:20:19 pinephone geoclue[2007]: WiFi AP 'xyz1' added.
Jul 20 11:20:19 pinephone geoclue[2007]: WiFi AP 'xyz2' added.
Jul 20 11:20:19 pinephone geoclue[2007]: WiFi AP 'xyz3' added.
Jul 20 11:20:19 pinephone geoclue[2007]: WiFi AP 'abc1' added.
Jul 20 11:20:19 pinephone geoclue[2007]: WiFi AP 'abc2' added.
Jul 20 11:20:20 pinephone geoclue[2007]: Got following response from 'https://location.services.mozilla.
com/v1/geolocate?key=geoclue':
                                               {"location": {"lat": 25.1234, "lng": -78.5678}, "accuracy": 25000.0, "fallback": "ipf"}
Jul 20 11:20:20 pinephone geoclue[2007]: location scrambled
Jul 20 11:20:20 pinephone geoclue[2007]: GClueWifi got new heading 0.000000
Jul 20 11:20:20 pinephone geoclue[2007]: New location available
Jul 20 11:20:20 pinephone geoclue[2007]: Time difference between previous and new location is 302 second
s and below threshold of 3600 seconds.
Jul 20 11:20:20 pinephone geoclue[2007]: Updating location, below threshold
Jul 20 11:24:33 pinephone geoclue[2007]: WiFi AP 'xyz1' removed.
Jul 20 11:24:33 pinephone geoclue[2007]: WiFi AP 'xyz2' removed.
Jul 20 11:24:33 pinephone geoclue[2007]: WiFi AP 'abc1' removed.

Here is another trace. This time a cell phone tower was used successfully to get a somewhat accurate (1km) location. The NMEA ($GP)GGA trace was empty so the GNSS could not get a fix at this point. This is why the MLS service was contacted with the cell phone tower information.

Jul 30 17:16:00 pinephone geoclue[2072]: Sending following request to 'https://location.services.mozilla.com/v1/geolocate?key=geoclue':
                                               {"radioType":"gsm","cellTowers":[{"cellId":186563742,"mobileCountryCode":302,"mobileNetworkCode":101,"locationAreaCode":22342}]}
Jul 30 17:16:00 pinephone geoclue[2072]: New GGA trace is same as last one: $GPGGA,,,,,
Jul 30 17:16:00 pinephone geoclue[2072]: WiFi scan timeout. Restarting-scan..
Jul 30 17:16:02 pinephone geoclue[2072]: Got following response from 'https://location.services.mozilla.com/v1/geolocate?key=geoclue':
                                               {"location": {"lat": 24.300082, "lng": -76.183612}, "accuracy": 1000.0}
Jul 30 17:16:02 pinephone geoclue[2072]: GClue3G got new heading 0.000000

In this example there are WiFi access points detected nearby, but still no GNSS fix. WiFi access points can sometimes offer better accuracy than cell phone towers with MLS because the range is much smaller.

Jul 30 17:18:54 pinephone geoclue[2072]: Sending following request to 'https://location.services.mozilla.com/v1/geolocate?key=geoclue':
                                               {"wifiAccessPoints":[{"macAddress":"c8:d3:ff:80:89:a3","signalStrength":-88},{"macAddress":"90:72:82:f2:89:36","signalStrength":-88},{"macAddress":"90:84:0d:d5:e1>

Submitting Location Data to MLS

As you can see location is fairly often determined using the Mozilla Location Services, whether it uses cell towers or WiFi access points. If the data isn't there in its database to determine your location based on the available information then you are left with only the IP Address, which provides terrible accuracy. Fortunately, with your shiny new ?PinePhone (or even an Android App) there are ways you can help keep the database up to date.

Geo Clue has a built-in feature where it can actually publish radio station information (cell tower, wifi, bluetooth beacons) along with your current GNSS fix. Enabling it is pretty easy. Edit your /etc/geoclue/geoclue-conf and change the value of "submit-data" to true. There is a rumour that the Mobian initial setup wizard will also set this for you if you answer the question the right way.

# Submit data to Mozilla Location Service
# If set to true, geoclue will automatically submit network data to Mozilla
# each time it gets a GPS lock.
#
submit-data=true

Once you change this value you can either reboot your phone or restart the geoclue service (sudo systemctl restart geoclue.service). If you happen to have your Geo Clue tracing turned on you can see if/when it posts information to MLS. In this case it was a nearby WiFi access point that it discovered at the same time as a GNSS fix.

Jul 30 18:24:03 pinephone geoclue[2072]: Sending following request to 'https://location.services.mozilla.com/v1/submit?key=geoclue':
                                               {"items":[{"lat":25.103944839483,"lon":-45.11111111111,"accuracy":1.0,"altitude":82.900000000000006,"time":"2020-07-30T22:24:03Z","radioType":"gsm","wifi":[{"key":"b0:22:26:36:80:6a","signal":-88,"frequency":2462}]}]}
--
Jul 30 18:24:04 pinephone geoclue[2072]: Successfully submitted location data to 'https://location.services.mozilla.com/v1/submit?key=geoclue'

Here is a version that published the presence of a cell phone (3GPP) tower.

Jul 30 18:23:03 pinephone geoclue[2072]: Sending following request to 'https://location.services.mozilla.com/v1/submit?key=geoclue':
                                               {"items":[{"lat":25.11111111111,"lon":-45.11134242412341243,"accuracy":1.0,"altitude":85.299999999999997,"time":"2020-07-30T22:23:03Z","radioType":"gsm","cell":[{"radio":"gsm","cid":22848384,"mcc":302,"mnc":610,"lac":10965}]}]}

GPS location in Aeroplane mode

In areas without network connection or WiFi networks around, which is quite common outside densely populated areas, but also during all sorts of outdoor activities, your EG25 modem is still able to determine your GPS location. Unfortunately, there is a bug in ModemManager which prevents access to raw GPS without an active SIM card.

At the moment there are workarounds for this:

gpsd based applications

As already demonstrated above, after successful setup of gpsd, your GPS location can be determined bypassing Modem Manager. In order to speed your process, external loading of AGPS data, as long as you've WiFi connection is preferable:

## this only disables the EG25 modem, not the WiFi:
sudo systemctl disable ModemManager.service
sudo systemctl stop ModemManager.service
## update AGPS data on the EG25 modem
python3 /home/mobian/load_agps_data.py
## GPS fix should be there within seconds, if phone is placed properly outdoors
gpspipe --nmea

After receiving a GPS fix, you can use e.g. FoxtrotGPS for your GPS location and tracking, which directly relies on gpsd.

The location had to be activated either with Modem Manager before you go into Airplane mode: mmcli -m any --location-enable-gps-nmea --location-enable-gps-raw

Network NMEA

Unfortunately, Geo Clue doesn't support gpsd out of the box. There seems some reasons for this. Instead Geo Clue has network NMEA support. In order to get that working you need gps-share, which is actually not yet packaged for debian.

Here are instructions to compile it from source:

sudo apt install cargo libudev-dev
git clone https://github.com/zeenix/gps-share.git
cd gps-share/
cargo build --release

Make sure the build process was completed without problems. As Geo Clue complained it can't find mobian.local (is there any config for Geo Clue to look directly at localhost?) add the following line to /etc/hosts:

127.0.0.1       mobian.local

If you just got an AGPS fix with gpsd, all you need is to start gps-share. Make sure gpsd is not running at the same time:

sudo systemctl stop gpsd.service
## Just to make sure GeoClue is running, typical it's invoked automatically
sudo systemctl start geoclue.service
## start gps-share and talk directly to the EG25 modem
./target/release/gps-share /dev/ttyUSB1

The output should look similar to:

TCP server bound on all interfaces
Port: 10110
group: /Client9/EntryGroup1
Connection from 127.0.0.1
Connection from 127.0.0.1

The output of sudo journalctl -u geoclue.service -n 40 should read, after a GPS fix was received, like this:

Jul 05 15:18:27 mobian geoclue[13077]: GClueNMEASource got new heading 0.000000
Jul 05 15:18:27 mobian geoclue[13077]: New location available
Jul 05 15:18:27 mobian geoclue[13077]: [97B blob data]
Jul 05 15:18:27 mobian geoclue[13077]: Ignoring non-GGA sentence from NMEA source
Jul 05 15:18:27 mobian geoclue[13077]: [61B blob data]
Jul 05 15:18:27 mobian geoclue[13077]: Ignoring non-GGA sentence from NMEA source
Jul 05 15:18:27 mobian geoclue[13077]: [101B blob data]
Jul 05 15:18:27 mobian geoclue[13077]: Ignoring non-GGA sentence from NMEA source
Jul 05 15:18:27 mobian geoclue[13077]: [75B blob data]
Jul 05 15:18:27 mobian geoclue[13077]: Ignoring non-GGA sentence from NMEA source
Jul 05 15:18:27 mobian geoclue[13077]: [75B blob data]
Jul 05 15:18:27 mobian geoclue[13077]: Ignoring non-GGA sentence from NMEA source
Jul 05 15:18:27 mobian geoclue[13077]: [65B blob data]
Jul 05 15:18:27 mobian geoclue[13077]: Ignoring non-GGA sentence from NMEA source

Now open PureMaps and in combination with the offline maps from OSM ScoutServer you're able to navigate in Airplane mode!

GPS tracking when phone is suspended

Even GPS is working in Aeroplane mode, it will stop as soon as the phone is getting suspended in order to save battery. If the tracking is done in foreground directly on the phone, it can be expected that the battery will run flat after 3-5 hours.

This description only applies to ?PinePhones running on the FLOSS Modem Firmware

As the modem is always supplied from the battery, one can track the GPS signal directly on the modem, even if the phone is sent into suspend mode. Therefore create a (proof of concept) script in your ($HOME) directory. The log file is stored in the /persist directory. Therefore persistent logging must be activated:

while true; do
    head -n 20 /dev/smd7 | grep -m 1 GGA >> /persist/gps.log
    sleep 60
done

You also need to create an init script:

#
#
# Init script for: gps logger
USER=root
GROUP=root
DAEMON_PATH=/usr/bin/
DAEMON=gps-logger.sh

set -e

case "$1" in
  start)
        echo "Starting $DAEMON" > /dev/kmsg
        start-stop-daemon -c $USER:$GROUP -S -b -a $DAEMON_PATH$DAEMON
        ;;
  stop)
        echo "Stopping $DAEMON" > /dev/kmsg
        start-stop-daemon -K -n $DAEMON
        ;;
  restart)
        $0 stop
        $0 start
        ;;
  *)
        echo "Usage $0 { start | stop | restart}" >&2
        exit 1
        ;;
esac

exit 0

As the main filesystem on the modem is read-only, you need to make it writeable once to push the scripts onto the modem. You need to do this sequence again after every modem firmware update:

adb shell
sh-5.1# mount -o remount,rw /
sh-5.1# exit
adb push gps-logger.sh /usr/bin/
adb push init_gpslogging /etc/init.d/
adb shell
sh-5.1# chmod 755 /usr/bin/gps-logger.sh
sh-5.1# chmod 755 /etc/init.d/init_gpslogging

If you've problems accessing with adb, try to restart the adb server:

sudo adb kill-server
sudo adb start-server

Check with atinout if GPS had already been activated (this works even when ttyUSB2 is already locked by Modem Manager):

echo 'AT+QGPS?' | sudo atinout - /dev/ttyUSB2 -

A non-complete list of AT commands can be found here.

Then you can start the gps logging remotely via adb:

adb shell "service init_gpslogging start"

You can check via adb, if the gps logging is still running, even after you've logged out from the modem, and pull the gps.log at anytime from the modem:

adb shell "ps | grep gps"
adb pull /persist/gps.log
tail gps.log

WARNING These scripts do NOT reset the log file. Make sure you manually delete it in certain intervals. This was done in case the phone or modem crashes during a trip, and you need/want to continue gps logging immediately without dealing with the log files.

If you get the error message:

adb: error: failed to get feature set: device offline

You can manually activate ADB again with

echo 'AT+ADBON' | sudo atinout - /dev/ttyUSB2 -

and then check with, if the modem is online again:

adb devices

The output should look like

List of devices attached
community_fw    device

Convert log to gpx file

In order to convert the gps.log file into a gpx file to further processed by other software, you can use this simple python script. It converts the decimal minutes into decimal degrees for the gpx file. It looks for the file gps.log in the current directory, and write a gpx file in the same directory:

# -*- coding: utf-8 -*-

from datetime import datetime
import math

logfile = open("gps.log", "r")
loglist = logfile.readlines()

today = datetime.utcnow().strftime('%Y-%m-%d')
outputFile = open("gps_log_"+today+".gpx", "w")

header = """<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.0" creator="Pinephone"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://www.topografix.com/GPX/1/0" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">

\t<trk>
\t\t<trkseg>\n"""

footer = """\t\t</trkseg>
\t</trk>
</gpx>\n"""

outputFile.write(header)

for i in range(len(loglist)):
    myLine = loglist[i].split(",")
    
    if len(myLine[2]) > 0:
        time = today+"T"+(myLine[1])[0:2]+":"+(myLine[1])[2:4]+":"+(myLine[1])[4:]+"Z"
        
        lat_f, lat_w = math.modf(float(myLine[2])/100)
        lat = lat_w + lat_f/.6
        
        lon_f, lon_w = math.modf(float(myLine[4])/100)
        lon = lon_w + lon_f/.6
        
        if myLine[3] == "S":
            lat = -lat
        if myLine[5] == "W":
            lon = -lon
    
        outputFile.write('\t\t\t<trkpt lat="'+str(lat)+'" lon="'+str(lon)+'">\n')
        outputFile.write('\t\t\t\t<time>'+time+'</time>\n\t\t\t</trkpt>\n')


outputFile.write(footer)

logfile.close()
outputFile.close() 

TBD