| 209 | def _try_gpsd(host='127.0.0.1', port=2947, timeout=2): |
| 210 | """Return an open gpsd socket if gpsd is running and responsive, else None.""" |
| 211 | sock = None |
| 212 | try: |
| 213 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 214 | sock.settimeout(timeout) |
| 215 | sock.connect((host, port)) |
| 216 | sock.sendall(b'?WATCH={"enable":true,"json":true}\n') |
| 217 | data = sock.recv(2048).decode('utf-8', errors='ignore') |
| 218 | if '"class"' in data: |
| 219 | sock.settimeout(None) |
| 220 | return sock |
| 221 | except Exception: |
| 222 | pass |
| 223 | if sock: |
| 224 | try: |
| 225 | sock.close() |
| 226 | except Exception: |
| 227 | pass |
| 228 | return None |
| 229 | |
| 230 | |
| 231 | # /dev/serial/by-id name fragments that mark a USB GPS receiver. Shared with |
| 232 | # cyd_serial_bridge.detect_port so its auto-detect never claims a GPS puck. |
| 233 | GPS_BYID_KEYWORDS = ('gps', 'u-blox', 'ublox', 'nmea', 'gnss', 'bn-', 'vk-') |
| 234 | |
| 235 | |
| 236 | def detect_gps_device(exclude_ports=None): |
| 237 | """Auto-detect a GPS source. |
| 238 | |
| 239 | Detection has four stages, in order of confidence: |
| 240 | 0. gpsd socket — returns the sentinel string 'gpsd' if gpsd is running. |
| 241 | This avoids port conflicts when gpsd already owns the serial device. |
| 242 | 1. by-id symlinks containing GPS keywords (gps, u-blox, nmea, gnss, …). |
| 243 | 2. by-id symlinks NOT containing known-ESP32 markers — probe for NMEA. |
| 244 | 3. raw ttyACM/ttyUSB/ttyS/ttyAMA — probe for NMEA at multiple bauds. |
| 245 | Covers native UART ports (e.g. Raspberry Pi /dev/ttyAMA0, /dev/serial0). |