Open-source IoT Platform

Device management, data collection, processing and visualization
for your IoT projects
Learn about Thingsboard

Wednesday, December 21, 2016

GPS data upload and visualization using LinkIt ONE and Thingsboard

Thingsboard is an open-source server-side platform that allows you to monitor and control IoT devices. It is free for both personal and commercial usage and you can deploy it anywhere. If this is your first experience with the platform we recommend to review what-is-thingsboard page and getting-started guide.

This sample application shows capability to track GPS location of LinkIt ONE device and further visualization on the map. It performs collection of latitude and longitude values produced by GPS module. Collected data is pushed to Thingsboard for storage and visualization. The purpose of this application is to demonstrate Thingsboard data collection API and visualization capabilities.

The GPS module is built-in module of LinkIt ONE. LinkIt ONE pushes data to Thingsboard server via MQTT protocol by using PubSubClient library for Arduino. Data is visualized using map widget which is part of customizable dashboard. The application that is running on LinkIt ONE is written using Arduino SDK which is quite simple and easy to understand.

Once you complete this sample/tutorial, you will see your device GPS and battery data on the following dashboard.

image

Prerequisites

You will need to Thingsboard server up and running. Use either Live Demo or Installation Guide to install Thingsboard.

This tutorial was prepared for Windows OS users. However it is possible to run it on other OS (Linux or MacOS).

List of hardware

  • LinkIt One

    GPS and WIFI Antenna are shipped with board.

Thingsboard configuration

Note Thingsboard configuration steps are necessary only in case of local Thingsboard installation. If you are using Live Demo instance all entities are pre-configured for your demo account. However, we recommend to review this steps because you will still need to get device access token to send requests to Thingsboard.

Provision your device

This step contains instructions that are necessary to connect your device to Thingsboard.

Open Thingsboard Web UI (http://localhost:8080) in browser and login as tenant administrator

Goto “Devices” section. Click “+” button and create device with name “LinkIt One Demo Device”.

image

Once device created, open its details and click “Manage credentials”.

Copy auto-generated access token from the “Access token” field. Please save this device token. It will be referred to later as $ACCESS_TOKEN.

image

Click “Copy Device ID” in device details to copy your device id to clipboard. Paste your device id to some place, this value will be used in further steps.

Provision your dashboard

This step contains instructions that are necessary to provision new dashboard with map widgets to Thingsboard.

Open “Docker Quickstart Terminal” and download file containing demo dashboard JSON:

curl -L https://thingsboard.io/docs/samples/linkit-one/resources/linkit_one_gps_dashboard.json > linkit_one_gps_dashboard.json

Update dashboard configuration with your device Id (obtained in previous step) by issuing the following command:

sed -i "s/{DEVICE_ID}/<your device id>/" linkit_one_gps_dashboard.json

Obtain JWT token by issuing login POST command:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{"username":"[email protected]", "password":"tenant"}' 'http://localhost:8080/api/auth/login'

You will receive response in the following format:

{"token":"$YOUR_JSON_TOKEN", "refreshToken": "$REFRESH_TOKEN"}

copy $YOUR_JSON_TOKEN to some place. Note that it will be valid for 15 minutes by default.

Execute dashboard upload command:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'X-Authorization: Bearer $YOUR_JSON_TOKEN' -d "@linkit_one_gps_dashboard.json" 'http://localhost:8080/api/dashboard'

Programming the LinkIt One device

If you already familiar with basics of LinkIt One programming using Arduino IDE you can skip the following step and proceed with step 2.

Step 1. LinkIt ONE and Arduino IDE setup.

In order to start programming LinkIt One device you will need Arduino IDE installed and all related libraries. Please follow this guide in order to install the Arduino IDE and LinkIt One SDK:

It’s recommended to update your firmware by following this guide. To try your first LinkIt One sample, please follow this guide.

Step 2. PubSubClient library installation.

Open Arduino IDE and go to Sketch -> Include Library -> Manage Libraries. Find PubSubClient by Nick O’Leary and install it.

Note that this tutorial was tested with PubSubClient 2.6.

Download and open gps_tracker.ino sketch.

Note You need to edit following constants and variables in the sketch:

  • WIFI_AP - name of your access point
  • WIFI_PASSWORD - access point password
  • WIFI_AUTH - choose one of LWIFI_OPEN, LWIFI_WPA, or LWIFI_WEP.
  • TOKEN - the $ACCESS_TOKEN from Thingsboard configuration step.
  • thingsboardServer - Thingsboard HOST/IP address that is accessable within your wifi network. Specify “demo.thingsboard.io” if you are using live demo server.
resources/gps_tracker.ino
#include <PubSubClient.h>

#include <LWiFi.h>
#include <LWiFiClient.h>
#include <LGPS.h>
#include <LBattery.h>

#define WIFI_AP "YOUR_WIFI_AP"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"
#define WIFI_AUTH LWIFI_WPA  // choose from LWIFI_OPEN, LWIFI_WPA, or LWIFI_WEP.

#define TOKEN "YOUR_ACCESS_TOKEN"

gpsSentenceInfoStruct gpsInfo;

char thingsboardServer[] = "YOUR_THINGSBOARD_HOST_OR_IP";

LWiFiClient wifiClient;

PubSubClient client( wifiClient );

unsigned long lastSend;

void setup()
{
  Serial.begin(115200);
  LGPS.powerOn();
  Serial.println("GPS started.");
  InitLWiFi();
  client.setServer( thingsboardServer, 1883 );
  lastSend = 0;
}

void loop()
{
  LWifiStatus ws = LWiFi.status();
  boolean status = wifi_status(ws);
  if (!status) {
    Serial.println("Connecting to AP ...");
    while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)))
    {
      delay(500);
    }
    Serial.println("Connected to AP");
  }

  if ( !client.connected() ) {
    reconnect();
  }

  if ( millis() - lastSend > 1000 ) { // Update and send only after 1 seconds
    getAndSendGPSData();
    lastSend = millis();
  }

  client.loop();

}

void getAndSendGPSData()
{
  Serial.println("Collecting GPS data.");
  LGPS.getData(&gpsInfo);
  Serial.println((char*)gpsInfo.GPGGA);

  char latitude[20];
  char lat_direction[1];
  char longitude[20];
  char lon_direction[1];
  char buf[20];
  char time[30];

  const char* p = (char*)gpsInfo.GPGGA;

  p = nextToken(p, 0); // GGA
  p = nextToken(p, time); // Time
  p = nextToken(p, latitude); // Latitude
  p = nextToken(p, lat_direction); // N or S?
  p = nextToken(p, longitude); // Longitude
  p = nextToken(p, lon_direction); // E or W?
  p = nextToken(p, buf); // fix quality

  const int coord_size = 8;
  char lat_fixed[coord_size], lon_fixed[coord_size];
  convertCoords(latitude, longitude, lat_direction, lon_direction, lat_fixed, lon_fixed, coord_size);

  Serial.print("Latitude:");
  Serial.println(lat_fixed);

  Serial.print("Longitude:");
  Serial.println(lon_fixed);

  if (buf[0] == '1')
  {
    // GPS fix
    p = nextToken(p, buf); // number of satellites
    Serial.print("GPS is fixed:");
    Serial.print(atoi(buf));
    Serial.println(" satellite(s) found!");
  }
  else
  {
    Serial.println("GPS is not fixed yet.");
  }

  // Obtain battery level
  String batteryLevel = String(LBattery.level());
  String batteryCharging = LBattery.isCharging() == 1 ? "true" : "false";

  // Just debug messages
  Serial.print( "Sending gps location and battery level: [" );
  Serial.print( lat_fixed ); Serial.print( lon_fixed );
  Serial.print(" Battery level: "); Serial.print( batteryLevel );
  Serial.print(" Battery charging: "); Serial.print( batteryCharging );
  Serial.print( "]   -> " );

  // Prepare a JSON payload string
  String payload = "{";
  payload += "\"latitude\":"; payload += lat_fixed; payload += ", ";
  payload += "\"longitude\":"; payload += lon_fixed; payload += ", ";
  payload += "\"batteryLevel\":"; payload += batteryLevel;  payload += ", ";
  payload += "\"batteryCharging\":"; payload += batteryCharging;
  payload += "}";

  // Send payload
  char attributes[100];
  payload.toCharArray( attributes, 100 );
  client.publish( "v1/devices/me/attributes", attributes );
  Serial.println( attributes );
}

void InitLWiFi()
{
  LWiFi.begin();
  // Keep retrying until connected to AP
  Serial.println("Connecting to AP ...");
  while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD))) {
    delay(500);
  }
  Serial.println("Connected to AP");
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Connecting to Thingsboard node ...");
    // Attempt to connect (clientId, username, password)
    if ( client.connect("LinkIt One Device", TOKEN, NULL) ) {
      Serial.println( "[DONE]" );
    } else {
      Serial.print( "[FAILED] [ rc = " );
      Serial.print( client.state() );
      Serial.println( " : retrying in 5 seconds]" );
      // Wait 5 seconds before retrying
      delay( 5000 );
    }
  }
}

void convertCoords(const char* latitude, const char* longitude, const char* lat_direction,
                   const char* lon_direction, char* lat_return, char* lon_return, int buff_length)
{
  char lat_deg[3];

  // extract the first 2 chars to get the latitudinal degrees
  strncpy(lat_deg, latitude, 2);

  // null terminate
  lat_deg[2] = 0;

  char lon_deg[4];

  // extract first 3 chars to get the longitudinal degrees
  strncpy(lon_deg, longitude, 3);

  // null terminate
  lon_deg[3] = 0;

  // convert to integer from char array
  int lat_deg_int = arrayToInt(lat_deg);
  int lon_deg_int = arrayToInt(lon_deg);

  // must now take remainder/60
  // this is to convert from degrees-mins-secs to decimal degrees
  // so the coordinates are "google mappable"

  // convert the entire degrees-mins-secs coordinates into a float - this is for easier manipulation later
  float latitude_float = arrayToFloat(latitude);
  float longitude_float = arrayToFloat(longitude);

  // remove the degrees part of the coordinates - so we are left with only minutes-seconds part of the coordinates
  latitude_float = latitude_float - (lat_deg_int * 100);
  longitude_float = longitude_float - (lon_deg_int * 100);

  // convert minutes-seconds to decimal
  latitude_float /= 60;
  longitude_float /= 60;

  // add back on the degrees part, so it is decimal degrees
  latitude_float += lat_deg_int;
  longitude_float += lon_deg_int;

  if (strcmp (lat_direction, "S") == 0) {
    latitude_float *= -1;
  }

  if (strcmp (lon_direction, "W") == 0) {
    longitude_float *= -1;
  }

  // format the coordinates nicey - no more than 6 decimal places
  snprintf(lat_return, buff_length, "%2.6f", latitude_float);
  snprintf(lon_return, buff_length, "%3.6f", longitude_float);
}

int arrayToInt(const char* char_array)
{
  int temp;
  sscanf(char_array, "%d", &temp);
  return temp;
}

float arrayToFloat(const char* char_array)
{
  float temp;
  sscanf(char_array, "%f", &temp);
  return temp;
}

const char *nextToken(const char* src, char* buf)
{
  int i = 0;
  while (src[i] != 0 && src[i] != ',')
    i++;
  if (buf)
  {
    strncpy(buf, src, i);
    buf[i] = 0;
  }
  if (src[i])
    i++;
  return src + i;
}

boolean wifi_status(LWifiStatus ws) {
  switch (ws) {
    case LWIFI_STATUS_DISABLED:
      return false;
      break;
    case LWIFI_STATUS_DISCONNECTED:
      return false;
      break;
    case LWIFI_STATUS_CONNECTED:
      return true;
      break;
  }
  return false;
}

Connect your LinkIt One device via USB cable and select Serial Debug COM port in Arduino IDE. Compile and Upload your sketch to device using “Upload” button.

After application will be uploaded and started it will try to connect to Thingsboard node using mqtt client and upload “latitude” and “longitude” attributes once per second.

Troubleshooting

When application is running you can connect your device to Serial Debug COM port in Arduino IDE and open “Serial Monitor” in order to view debug information produced by serial output.

Data visualization

Finally, open Thingsboard Web UI. You can access this dashboard by logging in as a tenant administrator. Use

in case of local Thingsboard installation.

Go to “Devices” section and locate “LinkIt One Demo Device”, open device details and switch to “Attributes” tab. If all is configured correctly you should be able to see “latitude”, “longitude” and battery status attributes and theirs latest values in the table.

image

After, open “Dashboards” section then locate and open “LinkIt One GPS Tracking Demo Dashboard”. As a result you will see the map widget with pointer indicating your device location and battery level widget (similar to dashboard image in the introduction).

Next steps

Browse other samples or explore guides related to main Thingsboard features:

Your feedback

If you found this article interesting, please leave your feedback in the comments section, post questions or feature requests on the forum and “star” our project on the github in order to stay tuned for new releases and tutorials.

73 comments :

  1. I need to test this software, it is possible to replace this vehicle track system uboro. I started use this for a long time, since I had to control my son. Now I do not have such a need, but it would be in case of force majeure find him.

    ReplyDelete
  2. Reduce Fuel and Maintenance Costs – The average operating cost per vehicle is about $1.50 per mile. A company can reduce at least 25 miles per week for each vehicle with a RMT Rover GPS Tracking System. ELD Mandate

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. I think it's not right! we all have to respect privacy of each other. I like Trump but in this situation I can't agree with this man! Hope, he will decide not to do it. By the way, my good friend told me she wanted to know waht her child do when she is away. And she decided to install this Hoverwatch phone tracker. Good luck!

    ReplyDelete
  5. is it possible to add multipel tracking devices on "MAP" and monitoring them??

    ReplyDelete
  6. Nice post. Thank you for you great article

    ReplyDelete
  7. Hi there, I read your blogs on a regular basis. Your humoristic style is witty, keep it up! Thank You for Providing Such a Unique and valuable information, If you
    are looking for the best Gps Tracker For Kids, then visit Vimel Technology Pty Ltd.I enjoyed this blog post.

    ReplyDelete
  8. Real-time tracking is the main reason for buying a GPS Tracker. Real-time GPS tracking differs from one tracking device to another. Some tracking devices do not offer the ability to manually ping the tracker which allows you to know its exact location at any time and others only offer a location update at pre-defined intervals. Fleet Management Solutions

    ReplyDelete
  9. After Reading your article about features of GPS Tracker, I get some good knowledge about it. You very well defined about the GPS system which is quite unique. Thanks for sharing such good information. Car GPS Ireland.

    ReplyDelete
  10. The blog was having very informative content and very useful for me. Well done post and keep it up... Thanks for sharing such a Useful info. tableau automation

    ReplyDelete
  11. How do I start to learn how to Hip Hop dance? GPS tracker

    ReplyDelete
  12. Many radio broadcasts are overhauling their transmission innovation, with some contribution HD2 multicast channels.ADN GPS

    ReplyDelete
  13. You wrote this post very carefully. The amount of information is stunning and also a gainful article for us. Keep sharing this kind of articles, Thank you. spy software

    ReplyDelete
  14. Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family. www.meridiannorstar.net

    ReplyDelete
  15. I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. tracking devices

    ReplyDelete
  16. It is truly a well-researched content and excellent wording. I got so engaged in this material that I couldn’t wait to read. Read more info about car trackers ireland. I am impressed with your work and skill. Thanks.

    ReplyDelete
  17. Clearly, It is an engaging article for us which you have provided here about vessel fleet tracking system. This is a great resource to enhance knowledge about it. Thank you.

    ReplyDelete
  18. I like the way you have explained things and I also want to showcase my website Web hosting “Write for us” that provides you information about guest posting.

    ReplyDelete
  19. I think this is one of the most significant pieces of information for me about Specialty Pharmacies Medication Tracking . And I'm glad to read your article. Thank you for sharing!

    ReplyDelete
  20. Nice info, I am very thankful to you for sharing this important knowledge. This information is helpful for everyone. Read more info about truck gps tracker. So please always share this kind of information. Thanks.

    ReplyDelete
  21. يتسائل الجميع لماذا يطلق علي دكتور محمود ناصر افضل دكتور اوعية دموية في مصر لانه الدكتور الوحيد في مصر الذي يقوم بعلاج دوالي الساقين بدون جراحة باستعمال احدث تقنية في العصر الحالي تقنية الكلاكس

    ReplyDelete
  22. thanks for all of this. A very good content you shared here. I liked your work and the way in which you have shared this blog here. you can use OBD Port, the Automotive Electronic Diagnostic equipment use to check the Errors of a Car. And Get the complete automotive solution for your vehicle.

    ReplyDelete
  23. I appreciate the efforts which you have put into this post. This post provides a good idea. Genuinely, it is a useful post to increase our knowledge. Thanks for sharing such content here. Visit also Gps Tracking Hardware Australia

    ReplyDelete

  24. I liked your work and the way you have shared this blog here. Very nice stuff you shared here. You can use obd device, an automotive electronic diagnostic tool which is used to check for car

    ReplyDelete
  25. Winter clothing presents a range of challenges. We appreciate you teaching us about winter clothing trends.Faux Leather Jackets Thank You for sharing

    ReplyDelete
  26. TikTok is a social media app that allows people to share short videos with each other. It's a place for people to watch and upload short video clips of themselves, which are usually 15 seconds long. If you want to save your favourite TikTok videos, then this is the Snaptik app that helps you download TikTok videos on your Android device.

    ReplyDelete
  27. Data Mining Assignment Help
    Professionally Written Data Mining Assignment Help
    Data Mining assignments are about understanding the data, preparing the data for analysis and then comes data modelling, evaluation and deployment. Completing data mining coursework is time-consuming and demands focus and accuracy at every stage to ensure excellent grades. Many students don’t have the knowledge or time to complete the assignments and they come to us for data mining assignment help. After receiving multiple queries of data mining coursework help from our repeat customers, we finally started the service in 2014.

    Today, we are the leaders in providing data mining homework help to students in the USA, UK, Australia, Canada, UAE, and various other European countries. Students who aspire to get an A grade in their statistics coursework, seek our expert’s guidance in the form of Data Mining Assignment Help and online tutoring. for more visit us at - https://archliteassignments.co.uk/data-mining-assignment-help/

    ReplyDelete
  28. Infinity Advertisement is the best digital marketing company In Delhi , India offers SEO, PPC, Social media, Web design/development services. Contact a top digital marketing agency in Delhi, India to improve your ROI.

    ReplyDelete
  29. It’s really a nice and useful piece of information. I am glad that you shared this useful information with us. Please keeps us to date like this .thank you for sharing
    abogados de quiebras
    semi truck accident attorneys

    ReplyDelete
  30. Thank you for sharing such an interesting article; it is definitely worth reading. I've subscribed to you and will now check your profile daily for interesting content.
    leather motorcycle jackets for men

    ReplyDelete
  31. Wow, this article on GPS data upload and visualization using LinkIt ONE and Thingsboard was incredibly helpful! I've been looking for a comprehensive guide on how to work with GPS data, and this tutorial provided clear instructions and explanations. Thanks for sharing Aviator Brown Bomber Jacket!

    ReplyDelete
  32. Admiration for the blog's beauty and the tutorial's excellence. Kill Em Hoodie

    ReplyDelete
  33. The tutorial's educational value is highly appreciated. Kill Em Hoodie

    ReplyDelete
  34. Captivating blog design matched with a valuable tutorial. Kill Em Hoodie

    ReplyDelete
  35. The blog's aesthetics enhance the impact of the tutorial. Stussy 8 Ball Sherpa

    ReplyDelete
  36. Expressing gratitude for the shared, insightful tutorial. Stussy 8 Ball Sherpa

    ReplyDelete
  37. Commendable tutorial shared through a beautiful blog. Stussy 8 Ball Sherpa

    ReplyDelete
  38. Sincere thanks for the enriching tutorial content. Stussy 8 Ball Sherpa

    ReplyDelete
  39. The blog's beauty amplifies the value of the tutorial. Stussy 8 Ball Sherpa

    ReplyDelete
  40. Appreciation for the valuable insights in the tutorial. Stussy 8 Ball Sherpa

    ReplyDelete
  41. Impressed by the tutorial's quality and the blog's aesthetics. Stussy 8 Ball Sherpa

    ReplyDelete
  42. Thankful for the well-structured and informative tutorial. Stussy 8 Ball Sherpa

    ReplyDelete
  43. The tutorial's excellence is greatly acknowledged. Stussy 8 Ball Sherpa

    ReplyDelete
  44. The blog's visual appeal adds to the tutorial's worth. Stussy 8 Ball Sherpa

    ReplyDelete
  45. Expressing gratitude for the valuable information shared. Stussy 8 Ball Sherpa

    ReplyDelete
  46. Impressed by the tutorial's depth and the blog's design. Stussy 8 Ball Sherpa

    ReplyDelete
  47. The tutorial's impact is enhanced by the blog's elegance. Stussy 8 Ball Sherpa

    ReplyDelete
  48. Commendable tutorial, a great addition to the blog. Stussy 8 Ball Sherpa

    ReplyDelete
  49. Thanking for the informative content presented. Stussy 8 Ball Sherpa

    ReplyDelete
  50. The blog's aesthetic charm complements the tutorial. Stussy 8 Ball Sherpa

    ReplyDelete
  51. Valuable insights shared through an appealing blog. Stussy 8 Ball Sherpa

    ReplyDelete
  52. Appreciation for the enlightening tutorial provided. Stussy 8 Ball Sherpa

    ReplyDelete
  53. Impressed by the tutorial's quality and the blog's beauty. Stussy 8 Ball Sherpa

    ReplyDelete
  54. The tutorial significantly adds to the blog's value. Stussy 8 Ball Sherpa

    ReplyDelete
  55. Expressing gratitude for the valuable tutorial's sharing. Stussy 8 Ball Sherpa

    ReplyDelete
  56. The blog's aesthetics amplify the tutorial's worth. Stussy 8 Ball Sherpa

    ReplyDelete
  57. Commendable tutorial shared through an elegant blog. Stussy 8 Ball Sherpa

    ReplyDelete
  58. Thankful for the insightful content and beautiful design. Stussy 8 Ball Sherpa

    ReplyDelete
  59. Impressed by the tutorial's educational impact. Stussy 8 Ball Sherpa

    ReplyDelete
  60. The blog's aesthetics enhance the tutorial's quality. Stussy 8 Ball Sherpa

    ReplyDelete
  61. Valuable insights shared through the well-crafted blog. Stussy 8 Ball Sherpa

    ReplyDelete
  62. Appreciating the tutorial's excellence and the blog's beauty. Stussy 8 Ball Sherpa

    ReplyDelete
  63. The blog's design perfectly complements the tutorial. Stussy 8 Ball Sherpa

    ReplyDelete
  64. You wrote this post very carefully.車 gps 発信 機 The amount of information is stunning and also a gainful article for us. Keep sharing this kind of articles, Thank you.

    ReplyDelete
  65. The article on GPS data upload and visualization using LinkIt ONE and Thingsboard is informative, well-explained, and accessible. It highlights practical applications, practical applications, and the integration of GPS technology with IoT, making it a valuable resource. chesapeake personal injury lawyer

    ReplyDelete
  66. Seasoned multi state family law attorneys providing adept guidance and tailored solutions for intricate legal matters. Trust our experienced team for comprehensive and empathetic representation.

    ReplyDelete
  67. Enhance your social media game effortlessly! Purchase Twitter likes to increase visibility and credibility. Instant delivery and genuine results guaranteed.

    ReplyDelete
  68. The project demonstrates the potential of using IoT technologies like LinkIt ONE and ThingsBoard for real-time tracking and monitoring applications. It integrates GPS data upload and visualization, making it accessible to beginners in IoT development. The combination of LinkIt ONE's GPS module and ThingsBoard's dashboard capabilities allows users to track location data and visualize it in a user-friendly interface. However, more in-depth troubleshooting tips could be beneficial. Overall, this project showcases the potential of IoT technologies for efficient GPS data management and visualization in various applications.
    Domestic violence New Jersey

    ReplyDelete