GPS Tracking using MQTT and ThingsBoard
GPS Tracking using MQTT and ThingsBoard
Section titled “GPS Tracking using MQTT and ThingsBoard”Summary
Section titled “Summary”This guide explains how to configure MikroTik routers with GPS capabilities to track their location and transmit coordinates via MQTT to ThingsBoard, a popular open-source IoT platform. The integration enables real-time vehicle tracking, asset monitoring, and geographic visualization through ThingsBoard’s map widgets. RouterOS devices with GPS support, such as the LtAP series, can function as MQTT publishers sending latitude, longitude, and altitude data to a centralized ThingsBoard server acting as the MQTT broker. This setup is suitable for fleet management, logistics tracking, and any scenario requiring geographic position monitoring of remote devices.
The architecture supports multiple deployment options including cloud-hosted ThingsBoard instances, locally installed servers, or containerized ThingsBoard running on a more powerful RouterOS device like a Cloud Hosted Router (CHR). The MQTT protocol provides efficient, lightweight communication suitable for cellular-connected devices where bandwidth may be limited. ThingsBoard’s built-in visualization tools allow quick creation of dashboards displaying tracked positions on interactive maps with location history.
Introduction
Section titled “Introduction”Many RouterOS devices include GPS hardware enabling precise location determination. The GPS receiver provides latitude, longitude, altitude, speed, and heading information that can be leveraged for tracking applications. Rather than storing this data locally, transmitting it to a central server enables real-time monitoring and historical analysis. This guide demonstrates how to achieve this by publishing GPS telemetry from RouterOS to ThingsBoard using the MQTT protocol.
ThingsBoard serves as both the MQTT broker receiving data from tracked devices and the visualization platform displaying locations on maps. The platform offers cloud hosting at thingsboard.cloud for quick deployment or can be installed locally for self-hosted solutions. Additionally, MikroTik’s Container feature enables running ThingsBoard entirely on RouterOS devices with sufficient resources, creating an all-RouterOS tracking solution where tracked devices communicate with a central RouterOS server running the ThingsBoard broker.
GPS tracking via MQTT suits scenarios including vehicle fleet management where company cars or delivery vehicles need monitoring, asset tracking for valuable equipment that moves between locations, remote site monitoring where field equipment requires position verification, and personal tracking for high-value shipments or personnel safety applications. The MQTT protocol’s lightweight nature makes it efficient for cellular connections where data costs matter, while ThingsBoard’s robust visualization tools transform raw coordinates into actionable intelligence.
Prerequisites
Section titled “Prerequisites”This configuration requires RouterOS devices with GPS hardware and specific packages installed. The gps package provides GPS receiver functionality and data access through the GPS monitor command. The iot package enables MQTT client capabilities for publishing data to the ThingsBoard broker. Verify package availability before beginning configuration:
/system package print where name=gps/system package print where name=iotDevices suitable for GPS tracking include the LtAP mini and LtAP models designed specifically for mobile applications, certain hEX and other routers with USB GPS module support, and any RouterOS device with USB ports that can accommodate a USB GPS receiver. The tracking device must have clear sky access for GPS signal reception, which limits indoor deployment without external antenna placement.
ThingsBoard deployment requires either a cloud account at thingsboard.cloud or a local installation. Local installations demand at least 2GB RAM for standard deployments or 1GB RAM with minimal system load. Architecture support includes ARM64 and AMD64 systems. Containerized ThingsBoard on RouterOS requires a CHR or high-end hardware RouterOS device with sufficient resources to run the container alongside normal router functions.
Architecture Overview
Section titled “Architecture Overview”The tracking system architecture consists of three primary components working together. GPS-enabled RouterOS devices function as MQTT publishers, capturing their current position at regular intervals and transmitting the data to the broker. The MQTT broker, typically a ThingsBoard instance, receives published data from all tracked devices and stores it for retrieval. The visualization layer, accessed through ThingsBoard’s web interface, displays current positions on maps and provides historical tracking through dashboard widgets.
Data flows from GPS receiver to visualization through a defined sequence. The RouterOS GPS module receives signals from satellites and calculates position coordinates. The RouterOS script extracts relevant data (latitude, longitude, altitude) and formats it as a JSON message. The MQTT client publishes the formatted message to the ThingsBoard broker on the configured topic. ThingsBoard receives the message, associates it with the correct device based on credentials, and updates the device’s telemetry data. The dashboard widget queries ThingsBoard for the latest telemetry and renders the position on a map.
ThingsBoard Configuration
Section titled “ThingsBoard Configuration”Initial Setup
Section titled “Initial Setup”Begin by accessing your ThingsBoard instance through its web management portal. Log in with administrator credentials and navigate to the Devices section, accessible from the main navigation menu. Click the Add Device button (typically a plus icon) to create a new device entry that will represent your tracked RouterOS device. Enter a descriptive name such as “LTAP-Vehicle-01” to identify this specific tracked unit, then confirm device creation.
After creating the device, click on its entry in the device list to access detailed configuration. Navigate to the Details section showing general information about the device. Locate the Device Credentials section displaying authentication information. The default credential type for new devices uses an access token mechanism. Click Manage Credentials or the appropriate button to reveal the access token value. Copy this token and store it securely, as it serves as the authentication password for MQTT connections from this device.
The access token method represents the simplest authentication scenario suitable for initial configuration and testing. Each device receives a unique access token that identifies it to ThingsBoard and associates incoming telemetry data with the correct device record. More sophisticated authentication using X.509 certificates provides enhanced security for production deployments, but the access token approach enables rapid validation of the complete data pipeline before implementing security hardening.
MQTT Topic Structure
Section titled “MQTT Topic Structure”ThingsBoard expects MQTT messages on specific topic patterns depending on the data type being transmitted. The telemetry topic v1/devices/me/telemetry carries general sensor data including GPS coordinates. The attributes topic v1/devices/me/attributes publishes device properties or configuration values. The RPC topic v1/devices/me/rpc receives commands from ThingsBoard to the device.
Messages must be formatted as valid JSON objects containing key-value pairs representing the telemetry data. For GPS tracking, the message includes latitude, longitude, and optionally altitude values. ThingsBoard automatically parses these values and makes them available for dashboard widgets:
{"latitude": 56.969862, "longitude": 24.162425, "altitude": 31.8}The topic structure follows ThingsBoard’s conventions for MQTT API communication. The v1 prefix indicates API version one. The devices component specifies communication with device entities. The me placeholder represents the current device being configured, with the actual device identified through the MQTT username (access token) rather than topic content.
RouterOS MQTT Configuration
Section titled “RouterOS MQTT Configuration”Broker Configuration
Section titled “Broker Configuration”Configure the RouterOS MQTT broker connection to point at your ThingsBoard instance. The broker configuration defines how the router connects to ThingsBoard and what credentials it uses for authentication. From the RouterOS command line, create a broker entry specifying the ThingsBoard server address, port, and authentication parameters.
For non-SSL connections suitable for local testing or VPN-accessible brokers:
/iot/mqtt/brokers/add name=tb address=192.0.2.100 port=1883 username=YOUR_ACCESS_TOKENFor SSL connections recommended for public-access deployments:
/iot/mqtt/brokers/add name=tb address=203.0.113.50 port=8883 username=YOUR_ACCESS_TOKEN ssl=yesThe broker configuration parameters include the name (used when referencing this broker in scripts), the address (IP or hostname of the ThingsBoard server), the port (1883 for non-SSL MQTT, 8883 for SSL MQTT), the username (access token from ThingsBoard device credentials), and the ssl flag (yes to enable encrypted communication). SSL communication protects authentication credentials and location data from interception, which is essential when transmitting over cellular networks or public internet connections.
Verify the broker configuration is correct:
/iot/mqtt/brokers/print/iot/mqtt/brokers/monitor tbThe print command displays all configured brokers with their settings. The monitor command shows current connection status including connection state, last error if any, and message statistics. A successful connection shows state as “running” with no error messages.
Testing MQTT Publish
Section titled “Testing MQTT Publish”Before implementing automated scripts, verify basic MQTT connectivity by publishing a test message:
/iot/mqtt/publish broker="tb" topic="v1/devices/me/telemetry" message="{\"test\":\"123\"}"This command sends a simple test message to verify the broker connection works. After execution, check ThingsBoard’s device telemetry page to confirm the test message was received. The “Latest telemetry” section should display the test key-value pair. If the test message does not appear, verify broker connectivity, check the access token matches the device credentials in ThingsBoard, and confirm network connectivity to the ThingsBoard MQTT port.
For troubleshooting connection issues, examine the broker monitor output for error messages, verify firewall rules permit outbound MQTT traffic on ports 1883 or 8883, and confirm the ThingsBoard MQTT service is running and accessible from the RouterOS device’s network location.
GPS Data Publishing Script
Section titled “GPS Data Publishing Script”Script Creation
Section titled “Script Creation”Create a RouterOS script that captures GPS coordinates and publishes them via MQTT. The script reads current GPS position, formats the data as JSON, and sends it to ThingsBoard. This script will be executed on a schedule to provide regular position updates.
/system/script/add name=mqttgps owner=admin policy="ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon" source="\:local broker \"tb\"\:local topic \"v1/devices/me/telemetry\"\\:global lat\:global lon\:global alt1\:global alt2\\:put (\"[*] Capturing GPS coordinates...\")\/system gps monitor once do={\:set \$lat \$(\"latitude\");\:set \$lon \$(\"longitude\");\:set \$alt1 \$(\"altitude\")}\\:set \$alt2 [:pick \$alt1 0 [find \$alt1 \" m\"]]\\:local message \"{\\\"latitude\\\":\$lat,\\\"longitude\\\":\$lon,\\\"altitude\\\":\$alt2}\"\\:if (\$lat != \"none\") do={\:put (\"[*] Sending message to MQTT broker...\");\/iot mqtt publish broker=\$broker topic=\$topic message=\$message} else={:put (\"[*] Latitude=none, not posting anything!\");:log info \"Latitude=none, not posting anything!\"}"The script begins by defining configuration variables for the broker name and MQTT topic. It then declares global variables to hold GPS coordinate values. The GPS monitor command retrieves current position data from the GPS receiver, with the once parameter indicating a single reading rather than continuous monitoring. The script captures latitude, longitude, and altitude values from the GPS monitor output.
The altitude value from GPS includes a “m” suffix for meters, which must be removed for valid JSON formatting. The script uses the pick and find functions to extract only the numeric portion of the altitude value. The message variable constructs a JSON object containing the three coordinate values with appropriate escaping for RouterOS script syntax.
The script includes conditional logic to handle GPS reception failure. If latitude equals “none” (indicating the GPS receiver cannot obtain satellite signals), the script logs a message and skips the MQTT publish. This prevents sending invalid data to ThingsBoard and provides notification of GPS issues through the system log.
Script Execution
Section titled “Script Execution”Execute the script manually to verify it functions correctly:
/system/script/run mqttgpsThe output displays GPS coordinate capture and MQTT transmission:
[*] Capturing GPS coordinates... date-and-time: feb/01/2023 10:39:37 latitude: 56.969862 longitude: 24.162425 altitude: 31.799999 m speed: 1.000080 km/h destination-bearing: none true-bearing: 153.089996 deg. True magnetic-bearing: 0.000000 deg. Mag valid: yes satellites: 6 fix-quality: 1 horizontal-dilution: 1.42 data-age: 0s[*] Sending message to MQTT broker...The GPS monitor output shows all available position data including the three primary coordinates (latitude, longitude, altitude), signal quality indicators (satellites, fix-quality, horizontal-dilution), and movement data (speed, bearing). The script only uses the three coordinates for transmission, but this comprehensive output aids troubleshooting when investigating GPS reception issues.
After execution, verify the data appeared in ThingsBoard under the device’s Latest Telemetry section. The latitude, longitude, and altitude keys should appear with their corresponding values. If the data is missing, review the troubleshooting steps for MQTT connectivity and verify the script executed without error messages.
Scheduled Automation
Section titled “Scheduled Automation”Configure the RouterOS scheduler to execute the GPS publishing script at regular intervals. The interval determines how frequently position updates are sent to ThingsBoard. More frequent updates provide smoother tracking visualization but consume more cellular data and may exceed MQTT message rate limits on the ThingsBoard instance.
/system/scheduler/add name=mqttgpsscheduler interval=30s on-event="/system/script/run mqttgps"This configuration runs the script every 30 seconds. For battery-powered or data-sensitive applications, increasing the interval to 60 seconds or longer reduces power consumption and data usage. Consider the trade-off between update granularity and resource consumption when selecting the interval value.
Additional scheduler options include setting start date and time, configuring repeat count for limited-duration tracking, and defining maximum run time. For continuous tracking applications, the default configuration (no start time, infinite repeat count) provides ongoing operation until manually disabled.
ThingsBoard Dashboard Configuration
Section titled “ThingsBoard Dashboard Configuration”Creating Map Widgets
Section titled “Creating Map Widgets”ThingsBoard provides map visualization widgets through its Widget Library. To display GPS coordinates on a map, navigate to your ThingsBoard dashboard (or create a new dashboard using the Add Widget button). In the dashboard edit mode, locate the entity alias or device filter that specifies which tracked device to display. Select the latitude and longitude keys from the device telemetry, then click the Show on Widget button to begin widget creation.
In the widget bundle selector, find the Maps bundle containing various map visualization options. Select the appropriate map widget type based on your visualization needs. The “Map” widget displays the current device position with a marker. The “Map (with tracks)” widget shows position history as a path on the map. Choose the variant that best suits your monitoring requirements.
After selecting the widget type, choose the target dashboard (existing or new) and configure widget appearance options including title, icon, and default zoom level. Save the widget configuration to add it to the dashboard. The widget immediately begins displaying data from the tracked device if current telemetry is available.
Dashboard Organization
Section titled “Dashboard Organization”Organize multiple tracked devices on a single dashboard for comprehensive fleet visibility. Create a dashboard entity (rather than a specific device dashboard) and add map widgets for each tracked device. Configure entity aliases that resolve to all tracked device entities, allowing widgets to automatically include all devices in the fleet.
For large deployments with many tracked units, consider grouping devices by vehicle type, geographic region, or operational status. ThingsBoard’s filter capabilities enable dynamic dashboards showing only devices matching specific criteria. Alarms and thresholds can highlight devices that have stopped moving, departed from designated areas, or exceeded speed limits.
Deployment Considerations
Section titled “Deployment Considerations”Cellular Data Optimization
Section titled “Cellular Data Optimization”MQTT’s lightweight protocol design minimizes data consumption for GPS tracking applications. Each position update message contains only the JSON-formatted coordinates, typically under 100 bytes per message. At 30-second intervals, a single device consumes approximately 200KB per hour or 5MB per day for position data alone. Additional message overhead from MQTT protocol headers and TCP/IP stacks increases this figure but remains manageable on most cellular data plans.
Consider implementing conditional publishing to reduce update frequency when the device is stationary. The script can compare new coordinates against the previous position and only publish when movement exceeds a threshold distance. This stationary filtering dramatically reduces data consumption for vehicles that park for extended periods.
SSL encryption adds approximately 40-60 bytes of overhead per MQTT message due to TLS handshake and certificate data. For cost-sensitive deployments, non-SSL MQTT over VPN tunnels provides security while reducing per-message data consumption. Evaluate the specific requirements of your deployment to select the appropriate balance between security and efficiency.
Power Consumption
Section titled “Power Consumption”GPS receivers and cellular modems consume significant power, making power management critical for battery-powered deployments. The LtAP series includes cellular modem capabilities but requires stable power input for continuous operation. External battery solutions or vehicle power connections provide necessary power for extended tracking scenarios.
RouterOS power management features can reduce consumption between position updates. Disabling unused interfaces, reducing cellular modem transmit power when strong signals are available, and scheduling GPS receiver activation only when needed all contribute to extended battery operation. Test power consumption under realistic operating conditions to ensure adequate power supply for expected deployment duration.
GPS Signal Considerations
Section titled “GPS Signal Considerations”GPS reception requires clear sky views for satellite signal acquisition. Vehicle installations should position the GPS antenna with unobstructed sky access, typically on the vehicle roof or through specialized GPS antennas designed for through-glass installation. Metallic window tinting, vehicle structural elements, and underground locations all degrade or prevent GPS reception.
The GPS monitor output includes signal quality indicators that help diagnose reception issues. The “satellites” value shows how many satellites the receiver has acquired (typically 8-12 for good reception). The “fix-quality” value of 1 indicates standard GPS accuracy (within approximately 5 meters), while higher values indicate degraded accuracy. The “horizontal-dilution” value represents position accuracy degradation, with lower values indicating better accuracy (values under 2 indicate good reception).
Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”GPS receiving “none” coordinates typically indicates satellite reception problems. Verify the GPS antenna has clear sky view, check antenna cable connections for damage or loose fittings, and confirm the GPS receiver is receiving power and functioning. Some indoor or urban canyon locations may never achieve adequate GPS reception regardless of configuration.
MQTT connection failures manifest as connection errors in broker monitor output or failed publish operations. Verify the ThingsBoard server is accessible from the RouterOS device network location, confirm the access token matches the device credentials exactly, and check that firewall rules permit outbound MQTT traffic on the configured port. ThingsBoard server logs often provide additional detail about connection rejection reasons.
Data appearing in ThingsBoard but not updating on maps indicates widget configuration issues rather than data transmission problems. Verify the widget is configured to use the correct entity (device) and the latitude/longitude key names match exactly what the script publishes. Check ThingsBoard entity attributes to confirm the latest telemetry contains the expected keys.
Monitoring Commands
Section titled “Monitoring Commands”/system gps printDisplays GPS receiver status including port configuration, power status, and current satellite data summary.
/system gps monitor onceProvides detailed position output including all coordinate values and signal quality metrics. Use this command when investigating GPS reception issues.
/iot/mqtt/brokers/monitor tbShows MQTT broker connection status including state, statistics, and any error messages. Use this to verify ongoing connectivity to ThingsBoard.
/log print where message~"mqttgps"Filters system logs for messages from the GPS tracking script, helpful for reviewing script execution history and diagnosing issues.
Security Recommendations
Section titled “Security Recommendations”SSL MQTT Communication
Section titled “SSL MQTT Communication”Enable SSL MQTT (port 8883) for all production deployments transmitting over public or untrusted networks. SSL encryption protects access tokens from interception during authentication and prevents location data eavesdropping. Configure the broker with the ssl=yes parameter and ensure the ThingsBoard instance has valid SSL certificates configured.
Credential Management
Section titled “Credential Management”Store access tokens securely and rotate them periodically. If an access token is compromised, generate a new one in ThingsBoard and update the RouterOS broker configuration immediately. Avoid hardcoding tokens in script source code that might be exposed through configuration exports.
Network Security
Section titled “Network Security”Configure firewall rules to restrict MQTT traffic to the specific ThingsBoard server address rather than permitting connections to any destination on ports 1883/8883. Consider implementing VPN tunnels for additional network-layer security, particularly when using non-SSL MQTT.
Related Resources
Section titled “Related Resources”Related Topics
Section titled “Related Topics”- MQTT and ThingsBoard Configuration - General MQTT integration with ThingsBoard
- GPS Overview - RouterOS GPS functionality
- Container - ThingsBoard MQTT/HTTP Server - Running ThingsBoard in RouterOS containers
- Scheduler - RouterOS task scheduling
- RouterOS Scripts - Scripting automation
Configuration Commands
Section titled “Configuration Commands”/iot/mqtt/brokers/add- Create MQTT broker configuration/iot/mqtt/publish- Send MQTT message manually/system/gps/monitor- Read current GPS position/system/script/add- Create automation script/system/scheduler/add- Schedule script execution