|
| 1 | +# Traccar client ##################################################################################################################################### |
| 2 | +# |
| 3 | +# Reports this phone's position to Heimdall's Traccar over the OsmAnd protocol, which is the only one that server starts a listener for. |
| 4 | +# |
| 5 | +# A timer rather than a daemon, because a geoclue client held open keeps the modem's GNSS receiver powered: each run asks for one fix, posts it and |
| 6 | +# exits, so the radio is on for as long as a fix takes rather than all day. Five minutes is the interval the Traccar client app itself defaults to. |
| 7 | +# |
| 8 | +# The identifier below has to exist as a device in Traccar before a single report is stored. The server keeps its devices in its own database and |
| 9 | +# offers no way to declare one, so that is a job for the web UI, once. |
| 10 | +# |
| 11 | +{ |
| 12 | + config, |
| 13 | + lib, |
| 14 | + pkgs, |
| 15 | + ... |
| 16 | +}: |
| 17 | +let |
| 18 | + device = lib.toLower config.networking.hostName; |
| 19 | + desktopId = "traccar-client"; |
| 20 | + server = "http://heimdall.technet:5055"; # Reached over the tunnel, so it answers on mobile data as well as at home |
| 21 | + fixTimeout = 120; |
| 22 | + |
| 23 | + traccarClient = |
| 24 | + pkgs.writers.writePython3Bin "traccar-client" |
| 25 | + { |
| 26 | + libraries = [ pkgs.python3Packages.pygobject3 ]; |
| 27 | + flakeIgnore = [ "E501" ]; |
| 28 | + } |
| 29 | + '' |
| 30 | + import glob |
| 31 | + import sys |
| 32 | + import time |
| 33 | + import urllib.error |
| 34 | + import urllib.parse |
| 35 | + import urllib.request |
| 36 | +
|
| 37 | + import gi |
| 38 | + gi.require_version("Gio", "2.0") |
| 39 | + from gi.repository import Gio, GLib # noqa: E402 |
| 40 | +
|
| 41 | + SERVER = "${server}" |
| 42 | + DEVICE = "${device}" |
| 43 | + DESKTOP_ID = "${desktopId}" |
| 44 | + TIMEOUT = ${toString fixTimeout} |
| 45 | + GEOCLUE = "org.freedesktop.GeoClue2" |
| 46 | +
|
| 47 | + # Geoclue reports a double it has no value for as the most negative double there is. |
| 48 | + UNSET = -1.7976931348623157e308 |
| 49 | + # 8 is GeoClue's exact level; anything lower rounds the fix to the city, which is not a track. |
| 50 | + ACCURACY_EXACT = 8 |
| 51 | +
|
| 52 | +
|
| 53 | + def battery(): |
| 54 | + """Charge percentage and whether it is charging, as the Traccar client app reports them.""" |
| 55 | + for path in sorted(glob.glob("/sys/class/power_supply/*")): |
| 56 | + try: |
| 57 | + if open(path + "/type").read().strip() != "Battery": |
| 58 | + continue |
| 59 | + capacity = open(path + "/capacity").read().strip() |
| 60 | + status = open(path + "/status").read().strip() |
| 61 | + except OSError: |
| 62 | + continue |
| 63 | + if capacity: |
| 64 | + return capacity, status == "Charging" |
| 65 | + return None, False |
| 66 | +
|
| 67 | +
|
| 68 | + def report(bus, path): |
| 69 | + """Post one geoclue Location, returning whether the server took it.""" |
| 70 | + location = Gio.DBusProxy.new_sync( |
| 71 | + bus, Gio.DBusProxyFlags.NONE, None, |
| 72 | + GEOCLUE, path, GEOCLUE + ".Location", None, |
| 73 | + ) |
| 74 | +
|
| 75 | + def number(name): |
| 76 | + value = location.get_cached_property(name) |
| 77 | + return None if value is None else value.get_double() |
| 78 | +
|
| 79 | + latitude, longitude = number("Latitude"), number("Longitude") |
| 80 | + if latitude is None or longitude is None: |
| 81 | + return False |
| 82 | +
|
| 83 | + params = {"id": DEVICE, "lat": latitude, "lon": longitude, "timestamp": int(time.time())} |
| 84 | +
|
| 85 | + # Speed is metres per second, which is what geoclue reports and what the OsmAnd decoder converts from. |
| 86 | + for key, name in (("altitude", "Altitude"), ("accuracy", "Accuracy"), |
| 87 | + ("speed", "Speed"), ("bearing", "Heading")): |
| 88 | + value = number(name) |
| 89 | + if value is not None and value != UNSET and value >= 0: |
| 90 | + params[key] = value |
| 91 | +
|
| 92 | + level, charging = battery() |
| 93 | + if level is not None: |
| 94 | + params["batt"] = level |
| 95 | + params["charge"] = "true" if charging else "false" |
| 96 | +
|
| 97 | + with urllib.request.urlopen(SERVER + "/?" + urllib.parse.urlencode(params), timeout=20) as response: |
| 98 | + print("reported %(lat)s %(lon)s" % params, "->", response.status, flush=True) |
| 99 | + return True |
| 100 | +
|
| 101 | +
|
| 102 | + def main(): |
| 103 | + bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) |
| 104 | + manager = Gio.DBusProxy.new_sync( |
| 105 | + bus, Gio.DBusProxyFlags.NONE, None, |
| 106 | + GEOCLUE, "/org/freedesktop/GeoClue2/Manager", GEOCLUE + ".Manager", None, |
| 107 | + ) |
| 108 | + client_path = manager.call_sync("GetClient", None, Gio.DBusCallFlags.NONE, -1, None).unpack()[0] |
| 109 | +
|
| 110 | + # Geoclue hands a client no fix at all under an id its config does not allow. |
| 111 | + props = Gio.DBusProxy.new_sync( |
| 112 | + bus, Gio.DBusProxyFlags.NONE, None, |
| 113 | + GEOCLUE, client_path, "org.freedesktop.DBus.Properties", None, |
| 114 | + ) |
| 115 | + for key, value in (("DesktopId", GLib.Variant("s", DESKTOP_ID)), |
| 116 | + ("RequestedAccuracyLevel", GLib.Variant("u", ACCURACY_EXACT))): |
| 117 | + props.call_sync( |
| 118 | + "Set", GLib.Variant("(ssv)", (GEOCLUE + ".Client", key, value)), |
| 119 | + Gio.DBusCallFlags.NONE, -1, None) |
| 120 | +
|
| 121 | + client = Gio.DBusProxy.new_sync( |
| 122 | + bus, Gio.DBusProxyFlags.NONE, None, |
| 123 | + GEOCLUE, client_path, GEOCLUE + ".Client", None, |
| 124 | + ) |
| 125 | + loop = GLib.MainLoop() |
| 126 | + sent = [] |
| 127 | +
|
| 128 | + def on_signal(_proxy, _sender, name, params): |
| 129 | + if name == "LocationUpdated" and report(bus, params.unpack()[1]): |
| 130 | + sent.append(True) |
| 131 | + loop.quit() |
| 132 | +
|
| 133 | + client.connect("g-signal", on_signal) |
| 134 | + client.call_sync("Start", None, Gio.DBusCallFlags.NONE, -1, None) |
| 135 | +
|
| 136 | + # Geoclue only signals on change, so a fix it already holds would otherwise wait for the next move. |
| 137 | + held = client.get_cached_property("Location") |
| 138 | + if held is not None and held.get_string() not in ("", "/") and report(bus, held.get_string()): |
| 139 | + sent.append(True) |
| 140 | + else: |
| 141 | + GLib.timeout_add_seconds(TIMEOUT, loop.quit) |
| 142 | + loop.run() |
| 143 | +
|
| 144 | + client.call_sync("Stop", None, Gio.DBusCallFlags.NONE, -1, None) |
| 145 | + if not sent: |
| 146 | + print("no fix within", TIMEOUT, "seconds", flush=True) |
| 147 | +
|
| 148 | +
|
| 149 | + try: |
| 150 | + main() |
| 151 | + except urllib.error.URLError as err: |
| 152 | + # A phone with no route to the tunnel is an ordinary state, not a failure worth flagging |
| 153 | + print("traccar unreachable:", err, flush=True) |
| 154 | + except GLib.Error as err: |
| 155 | + print("geoclue:", err, file=sys.stderr, flush=True) |
| 156 | + sys.exit(1) |
| 157 | + ''; |
| 158 | +in |
| 159 | +{ |
| 160 | + services.geoclue2.appConfig.${desktopId} = { |
| 161 | + isAllowed = true; |
| 162 | + isSystem = true; # A background service with no session behind it, so there is no agent to ask on its behalf |
| 163 | + }; |
| 164 | + |
| 165 | + systemd.services.traccar-client = { |
| 166 | + description = "Report this phone's position to Traccar"; |
| 167 | + after = [ "network-online.target" ]; |
| 168 | + wants = [ "network-online.target" ]; |
| 169 | + |
| 170 | + serviceConfig = { |
| 171 | + Type = "oneshot"; |
| 172 | + ExecStart = lib.getExe traccarClient; |
| 173 | + DynamicUser = true; |
| 174 | + ProtectHome = true; |
| 175 | + ProtectSystem = "strict"; |
| 176 | + NoNewPrivileges = true; |
| 177 | + RestrictAddressFamilies = [ |
| 178 | + "AF_UNIX" |
| 179 | + "AF_INET" |
| 180 | + "AF_INET6" |
| 181 | + ]; |
| 182 | + }; |
| 183 | + }; |
| 184 | + |
| 185 | + systemd.timers.traccar-client = { |
| 186 | + wantedBy = [ "timers.target" ]; |
| 187 | + timerConfig = { |
| 188 | + OnBootSec = "3m"; |
| 189 | + OnUnitActiveSec = "5m"; |
| 190 | + AccuracySec = "30s"; # A tracker whose points are a minute out of place is not a tracker |
| 191 | + }; |
| 192 | + }; |
| 193 | +} |
0 commit comments