Files
bananarchy/src/dwm-plugins/gps_plugin.cpp
T

1198 lines
43 KiB
C++

// SPDX-License-Identifier: GPL-2.0-only
// GPS Reception Test Utility & OpenStreetMap Navigator DWM Plugin
// (gps.so / xgps / xmaps / xnav) for Bananarchy (240x320)
// Features:
// 1. GPS Test Tab: Live ModemManager/QDSP6 GNSS NMEA + raw coordinate parser,
// satellite SNR bar graph ($GPGSV/$GLGSV), DOP/fix quality ($GPGSA/$GPGGA),
// speed/course ($GPRMC/$GPVTG), and 3GPP cell tower info (MCC/MNC/TAC/CID).
// 2. OSM Map Tab: Slippy map renderer (zoom 2..18) with disk-cached 256x256
// OpenStreetMap PNG tiles, async tile downloader, live GPS crosshair,
// route polyline overlay, distance/bearing HUD, and keypad pan/zoom.
// 3. Navigate Tab: OpenStreetMap Nominatim place search, saved waypoints, and
// OSRM turn-by-turn route planner.
#include "../sxmo-dwm/dwm_plugin.h"
#include "net_tls.h"
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <fstream>
#include <mutex>
#include <thread>
#include <unordered_map>
namespace {
using namespace bananarchy;
volatile sig_atomic_t gRunning = 1;
void handleSignal(int) {
gRunning = 0;
}
constexpr double kPi = 3.14159265358979323846;
struct SatelliteInfo {
int prn = 0;
int elevation = 0;
int azimuth = 0;
int snr = 0;
};
struct GpsStatus {
bool gpsEnabled = false;
bool hasFix = false;
int fixDimension = 1; // 1=No fix, 2=2D, 3=3D
int satsUsed = 0;
int satsInView = 0;
double latitude = 0.0;
double longitude = 0.0;
double altitudeM = 0.0;
double speedKmh = 0.0;
double courseDeg = 0.0;
double hdop = 99.9;
std::string utcTime = "--:--:--";
std::string mcc = "-";
std::string mnc = "-";
std::string tac = "-";
std::string cid = "-";
std::vector<SatelliteInfo> satellites;
std::vector<std::string> rawNmea;
};
struct Waypoint {
std::string name;
double lat = 0.0;
double lon = 0.0;
};
struct RouteStep {
std::string instruction;
double distanceM = 0.0;
double lat = 0.0;
double lon = 0.0;
};
double degToRad(double d) { return d * (kPi / 180.0); }
double radToDeg(double r) { return r * (180.0 / kPi); }
double haversineMeters(double lat1, double lon1, double lat2, double lon2) {
constexpr double kEarthR = 6371000.0;
double dLat = degToRad(lat2 - lat1);
double dLon = degToRad(lon2 - lon1);
double a = std::sin(dLat / 2.0) * std::sin(dLat / 2.0) +
std::cos(degToRad(lat1)) * std::cos(degToRad(lat2)) *
std::sin(dLon / 2.0) * std::sin(dLon / 2.0);
double c = 2.0 * std::atan2(std::sqrt(a), std::sqrt(std::max(0.0, 1.0 - a)));
return kEarthR * c;
}
double bearingDegrees(double lat1, double lon1, double lat2, double lon2) {
double phi1 = degToRad(lat1);
double phi2 = degToRad(lat2);
double dLon = degToRad(lon2 - lon1);
double y = std::sin(dLon) * std::cos(phi2);
double x = std::cos(phi1) * std::sin(phi2) -
std::sin(phi1) * std::cos(phi2) * std::cos(dLon);
double brng = std::fmod(radToDeg(std::atan2(y, x)) + 360.0, 360.0);
return brng;
}
std::string formatDistance(double meters) {
char buf[32];
if (meters >= 1000.0) {
std::snprintf(buf, sizeof(buf), "%.1f km", meters / 1000.0);
} else {
std::snprintf(buf, sizeof(buf), "%d m", static_cast<int>(std::lround(meters)));
}
return buf;
}
const char* compassCardinal(double deg) {
static const char* kDirs[8] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"};
int idx = static_cast<int>(std::lround(deg / 45.0)) & 7;
return kDirs[idx];
}
// Slippy map Web Mercator projection helpers
void latLonToWorldPx(double lat, double lon, int zoom, double& outWx, double& outWy) {
lat = std::clamp(lat, -85.0511, 85.0511);
double n = static_cast<double>(1 << zoom) * 256.0;
outWx = ((lon + 180.0) / 360.0) * n;
double latRad = degToRad(lat);
outWy = (1.0 - std::log(std::tan(latRad) + 1.0 / std::cos(latRad)) / kPi) /
2.0 * n;
}
void worldPxToLatLon(double wx, double wy, int zoom, double& outLat, double& outLon) {
double n = static_cast<double>(1 << zoom) * 256.0;
outLon = (wx / n) * 360.0 - 180.0;
double latRad = std::atan(std::sinh(kPi * (1.0 - 2.0 * wy / n)));
outLat = radToDeg(latRad);
}
// Parse NMEA ddmm.mmmm coordinate to signed decimal degrees
bool parseNmeaCoord(const std::string& raw, const std::string& hemi,
double& outDeg) {
if (raw.size() < 4) return false;
size_t dot = raw.find('.');
if (dot == std::string::npos || dot < 2) return false;
double degPart = std::atof(raw.substr(0, dot - 2).c_str());
double minPart = std::atof(raw.substr(dot - 2).c_str());
double val = degPart + (minPart / 60.0);
if (hemi == "S" || hemi == "W") val = -val;
outDeg = val;
return true;
}
std::vector<std::string> splitCsv(const std::string& s) {
std::vector<std::string> out;
std::string cur;
for (char c : s) {
if (c == ',' || c == '*') {
out.push_back(cur);
cur.clear();
if (c == '*') break;
} else {
cur.push_back(c);
}
}
out.push_back(cur);
return out;
}
void pollModemGpsStatus(GpsStatus& st) {
std::string raw = runCaptureCmd("mmcli -m any -K --location-get 2>/dev/null");
if (raw.empty()) return;
st.rawNmea.clear();
std::vector<SatelliteInfo> gsvSats;
std::istringstream iss(raw);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
size_t colon = line.find(':');
if (colon == std::string::npos) continue;
std::string k = trimStr(line.substr(0, colon));
std::string v = trimStr(line.substr(colon + 1));
if (v == "--" || v.empty()) continue;
if (k == "modem.location.3gpp.mcc") st.mcc = v;
else if (k == "modem.location.3gpp.mnc") st.mnc = v;
else if (k == "modem.location.3gpp.tac") st.tac = v;
else if (k == "modem.location.3gpp.cid") st.cid = v;
else if (k == "modem.location.gps.latitude") {
st.latitude = std::atof(v.c_str());
st.hasFix = true;
} else if (k == "modem.location.gps.longitude") {
st.longitude = std::atof(v.c_str());
st.hasFix = true;
} else if (k == "modem.location.gps.altitude") {
st.altitudeM = std::atof(v.c_str());
} else if (k == "modem.location.gps.utc") {
st.utcTime = v;
} else if (k.find("modem.location.gps.nmea.value") == 0) {
st.rawNmea.push_back(v);
std::vector<std::string> f = splitCsv(v);
if (f.empty()) continue;
const std::string& type = f[0];
if ((type == "$GPGGA" || type == "$GNGGA") && f.size() >= 10) {
if (!f[1].empty() && f[1].size() >= 6) {
st.utcTime = f[1].substr(0, 2) + ":" + f[1].substr(2, 2) + ":" +
f[1].substr(4, 2);
}
int qual = std::atoi(f[6].c_str());
if (qual > 0) {
st.hasFix = true;
parseNmeaCoord(f[2], f[3], st.latitude);
parseNmeaCoord(f[4], f[5], st.longitude);
}
if (!f[7].empty()) st.satsUsed = std::atoi(f[7].c_str());
if (!f[8].empty()) st.hdop = std::atof(f[8].c_str());
if (!f[9].empty()) st.altitudeM = std::atof(f[9].c_str());
} else if ((type == "$GPRMC" || type == "$GNRMC") && f.size() >= 9) {
if (f[2] == "A") {
st.hasFix = true;
parseNmeaCoord(f[3], f[4], st.latitude);
parseNmeaCoord(f[5], f[6], st.longitude);
}
if (!f[7].empty()) st.speedKmh = std::atof(f[7].c_str()) * 1.852;
if (!f[8].empty()) st.courseDeg = std::atof(f[8].c_str());
} else if ((type == "$GPGSA" || type == "$GNGSA") && f.size() >= 17) {
if (!f[2].empty()) st.fixDimension = std::atoi(f[2].c_str());
if (!f[16].empty()) st.hdop = std::atof(f[16].c_str());
} else if ((type == "$GPGSV" || type == "$GLGSV" || type == "$GNGSV") &&
f.size() >= 4) {
int inView = std::atoi(f[3].c_str());
if (inView > st.satsInView) st.satsInView = inView;
for (size_t idx = 4; idx + 3 < f.size(); idx += 4) {
if (f[idx].empty()) continue;
SatelliteInfo sat;
sat.prn = std::atoi(f[idx].c_str());
sat.elevation = std::atoi(f[idx + 1].c_str());
sat.azimuth = std::atoi(f[idx + 2].c_str());
sat.snr = std::atoi(f[idx + 3].c_str());
gsvSats.push_back(sat);
}
}
}
}
if (!gsvSats.empty()) {
st.satellites = std::move(gsvSats);
st.satsInView = std::max(st.satsInView, static_cast<int>(st.satellites.size()));
}
}
std::string getWaypointsPath() {
return getHomeDirPath() + "/.config/sxmo/gps_waypoints.tsv";
}
std::string getOsmTileCacheDir() {
if (!isDuressMode() && ::access("/media/sdcard", W_OK) == 0) {
std::string sdDir = "/media/sdcard/osm_tiles";
::mkdir(sdDir.c_str(), 0755);
return sdDir;
}
std::string dir = getHomeDirPath() + "/.cache/bananarchy/osm";
ContactBook::ensureParentDir(dir + "/tile");
return dir;
}
std::vector<Waypoint> loadWaypoints() {
std::vector<Waypoint> list;
std::ifstream in(getWaypointsPath());
std::string line;
while (std::getline(in, line)) {
line = trimStr(line);
if (line.empty()) continue;
size_t t1 = line.find('\t');
size_t t2 = (t1 == std::string::npos) ? std::string::npos : line.find('\t', t1 + 1);
if (t1 != std::string::npos && t2 != std::string::npos) {
Waypoint w;
w.name = line.substr(0, t1);
w.lat = std::atof(line.substr(t1 + 1, t2 - t1 - 1).c_str());
w.lon = std::atof(line.substr(t2 + 1).c_str());
list.push_back(std::move(w));
}
}
if (list.empty()) {
list.push_back({"Kyiv Center", 50.4501, 30.5234});
list.push_back({"Helsinki (Nokia)", 60.1699, 24.9384});
list.push_back({"Zurich", 47.3769, 8.5417});
}
return list;
}
void saveWaypoints(const std::vector<Waypoint>& list) {
std::string path = getWaypointsPath();
ContactBook::ensureParentDir(path);
std::ofstream out(path, std::ios::trunc);
if (!out.is_open()) return;
for (const auto& w : list) {
out << w.name << "\t" << w.lat << "\t" << w.lon << "\n";
}
}
// Search place name via OpenStreetMap Nominatim
bool searchNominatim(const std::string& query, std::vector<Waypoint>& outResults) {
std::string encoded;
char hex[4];
for (unsigned char c : query) {
if (std::isalnum(c) || c == '-' || c == '_') encoded.push_back(static_cast<char>(c));
else if (c == ' ') encoded.push_back('+');
else {
std::snprintf(hex, sizeof(hex), "%%%02X", c);
encoded += hex;
}
}
std::string url = "https://nominatim.openstreetmap.org/search?format=jsonv2&limit=5&q=" + encoded;
std::string body;
if (!httpGet(url, body, nullptr, 6000, "Bananarchy-Navigator/1.0")) {
return false;
}
size_t pos = 0;
while ((pos = body.find("\"lat\":\"", pos)) != std::string::npos) {
pos += 7;
size_t latEnd = body.find('"', pos);
if (latEnd == std::string::npos) break;
double lat = std::atof(body.substr(pos, latEnd - pos).c_str());
size_t lonPos = body.find("\"lon\":\"", latEnd);
if (lonPos == std::string::npos) break;
lonPos += 7;
size_t lonEnd = body.find('"', lonPos);
if (lonEnd == std::string::npos) break;
double lon = std::atof(body.substr(lonPos, lonEnd - lonPos).c_str());
std::string disp = query;
size_t namePos = body.find("\"display_name\":\"", lonEnd);
if (namePos != std::string::npos && namePos - lonEnd < 600) {
namePos += 16;
size_t nameEnd = body.find('"', namePos);
if (nameEnd != std::string::npos) {
disp = body.substr(namePos, std::min<size_t>(36, nameEnd - namePos));
}
}
outResults.push_back({disp, lat, lon});
pos = lonEnd;
}
return !outResults.empty();
}
// Compute route via OSRM public router
bool fetchOsrmRoute(double lat1, double lon1, double lat2, double lon2,
std::vector<std::pair<double, double>>& outPath,
std::vector<RouteStep>& outSteps,
double& outTotalDistM) {
outPath.clear();
outSteps.clear();
char urlBuf[512];
std::snprintf(urlBuf, sizeof(urlBuf),
"https://router.project-osrm.org/route/v1/driving/"
"%.5f,%.5f;%.5f,%.5f?overview=full&geometries=geojson&steps=true",
lon1, lat1, lon2, lat2);
std::string body;
if (!httpGet(urlBuf, body, nullptr, 7000, "Bananarchy-Navigator/1.0")) {
// Fallback straight-line vector route when offline
outPath.push_back({lat1, lon1});
outPath.push_back({lat2, lon2});
outTotalDistM = haversineMeters(lat1, lon1, lat2, lon2);
double brng = bearingDegrees(lat1, lon1, lat2, lon2);
outSteps.push_back({std::string("Head ") + compassCardinal(brng) +
" toward destination",
outTotalDistM, lat2, lon2});
return true;
}
size_t distPos = body.find("\"distance\":");
if (distPos != std::string::npos) {
outTotalDistM = std::atof(body.substr(distPos + 11).c_str());
}
// Parse GeoJSON coordinates: "coordinates":[[lon,lat],[lon,lat],...]
size_t coordPos = body.find("\"coordinates\":[[");
if (coordPos != std::string::npos) {
size_t endPos = body.find("]]", coordPos);
std::string arr = body.substr(
coordPos + 15, (endPos == std::string::npos) ? std::string::npos : (endPos - coordPos - 14));
size_t p = 0;
while ((p = arr.find('[', p)) != std::string::npos) {
size_t rb = arr.find(']', p);
if (rb == std::string::npos) break;
std::string pairStr = arr.substr(p + 1, rb - p - 1);
size_t comma = pairStr.find(',');
if (comma != std::string::npos) {
double lon = std::atof(pairStr.substr(0, comma).c_str());
double lat = std::atof(pairStr.substr(comma + 1).c_str());
outPath.push_back({lat, lon});
}
p = rb + 1;
}
}
if (outPath.empty()) {
outPath.push_back({lat1, lon1});
outPath.push_back({lat2, lon2});
outTotalDistM = haversineMeters(lat1, lon1, lat2, lon2);
}
// Parse steps
size_t stepPos = 0;
while ((stepPos = body.find("\"maneuver\":", stepPos)) != std::string::npos) {
size_t typePos = body.find("\"type\":\"", stepPos);
std::string mtype = "Continue";
if (typePos != std::string::npos && typePos - stepPos < 250) {
typePos += 8;
size_t te = body.find('"', typePos);
if (te != std::string::npos) mtype = body.substr(typePos, te - typePos);
}
std::string modStr;
size_t modPos = body.find("\"modifier\":\"", stepPos);
if (modPos != std::string::npos && modPos - stepPos < 250) {
modPos += 12;
size_t me = body.find('"', modPos);
if (me != std::string::npos) modStr = body.substr(modPos, me - modPos);
}
std::string roadName;
size_t namePos = body.find("\"name\":\"", stepPos);
if (namePos != std::string::npos && namePos - stepPos < 450) {
namePos += 8;
size_t ne = body.find('"', namePos);
if (ne != std::string::npos) roadName = body.substr(namePos, ne - namePos);
}
double sDist = 0.0;
size_t sdPos = body.find("\"distance\":", stepPos);
if (sdPos != std::string::npos && sdPos - stepPos < 450) {
sDist = std::atof(body.substr(sdPos + 11).c_str());
}
std::string desc = mtype;
if (!modStr.empty()) desc += " " + modStr;
if (!roadName.empty()) desc += " on " + roadName;
outSteps.push_back({desc, sDist, lat2, lon2});
stepPos += 12;
}
return true;
}
class OsmTileCache {
public:
struct TilePixels {
bool ready = false;
bool loading = false;
std::vector<uint8_t> rgb; // 256 * 256 * 3
};
~OsmTileCache() {
stopWorker_.store(true);
cv_.notify_all();
if (worker_.joinable()) worker_.join();
}
void startWorker() {
worker_ = std::thread([this]() { workerLoop(); });
}
bool getTileRgb(int z, int x, int y, std::vector<uint8_t>& outRgb) {
int n = 1 << z;
x = ((x % n) + n) % n;
if (y < 0 || y >= n) return false;
std::string key = std::to_string(z) + "_" + std::to_string(x) + "_" + std::to_string(y);
std::lock_guard<std::mutex> lk(mtx_);
auto it = cache_.find(key);
if (it != cache_.end()) {
if (it->second.ready && it->second.rgb.size() == 256 * 256 * 3) {
outRgb = it->second.rgb;
return true;
}
return false;
}
// Check disk cache first
std::string diskPath = getOsmTileCacheDir() + "/" + key + ".png";
std::vector<uint8_t> rgb;
int w = 0, h = 0;
if (::access(diskPath.c_str(), R_OK) == 0 &&
loadPngRgb24(diskPath, &rgb, &w, &h) && w == 256 && h == 256) {
TilePixels tp;
tp.ready = true;
tp.rgb = rgb;
cache_[key] = std::move(tp);
outRgb = std::move(rgb);
return true;
}
// Queue async download
TilePixels pending;
pending.loading = true;
cache_[key] = std::move(pending);
if (queue_.size() < 16) {
queue_.push_back({z, x, y, key, diskPath});
cv_.notify_one();
}
return false;
}
bool consumeTileLoadedFlag() {
return tileLoaded_.exchange(false);
}
private:
struct TileReq {
int z;
int x;
int y;
std::string key;
std::string diskPath;
};
void workerLoop() {
while (!stopWorker_.load()) {
TileReq req;
{
std::unique_lock<std::mutex> lk(mtx_);
cv_.wait(lk, [this]() { return stopWorker_.load() || !queue_.empty(); });
if (stopWorker_.load()) break;
req = queue_.back();
queue_.pop_back();
}
std::string url = "https://tile.openstreetmap.org/" + std::to_string(req.z) +
"/" + std::to_string(req.x) + "/" + std::to_string(req.y) + ".png";
std::string pngBytes;
if (httpGet(url, pngBytes, nullptr, 5000, "Bananarchy-OSM-Navigator/1.0") &&
pngBytes.size() > 64) {
std::ofstream out(req.diskPath, std::ios::binary | std::ios::trunc);
if (out.is_open()) {
out.write(pngBytes.data(), static_cast<std::streamsize>(pngBytes.size()));
out.close();
}
std::vector<uint8_t> rgb;
int w = 0, h = 0;
if (loadPngRgb24(req.diskPath, &rgb, &w, &h) && w == 256 && h == 256) {
std::lock_guard<std::mutex> lk(mtx_);
if (cache_.size() > 36) {
cache_.clear();
}
cache_[req.key] = {true, false, std::move(rgb)};
tileLoaded_.store(true);
}
}
}
}
std::mutex mtx_;
std::condition_variable cv_;
std::unordered_map<std::string, TilePixels> cache_;
std::vector<TileReq> queue_;
std::atomic<bool> stopWorker_{false};
std::atomic<bool> tileLoaded_{false};
std::thread worker_;
};
int gps_run_main(int argc, char** argv) {
gRunning = 1;
bool isPreload = false;
std::string initCmd;
for (int i = 1; i < argc; ++i) {
if (!argv[i] || !argv[i][0]) continue;
if (std::strcmp(argv[i], "--preload") == 0) isPreload = true;
else if (std::strcmp(argv[i], "--test") == 0) {
// CLI GPS test mode
GpsStatus st;
runAsyncCmd("mmcli -m any --location-enable-gps-nmea --location-enable-gps-raw >/dev/null 2>&1");
::usleep(300000);
pollModemGpsStatus(st);
std::printf("Fix: %s (%dD) Sats: %d/%d HDOP: %.1f UTC: %s\n",
st.hasFix ? "LOCKED" : "SEARCHING", st.fixDimension,
st.satsUsed, st.satsInView, st.hdop, st.utcTime.c_str());
std::printf("Coords: %.6f, %.6f Alt: %.1fm Speed: %.1f km/h\n",
st.latitude, st.longitude, st.altitudeM, st.speedKmh);
std::printf("3GPP Cell: MCC=%s MNC=%s TAC=%s CID=%s\n",
st.mcc.c_str(), st.mnc.c_str(), st.tac.c_str(), st.cid.c_str());
return 0;
} else {
if (!initCmd.empty()) initCmd.push_back(' ');
initCmd += argv[i];
}
}
std::string forwarded = isPreload ? "NOP" : (initCmd.empty() ? "OPEN" : ("OPEN " + initCmd));
if (sendPluginCommand("gps", forwarded)) {
return 0;
}
std::string daemonPidPath = getPluginDaemonPidPath("gps");
std::string activePidPath = getRuntimeFile("xgps.pid");
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
int fifoFd = setupPluginDaemonFifo("gps");
struct sigaction sa {};
sa.sa_handler = handleSignal;
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, nullptr);
sigaction(SIGINT, &sa, nullptr);
NeoWindow neo;
if (!neo.create("xgps", "XGps", "GPS & OpenStreetMap Navigator")) {
if (fifoFd >= 0) ::close(fifoFd);
::unlink(daemonPidPath.c_str());
return 1;
}
neo.bindAsActiveContext();
OsmTileCache tileCache;
tileCache.startWorker();
GpsStatus gps;
std::vector<Waypoint> waypoints = loadWaypoints();
std::vector<std::pair<double, double>> routePath;
std::vector<RouteStep> routeSteps;
double routeTotalDistM = 0.0;
bool hasActiveRoute = false;
Waypoint activeDest{"", 0.0, 0.0};
// Map viewport state
double mapCenterLat = 50.4501;
double mapCenterLon = 30.5234;
int mapZoom = 13;
bool followGps = true;
bool keepGpsInBg = false;
bool visible = false;
int activeTab = 0; // 0=GPS Test, 1=OSM Map, 2=Navigate
bool showRawNmea = false;
int selectedRow = 0;
int scrollOffset = 0;
bool menuOpen = false;
int menuSel = 0;
bool searchModalOpen = false;
int64_t lastGpsPollMs = 0;
auto enableModemGps = [&]() {
if (!gps.gpsEnabled) {
gps.gpsEnabled = true;
runAsyncCmd(
"mmcli -m any --location-enable-gps-nmea --location-enable-gps-raw >/dev/null 2>&1; "
"mmcli -m any --location-set-gps-refresh-rate=2 >/dev/null 2>&1");
}
};
auto disableModemGpsIfIdle = [&]() {
if (gps.gpsEnabled && !keepGpsInBg) {
gps.gpsEnabled = false;
runAsyncCmd(
"mmcli -m any --location-disable-gps-nmea --location-disable-gps-raw >/dev/null 2>&1");
}
};
auto renderMapCanvas = [&](int canvasY, int canvasH) {
constexpr int canvasW = 240;
std::vector<uint32_t> fb(canvasW * canvasH, 0x1a242c);
double centerWx = 0.0, centerWy = 0.0;
latLonToWorldPx(mapCenterLat, mapCenterLon, mapZoom, centerWx, centerWy);
double topLeftWx = centerWx - canvasW / 2.0;
double topLeftWy = centerWy - canvasH / 2.0;
int startTileX = static_cast<int>(std::floor(topLeftWx / 256.0));
int startTileY = static_cast<int>(std::floor(topLeftWy / 256.0));
int endTileX = static_cast<int>(std::floor((topLeftWx + canvasW) / 256.0));
int endTileY = static_cast<int>(std::floor((topLeftWy + canvasH) / 256.0));
std::vector<uint8_t> tileRgb;
for (int ty = startTileY; ty <= endTileY; ++ty) {
for (int tx = startTileX; tx <= endTileX; ++tx) {
int dstX0 = static_cast<int>(std::lround(tx * 256.0 - topLeftWx));
int dstY0 = static_cast<int>(std::lround(ty * 256.0 - topLeftWy));
bool gotTile = tileCache.getTileRgb(mapZoom, tx, ty, tileRgb);
for (int py = 0; py < 256; ++py) {
int sy = dstY0 + py;
if (sy < 0 || sy >= canvasH) continue;
for (int px = 0; px < 256; ++px) {
int sx = dstX0 + px;
if (sx < 0 || sx >= canvasW) continue;
if (gotTile) {
size_t off = static_cast<size_t>((py * 256 + px) * 3);
uint32_t r = tileRgb[off];
uint32_t g = tileRgb[off + 1];
uint32_t b = tileRgb[off + 2];
fb[sy * canvasW + sx] = (r << 16) | (g << 8) | b;
} else if (px == 0 || py == 0 || px == 128 || py == 128) {
fb[sy * canvasW + sx] = 0x2c3e50;
}
}
}
}
}
XImage* img = XCreateImage(
neo.dpy, neo.visual, DefaultDepth(neo.dpy, neo.screen), ZPixmap, 0,
reinterpret_cast<char*>(fb.data()), canvasW, canvasH, 32, canvasW * 4);
if (img) {
XPutImage(neo.dpy, neo.pix, neo.gc, img, 0, 0, 0, canvasY, canvasW, canvasH);
img->data = nullptr;
XDestroyImage(img);
}
// Draw active route polyline overlay
if (hasActiveRoute && routePath.size() >= 2) {
for (size_t i = 0; i + 1 < routePath.size(); ++i) {
double wx1, wy1, wx2, wy2;
latLonToWorldPx(routePath[i].first, routePath[i].second, mapZoom, wx1, wy1);
latLonToWorldPx(routePath[i + 1].first, routePath[i + 1].second, mapZoom, wx2, wy2);
int x1 = static_cast<int>(std::lround(wx1 - topLeftWx));
int y1 = canvasY + static_cast<int>(std::lround(wy1 - topLeftWy));
int x2 = static_cast<int>(std::lround(wx2 - topLeftWx));
int y2 = canvasY + static_cast<int>(std::lround(wy2 - topLeftWy));
neoui_draw_line(x1, y1, x2, y2, 0x0066FF);
neoui_draw_line(x1 + 1, y1, x2 + 1, y2, 0x0066FF);
}
}
// Draw waypoints
for (const auto& w : waypoints) {
double wx, wy;
latLonToWorldPx(w.lat, w.lon, mapZoom, wx, wy);
int sx = static_cast<int>(std::lround(wx - topLeftWx));
int sy = canvasY + static_cast<int>(std::lround(wy - topLeftWy));
if (sx >= 4 && sx < canvasW - 4 && sy >= canvasY + 4 && sy < canvasY + canvasH - 4) {
neoui_fill_rect(sx - 3, sy - 3, 7, 7, 0xF39C12);
}
}
// Draw GPS position marker + center crosshair
if (gps.hasFix) {
double gwx, gwy;
latLonToWorldPx(gps.latitude, gps.longitude, mapZoom, gwx, gwy);
int gx = static_cast<int>(std::lround(gwx - topLeftWx));
int gy = canvasY + static_cast<int>(std::lround(gwy - topLeftWy));
if (gx >= 0 && gx < canvasW && gy >= canvasY && gy < canvasY + canvasH) {
neoui_fill_rect(gx - 4, gy - 4, 9, 9, 0xE74C3C);
neoui_draw_rect(gx - 5, gy - 5, 11, 11, 0xFFFFFF);
}
}
int cx = canvasW / 2;
int cy = canvasY + canvasH / 2;
neoui_draw_line(cx - 6, cy, cx + 6, cy, 0xF4D03F);
neoui_draw_line(cx, cy - 6, cx, cy + 6, 0xF4D03F);
};
auto render = [&]() {
if (!visible) return;
neo.bindAsActiveContext();
neoui_begin_frame();
std::string fixBadge = gps.hasFix
? (std::to_string(gps.fixDimension) + "D FIX")
: ("SATS " + std::to_string(gps.satsInView));
neoui_draw_header(kIconGlobe, gps.hasFix ? NEO_TEXT_GREEN : NEO_TEXT_YELLOW,
"GPS & Maps", fixBadge.c_str());
neoui_draw_tabs("GPS Test|OSM Map|Navigate", activeTab, 34, 24);
constexpr int kBodyY = 58;
constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H;
if (activeTab == 0) {
char line1[64], line2[64], line3[64], line4[64];
std::snprintf(line1, sizeof(line1), "Lat: %.6f Lon: %.6f",
gps.latitude, gps.longitude);
std::snprintf(line2, sizeof(line2), "Alt: %.1fm Spd: %.1fkm/h CRS: %.0f",
gps.altitudeM, gps.speedKmh, gps.courseDeg);
std::snprintf(line3, sizeof(line3), "Sats: %d/%d HDOP: %.1f UTC: %s",
gps.satsUsed, gps.satsInView, gps.hdop, gps.utcTime.c_str());
std::snprintf(line4, sizeof(line4), "3GPP: %s-%s TAC:%s CID:%s",
gps.mcc.c_str(), gps.mnc.c_str(), gps.tac.c_str(), gps.cid.c_str());
neoui_fill_rect(4, kBodyY + 2, 232, 74, neoui_color(NEO_COLOR_BG_ALT_EVEN));
neoui_draw_text(NEO_FONT_SMALL, gps.hasFix ? NEO_TEXT_GREEN : NEO_TEXT_YELLOW,
8, kBodyY + 4, 18, line1, 224);
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_LIGHT, 8, kBodyY + 22, 18, line2, 224);
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_WHITE, 8, kBodyY + 40, 18, line3, 224);
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_MUTED, 8, kBodyY + 58, 16, line4, 224);
if (showRawNmea) {
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 8, kBodyY + 80, 16,
"Live NMEA Stream ([OK] SNR Graph):", 224);
int ny = kBodyY + 98;
for (size_t i = 0; i < gps.rawNmea.size() && i < 6; ++i) {
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_LIGHT, 6,
ny + static_cast<int>(i) * 18, 18,
gps.rawNmea[i].c_str(), 228);
}
} else {
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 8, kBodyY + 80, 16,
"Satellite SNR (dB-Hz) ([OK] Raw NMEA):", 224);
int graphY = kBodyY + 100;
int graphH = 92;
neoui_fill_rect(6, graphY, 228, graphH, neoui_color(NEO_COLOR_BG_INPUT));
neoui_draw_rect(6, graphY, 228, graphH, neoui_color(NEO_COLOR_BORDER));
if (gps.satellites.empty()) {
neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_MUTED, 6,
graphY + 34, 228, 22,
"Acquiring GNSS satellites...");
} else {
int maxBars = std::min<int>(10, static_cast<int>(gps.satellites.size()));
int slotW = 220 / std::max(1, maxBars);
for (int i = 0; i < maxBars; ++i) {
const auto& s = gps.satellites[i];
int snrClamped = std::clamp(s.snr, 0, 50);
int barH = (snrClamped * (graphH - 22)) / 50;
int bx = 10 + i * slotW;
int by = graphY + graphH - 16 - barH;
uint32_t col = (s.snr >= 25) ? neoui_color(NEO_COLOR_SUCCESS)
: ((s.snr > 0) ? neoui_color(NEO_COLOR_ACCENT)
: neoui_color(NEO_COLOR_BORDER));
if (barH > 0) {
neoui_fill_rect(bx, by, std::max(6, slotW - 4), barH, col);
}
char prnStr[12];
std::snprintf(prnStr, sizeof(prnStr), "%02d", s.prn % 100);
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_MUTED, bx,
graphY + graphH - 15, 14, prnStr, slotW);
}
}
}
neoui_draw_softkeys("Menu", showRawNmea ? "SNR BARS" : "RAW NMEA", "Close");
} else if (activeTab == 1) {
int mapH = kBodyH - 24;
renderMapCanvas(kBodyY, mapH);
// Map bottom HUD strip
int hudY = kBodyY + mapH;
neoui_fill_rect(0, hudY, 240, 24, neoui_color(NEO_COLOR_BG_ALT_EVEN));
char hudBuf[80];
if (hasActiveRoute) {
double curLat = gps.hasFix ? gps.latitude : mapCenterLat;
double curLon = gps.hasFix ? gps.longitude : mapCenterLon;
double d = haversineMeters(curLat, curLon, activeDest.lat, activeDest.lon);
double b = bearingDegrees(curLat, curLon, activeDest.lat, activeDest.lon);
std::snprintf(hudBuf, sizeof(hudBuf), "To %s: %s (%s) Z%d",
activeDest.name.substr(0, 10).c_str(),
formatDistance(d).c_str(), compassCardinal(b), mapZoom);
} else {
std::snprintf(hudBuf, sizeof(hudBuf), "Z%d %.4f,%.4f [*/#]Zoom [5]Center",
mapZoom, mapCenterLat, mapCenterLon);
}
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 6, hudY + 3, 18, hudBuf, 228);
neoui_draw_softkeys("Menu", "CENTER GPS", "Back");
} else {
// Navigate tab: Waypoints + Route Steps
int rowH = 38;
int maxVis = kBodyH / rowH;
int totalItems = static_cast<int>(waypoints.size() + routeSteps.size());
if (totalItems == 0) {
neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 60,
240, 24, "No Waypoints");
} else {
selectedRow = std::clamp(selectedRow, 0, totalItems - 1);
if (selectedRow < scrollOffset) scrollOffset = selectedRow;
if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1;
for (int i = 0; i < maxVis && (scrollOffset + i) < totalItems; ++i) {
int idx = scrollOffset + i;
if (idx < static_cast<int>(waypoints.size())) {
const auto& w = waypoints[idx];
double curLat = gps.hasFix ? gps.latitude : mapCenterLat;
double curLon = gps.hasFix ? gps.longitude : mapCenterLon;
double d = haversineMeters(curLat, curLon, w.lat, w.lon);
double b = bearingDegrees(curLat, curLon, w.lat, w.lon);
char sub[64];
std::snprintf(sub, sizeof(sub), "%.4f, %.4f (%s)",
w.lat, w.lon, compassCardinal(b));
neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0,
kIconGlobe, NEO_TEXT_GREEN, w.name.c_str(), sub,
formatDistance(d).c_str());
} else {
const auto& st = routeSteps[idx - static_cast<int>(waypoints.size())];
neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0,
kIconOutCall, NEO_TEXT_YELLOW,
st.instruction.c_str(), "Route Step",
formatDistance(st.distanceM).c_str());
}
}
neoui_draw_scrollbar(236, kBodyY, kBodyH, totalItems, maxVis, scrollOffset);
}
neoui_draw_softkeys("Menu", "ROUTE TO", "Back");
}
if (searchModalOpen) {
neoui_draw_modal_box(6, 46, 228, 174, kIconSearch, NEO_TEXT_YELLOW,
"Search Place (OSM Nominatim)");
neoui_draw_input_box(12, 80, 216, 42, 1, "City, street, or lat,lon:",
neoui_input_get_text(), "Kyiv", 0);
neoui_draw_multitap_bar(12, 130, 216, 22, "[*] Mode [OK/Left] Search");
neoui_draw_softkeys("Search", "FIND", "Cancel");
} else if (menuOpen) {
neoui_draw_menu_popup(
"Search Place (OSM)|Save Current Location|Clear Active Route|Keep GPS in Background|Delete Waypoint",
nullptr, menuSel, 5);
}
neoui_end_frame();
};
auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("gps");
enableModemGps();
pollModemGpsStatus(gps);
if (gps.hasFix && followGps) {
mapCenterLat = gps.latitude;
mapCenterLon = gps.longitude;
}
lastGpsPollMs = nowMs();
visible = true;
neoui_show();
render();
};
auto closeWindow = [&]() {
if (!visible) return;
visible = false;
searchModalOpen = false;
menuOpen = false;
disableModemGpsIfIdle();
neoui_hide();
::unlink(activePidPath.c_str());
};
if (!isPreload) {
openWindow();
}
while (gRunning) {
for (const std::string& cmd : readFifoLines(fifoFd)) {
if (cmd == "NOP") continue;
if (cmd == "CLOSE") closeWindow();
else if (cmd == "RELOAD_THEME") {
neo.reloadTheme();
if (visible) render();
} else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) {
if (cmd == "OPEN map" || cmd == "OPEN maps" || cmd == "OPEN nav") {
activeTab = 1;
}
openWindow();
}
}
int64_t now = nowMs();
if ((visible || keepGpsInBg) && now - lastGpsPollMs >= 2000) {
lastGpsPollMs = now;
pollModemGpsStatus(gps);
if (gps.hasFix && followGps) {
mapCenterLat = gps.latitude;
mapCenterLon = gps.longitude;
}
if (visible) render();
}
if (tileCache.consumeTileLoadedFlag() && visible && activeTab == 1) {
render();
}
if (visible) {
neo.bindAsActiveContext();
int ev = neoui_poll_event(0);
while (ev != NEO_EV_NONE) {
if (ev == NEO_EV_EXPOSE || ev == NEO_EV_THEME_RELOAD) {
render();
} else if (ev == NEO_EV_CLOSE_REQ) {
closeWindow();
break;
} else if (ev == NEO_EV_SOFTKEY_LEFT) {
if (searchModalOpen) {
std::string q = trimStr(neoui_input_get_text());
searchModalOpen = false;
if (!q.empty()) {
neoui_show_toast("Searching OpenStreetMap...", 1500);
render();
std::vector<Waypoint> found;
if (searchNominatim(q, found)) {
for (const auto& w : found) waypoints.insert(waypoints.begin(), w);
saveWaypoints(waypoints);
mapCenterLat = found[0].lat;
mapCenterLon = found[0].lon;
followGps = false;
neoui_show_toast(("Found: " + found[0].name).c_str(), 2000);
} else {
neoui_show_toast("No results found", 2000);
}
}
render();
} else {
menuOpen = !menuOpen;
menuSel = 0;
render();
}
} else if (ev == NEO_EV_SOFTKEY_RIGHT) {
if (searchModalOpen) {
searchModalOpen = false;
render();
} else if (menuOpen) {
menuOpen = false;
render();
} else if (activeTab != 0) {
activeTab = 0;
render();
} else {
closeWindow();
break;
}
} else if (ev == NEO_EV_KEY_PRESS) {
int k = neoui_event_key();
if (menuOpen) {
if (k == NEO_KEY_UP) menuSel = (menuSel + 4) % 5;
else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 5;
else if (k == NEO_KEY_OK) {
menuOpen = false;
if (menuSel == 0) {
searchModalOpen = true;
neoui_input_reset("");
} else if (menuSel == 1) {
double lat = gps.hasFix ? gps.latitude : mapCenterLat;
double lon = gps.hasFix ? gps.longitude : mapCenterLon;
waypoints.insert(waypoints.begin(),
{"Saved Fix " + gps.utcTime, lat, lon});
saveWaypoints(waypoints);
neoui_show_toast("Location saved to Waypoints", 1800);
} else if (menuSel == 2) {
hasActiveRoute = false;
routePath.clear();
routeSteps.clear();
} else if (menuSel == 3) {
keepGpsInBg = !keepGpsInBg;
neoui_show_toast(
keepGpsInBg ? "Background GPS: ON" : "Background GPS: OFF", 1800);
} else if (menuSel == 4 && activeTab == 2 && selectedRow >= 0 &&
selectedRow < static_cast<int>(waypoints.size())) {
waypoints.erase(waypoints.begin() + selectedRow);
saveWaypoints(waypoints);
}
} else if (k == NEO_KEY_BACK || k == NEO_KEY_END) {
menuOpen = false;
}
render();
} else if (searchModalOpen) {
if (k == NEO_KEY_OK) {
std::string q = trimStr(neoui_input_get_text());
searchModalOpen = false;
if (!q.empty()) {
std::vector<Waypoint> found;
if (searchNominatim(q, found)) {
for (const auto& w : found) waypoints.insert(waypoints.begin(), w);
saveWaypoints(waypoints);
mapCenterLat = found[0].lat;
mapCenterLon = found[0].lon;
followGps = false;
}
}
} else if (k == NEO_KEY_STAR) {
neoui_input_cycle_mode();
} else if (k == NEO_KEY_BACK) {
neoui_input_backspace();
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
neoui_input_feed_key(k);
}
render();
} else if (activeTab == 1) {
// Map pan / zoom / tab switch
double panStep = 48.0;
double wx, wy;
latLonToWorldPx(mapCenterLat, mapCenterLon, mapZoom, wx, wy);
if (k == NEO_KEY_UP || k == NEO_KEY_2) {
wy -= panStep;
worldPxToLatLon(wx, wy, mapZoom, mapCenterLat, mapCenterLon);
followGps = false;
} else if (k == NEO_KEY_DOWN || k == NEO_KEY_8) {
wy += panStep;
worldPxToLatLon(wx, wy, mapZoom, mapCenterLat, mapCenterLon);
followGps = false;
} else if (k == NEO_KEY_4) {
wx -= panStep;
worldPxToLatLon(wx, wy, mapZoom, mapCenterLat, mapCenterLon);
followGps = false;
} else if (k == NEO_KEY_6) {
wx += panStep;
worldPxToLatLon(wx, wy, mapZoom, mapCenterLat, mapCenterLon);
followGps = false;
} else if (k == NEO_KEY_LEFT) {
activeTab = 0;
} else if (k == NEO_KEY_RIGHT) {
activeTab = 2;
} else if (k == NEO_KEY_STAR || k == NEO_KEY_1) {
mapZoom = std::max(2, mapZoom - 1);
} else if (k == NEO_KEY_HASH || k == NEO_KEY_3) {
mapZoom = std::min(18, mapZoom + 1);
} else if (k == NEO_KEY_OK || k == NEO_KEY_5 || k == NEO_KEY_0) {
followGps = true;
if (gps.hasFix) {
mapCenterLat = gps.latitude;
mapCenterLon = gps.longitude;
}
neoui_show_toast("Following GPS fix", 1200);
} else if (k == NEO_KEY_CALL) {
searchModalOpen = true;
neoui_input_reset("");
} else if (k == NEO_KEY_END || k == NEO_KEY_BACK) {
closeWindow();
break;
}
render();
} else {
if (k == NEO_KEY_LEFT) {
activeTab = (activeTab + 2) % 3;
selectedRow = 0;
scrollOffset = 0;
} else if (k == NEO_KEY_RIGHT) {
activeTab = (activeTab + 1) % 3;
selectedRow = 0;
scrollOffset = 0;
} else if (activeTab == 0) {
if (k == NEO_KEY_OK) {
showRawNmea = !showRawNmea;
} else if (k == NEO_KEY_CALL) {
pollModemGpsStatus(gps);
neoui_show_toast("Refreshed GNSS status", 1200);
} else if (k == NEO_KEY_END || k == NEO_KEY_BACK) {
closeWindow();
break;
}
} else if (activeTab == 2) {
if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow;
else if (k == NEO_KEY_DOWN) ++selectedRow;
else if (k == NEO_KEY_CALL) {
searchModalOpen = true;
neoui_input_reset("");
} else if (k == NEO_KEY_OK) {
if (selectedRow >= 0 &&
selectedRow < static_cast<int>(waypoints.size())) {
activeDest = waypoints[selectedRow];
double startLat = gps.hasFix ? gps.latitude : mapCenterLat;
double startLon = gps.hasFix ? gps.longitude : mapCenterLon;
neoui_show_toast("Computing OSM route...", 1500);
render();
if (fetchOsrmRoute(startLat, startLon, activeDest.lat,
activeDest.lon, routePath, routeSteps,
routeTotalDistM)) {
hasActiveRoute = true;
mapCenterLat = activeDest.lat;
mapCenterLon = activeDest.lon;
activeTab = 1;
neoui_show_toast(
("Route: " + formatDistance(routeTotalDistM)).c_str(),
2000);
}
}
} else if (k == NEO_KEY_END || k == NEO_KEY_BACK) {
closeWindow();
break;
}
}
render();
}
}
ev = neoui_poll_event(0);
}
} else {
while (XPending(neo.dpy) > 0) {
XEvent xev;
XNextEvent(neo.dpy, &xev);
}
}
struct pollfd pfds[2] {};
pfds[0] = { ConnectionNumber(neo.dpy), POLLIN, 0 };
pfds[1] = { fifoFd, POLLIN, 0 };
int timeoutMs = (visible || keepGpsInBg) ? 500 : -1;
::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs);
}
disableModemGpsIfIdle();
if (fifoFd >= 0) ::close(fifoFd);
::unlink(getPluginFifoPath("gps").c_str());
::unlink(daemonPidPath.c_str());
return 0;
}
int gps_plugin_init(const DwmHostApi* host) {
if (host && host->spawn_plugin) {
host->spawn_plugin("gps", "--preload");
}
return 0;
}
} // namespace
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
DWM_PLUGIN_API_VERSION,
"gps",
"GPS reception test utility and OpenStreetMap navigator",
gps_plugin_init,
nullptr,
nullptr,
nullptr,
nullptr,
gps_run_main
};