Skip to content
ImagineWorld

Geolocalization Applications Using GPS, NoSQL, and K3s Clusters

node_idnode-book_edge-computing-systems-with-kubernetes_chapter-13-geolocalization-applications-using-gps-nosql-and-k3s-cluster
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num13
chapter_titleGeolocalization Applications Using GPS, NoSQL, and K3s Clusters
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 13 — Geolocalization Applications Using GPS, NoSQL, and K3s Clusters

Section titled “Chapter 13 — Geolocalization Applications Using GPS, NoSQL, and K3s Clusters”

One of the growing use cases for edge computing is the implementation of a system for tracking cargos and logistics. Sometimes, this tracking involves monitoring and getting metrics that can be used to optimize packages’ delivery times, reduce gas consumption, and so on. One of the important technologies that you can use for this is the Global Positioning System (GPS). GPS can help you to obtain the coordinates of an object when it is moving in real time. This, together with Kubernetes at the edge, results in a powerful combination of technologies to create geolocalization systems, also called geo-tracking systems.

In this chapter, we’re going to cover the following main topics:

  • Understanding how GPS is used in a geo-tracking system
  • Using Redis to store GPS coordinates data
  • Using MongoDB to store your devices’ tracking data
  • Creating services to monitor your devices in real time using GPS
  • Configuring your Raspberry Pi to track your device using GPS
  • Visualizing your devices using Leaflet library in real time
  • Deploying a real-time map and report application to track your devices

To deploy our databases in this chapter, you need the following:

  • A single node K3s cluster using an ARM device. In this case, we are going to use the Raspberry Pi 4B model with 8 GB. We are going to use the Raspberry Pi OS lite (64-bit) operating system with no desktop environment.
  • Multiple VK-162 G-Mouse USB GPS dongle navigation modules for your edge Raspberry devices.
  • A battery bank and a USB 2.0 A-Male to USB C cable. You can also power your Raspberry Pi with your car’s USB charger port.
  • A Kubernetes cluster hosted in your public cloud provider (AWS, Azure, or GCP) or your private cloud.
  • Basic knowledge of programming, especially Python and JavaScript.
  • Clone the repository at https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/tree/main/ch13 if you want to run the YAML configuration by using kubectl apply instead of copying the code from the book. Take a look at the python directory inside the code directory and the yaml directory for YAML configurations inside the ch13 directory.

With this, you can start to implement your geolocation system using edge computing. Let’s start to understand how GPS works in our first section.

Understanding how GPS is used in a geo-tracking system

Section titled “Understanding how GPS is used in a geo-tracking system”

For this chapter, our goal will be to build a geolocation system, also called a geo-tracking system. This means that we are going to build a system that gets GPS coordinates or positions from vehicles. In our use case, we are assuming that our vehicles will be used to deliver packages. Our vehicles will be equipped with a Raspberry Pi device and a GPS module. This hardware will collect GPS coordinates, using latitude and longitude to send them to the cloud. Then, our application will show the live positions of all the vehicles and a report to show the route of vehicles within a date range. In general, these are the main features that our geo-tracking system will have:

  • A real-time map showing the position of all delivery vehicles
  • A map showing the nearby delivery stops of each vehicle
  • A report that shows delivery routes for a vehicle between a date range

This geo-tracking system is represented using the following diagram:

Figure 13.1 – A geolocation application edge diagram

Now, let’s explain how this geo-tracking system is implemented by describing the edge computing layers:

  • Cloud layer: Here, we are going to install a Kubernetes cluster in our preferred cloud provider. Inside this cluster, we are going to install three main applications. The GPS server will receive requests from the vehicles. It will also save the collected positions in Redis for the real-time map and the logs in MongoDB for the report that shows delivery routes. Finally, we will have the frontend application that contains the web application to show the real-time map and the report.
  • Near edge: This layer represents all the information that will move from the far edge to the near edge using the LTE network. This means that all the GPS information will be sent across the internet to its final destination, the cloud layer.
  • Far edge: Here, we are going to find the vehicles equipped with a Raspberry Pi; this device will use a GPS module and an internet connection to send the GPS coordinates. Our Raspberry Pi will have K3s installed. Inside this K3s single-node cluster, we are going to find the GPS reader. This application is going to read GPS information and send it to the cloud. However, you can also include additional applications to add more functionalities – for example, showing an OLED screen with GPS information or other processed data, such as velocity, using the GPS coordinates to calculate it. Hence, this part represents the local process at the edge.

To connect the Raspberry Pi to the internet, you can use a 5G or 4G LTE module or your smartphone, which already includes this kind of module. To simplify the example, we are going to use the access point from a smartphone to share the internet with the Raspberry Pi device.

  • Tiny edge: Here, we are going to find the GPS module that our edge device will use to get GPS coordinates. Our GPS module is going to use the Global Navigation Satellite System (GNSS), which is a global system of satellites that gives you GPS coordinates. This will be the main data used in our implementation. You can also use an LTE 5G/4G module with GPS integrated to speed up GPS module initialization to capture GPS coordinates, but this could be expensive compared with the VK-162 G-Mouse USB module. In this case, we are going to use the VK-162 module to simplify the implementation and reduce costs for this prototype implementation.

In summary, our vehicle on the far edge is going to read information from the GPS module on the tiny edge. After reading the information and doing some processing, the information will be sent to the cloud layer using the near edge. Once all the information is received, it will be stored in Redis and Mongo to show the real-time map and the report using the frontend application.

As we explained in Chapter 10, SQL and NoSQL Databases at the Edge, Redis is a key-value database that is pretty lightweight when using resources. Redis exclusively uses RAM memory to store its data but can persist when using snapshot configuration, which basically stores this data on the disk. Redis can also store geolocation data, storing GPS coordinates and tuples with latitude and longitude values. Redis stores this information with the field’s latitude, longitude, and a name. Redis also calls this data a geospacial index. Redis also includes the ability to return coordinates close to a circular area with this type of data. In this use case, Redis will be used to calculate all this information. For this specific use case, we are going to use the GEOADD and GEOSEARCH commands to implement our geolocalization application. But first, let’s install Redis in the cloud to store some geolocation data. For this, follow these steps:

  1. First, let’s create a PersistentVolumeClaim for Redis to persist data:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
    name: db-pv-claim-1
    spec:
    accessModes:
    - ReadWriteOnce
    resources:
    requests:
    storage: 5Gi
    EOF
  2. Now, create a ConfigMap to configure Redis to use an authentication password:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: redis-configmap
    data:
    redis-config: |
    dir /data
    requirepass YOUR_PASSWORD
    EOF
  3. Create the deployment for Redis using the previous ConfigMap called redis-configmap and mounted as the redis.conf file. We also use the PersistentVolumeClaim called db-pv-claim-1, and some resource limits for the deployment setting the CPU and memory. Let’s create the deployment by running the following command:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    creationTimestamp: null
    labels:
    app: redis
    name: redis
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: redis
    strategy: {}
    template:
    metadata:
    creationTimestamp: null
    labels:
    app: redis
    spec:
    containers:
    - name: redis
    image: redis:6.2
    command:
    - redis-server
    - /redisconf/redis.conf
    ports:
    - containerPort: 6379
    resources:
    limits:
    cpu: "0.2"
    memory: "128Mi"
    volumeMounts:
    - mountPath: "/data"
    name: redis-storage
    - mountPath: /redisconf
    name: config
    volumes:
    - name: config
    configMap:
    name: redis-configmap
    items:
    - key: redis-config
    path: redis.conf
    - name: redis-storage
    persistentVolumeClaim:
    claimName: db-pv-claim-1
    status: {}
    EOF

This time, we are not going to use an image for ARM 64 bits.

  1. Now, create the service for Redis by opening port 6379:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    app: redis
    name: redis
    spec:
    ports:
    - port: 6379
    protocol: TCP
    targetPort: 6379
    selector:
    app: redis
    type: ClusterIP
    EOF

Now, we have Redis installed. Let’s move to install Mongo to store log information with this data.

Using MongoDB to store your device’s tracking data

Section titled “Using MongoDB to store your device’s tracking data”

MongoDB is a document-oriented NoSQL database that stores the information using JSON format. It also has the capability to store location data. In this use case, we are going to use MongoDB to store our geolocation data; this means storing all coordinates (latitude and longitude) that the GPS captures on the devices for later reports. MongoDB can perform some special manipulation for geolocation data, but in this case, we will use it just to store data in JSON format. To install MongoDB in the cloud, follow the next steps:

  1. Create a PersistentVolumeClaim for MongoDB, to persist data:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
    name: db-pv-claim-2
    spec:
    accessModes:
    - ReadWriteOnce
    #storageClassName: your_driver
    resources:
    requests:
    storage: 5Gi
    EOF

Important Note

You can change the storage class if you install Longhorn or another storage driver, or if you are using the storage class provided by your cloud provider. Just uncomment the storageClassName line by removing the # character.

  1. Deploy your custom configuration to enable clients to connect to MongoDB:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: mongo-configmap
    data:
    mongod-conf: |
    dbpath=/var/lib/mongodb
    logpath=/var/log/mongodb/mongodb.log
    logappend=true
    bind_ip = 0.0.0.0
    port = 27017
    journal=true
    auth = true
    EOF

This exposes MongoDB to listening in port 27017 across the network.

  1. Create the deployment using the ConfigMap called mongo-configmap, our PersistentVolumeClaim, and the MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD, and MONGO_INITDB_DATABASE variables that set the initial root username, an additional user to connect and their passwords to be used when connecting to MongoDB:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    labels:
    app: mongo
    name: mongo
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: mongo
    template:
    metadata:
    labels:
    app: mongo
    spec:
    containers:
    - name: mongo
    image: mongo:4.4
    env:
    - name: MONGO_INITDB_ROOT_USERNAME
    value: "admin"
    - name: MONGO_INITDB_ROOT_PASSWORD
    value: "YOUR_PASSWORD"
    - name: MONGO_INITDB_DATABASE
    value: "mydatabase"
    ports:
    - containerPort: 27017
    resources:
    limits:
    cpu: "0.2"
    memory: "200Mi"
    volumeMounts:
    - mountPath: "/data/db"
    name: mongo-storage
    - mountPath: /mongoconf
    name: config
    volumes:
    - name: config
    configMap:
    name: mongo-configmap
    items:
    - key: mongod-conf
    path: mongod.conf
    - name: mongo-storage
    persistentVolumeClaim:
    claimName: db-pv-claim-2
    EOF

Important Note

We are using some values directly to configure the deployment to simplify the example. But it’s a best practice to use secrets to protect sensitive data. You can explore Chapter 10, SQL and NoSQL Databases at the Edge, for more examples. We are also using version 4.4 in case you want to install MongoDB on an ARM device.

  1. Now, create the service that exposes your MongoDB deployment as a service accessible inside the cluster (MongoDB uses port 27017 to connect):
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    app: mongo
    name: mongo
    spec:
    ports:
    - port: 27017
    protocol: TCP
    targetPort: 27017
    selector:
    app: mongo
    type: ClusterIP
    EOF

Now, your MongoDB database has been installed. So, let’s deploy our GPS server application that will store data in Redis and our MongoDB in the next section.

Creating services to monitor your devices in real time using GPS

Section titled “Creating services to monitor your devices in real time using GPS”

In our use case, we are going to deploy a service that sends data from our edge device after some processing in the cloud. The goal of this use case is to have a global geolocation system for multiple vehicles delivering packages, showing their location in real time. For this, we are going to create a gps-server deployment that stores all the coordinates for our units in Redis and Mongo. We are going to use the Python Flask library to create this service. Let’s explore the main sections of the following pseudocode mixed with Python:

<imported libraries>
<app_initialization>
<CORS configuration>
def redisCon():
<return Redis connection object>
@app.route("/client/<cid>/position", methods=["POST"])
def setPosition(cid):
<Call redisCon>
<Store of data in a Redis hash data type using
the fields cid,lat,lng
in the hash key named client:{cid}:position>
<set the expiration of the key>
<call the tracking-server in /client/{cid}/position
to store the position in Mongo>
return {"client_id":cid,"setPosition":"done"}
@app.route("/clients/positions/unit/<unit>/r/<radius>"
,methods=["GET"])
def getPositions(unit,radius):
<Call redisCon>
<Search for client:*:position keys>
<Search the near geospacial index for
the current position>
<Add the position to data Array>
<Returns the near positions for each unit in JSON>
return jsonify({"clients":data})
@app.route("/client/<cid>/stops", methods=["POST"])
def setStops(cid):
<Call redisCon>
<GET json values stops to set>
<Store the stops in the key client:{cid}:stops >
return jsonify({"setStops":"done"})
<App initialization in port 3000>

Let’s focus on the following functions:

  • redisCon: This function sets the Redis connection. This application is going to use the Redis service created in the Using Redis to store GPS coordinates data section.
  • setPosition: Each time our application receives the /client/<cid>/position URL, the function will get the <cid> value that represents a connected client that sends information to this service – in this case, our delivery vehicles. Every time the information is received, it is stored in the key with the form client:{cid}:position inside Redis, and stores the latitude as a lat variable, the longitude as lng, and the client ID or vehicle number as cid. It also sets an expiration time as 180 seconds or 3 minutes. After calling the tracking server to store this coordinate in MongoDB, it returns the following JSON response: {"client_id":cid,"setPosition":"done"}.
  • getPositions: Each time our application receives the /clients/positions/unit/<unit>/r/<radius> URL, the function connects to Redis and gets all the keys with the form client:<cid>:position, which contains the current GPS position of each vehicle. Then gets the near stops to this position, using the Redis command geosearch. The returned JSON will look like: {"clients":[{"cid":1,"lat":0.0,"lng":0.0,"near":["stop1"]}]}.
  • setStops: Each time our application receives the /client/<cid>/stops URL, the function will get <cid> and store all the positions as a geospatial index in the key with the client:{cid}:stops form. Inside this key, each position will be stored with the name sent as part of the JSON data using curl. These stops are stored for 10 hours by default because the stops have to be completed during a workday. These stops will be near to the vehicle with the cid number.

After understanding the code, let’s deploy our GPS server application in the next section.

Deploying gps-server to store GPS coordinates

Section titled “Deploying gps-server to store GPS coordinates”

The gps-server application will receive the GPS coordinates from your edge devices. For this, we have to deploy it and expose it using a load balancer. To deploy the gps-server application, follow the following steps:

  1. Create the deployment for the GPS server:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    creationTimestamp: null
    labels:
    app: gps-server
    name: gps-server
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: gps-server
    strategy: {}
    template:
    metadata:
    creationTimestamp: null
    labels:
    app: gps-server
    spec:
    containers:
    - image: sergioarmgpl/gps_server
    name: gps-server
    imagePullPolicy: Always
    env:
    - name: REDIS_HOST
    value: "redis"
    - name: REDIS_AUTH
    value: "YOUR_PASSWORD"
    - name: ENDPOINT
    value: "http://tracking-server:3000"
    resources: {}
    status: {}
    EOF

This deployment uses the following variables:

  • REDIS_HOST: This is the name of the Redis service; this variable can be customized to fit your needs.
  • REDIS_AUTH: This is the password to connect to the Redis service.
  • ENDPOINT: This is the URL of tracking-server – in this case, the URL matches the internal tracking-server service in port 3000.

Important Note

To check the code and create your own container, refer to this link: https://github.com/sergioarmgpl/containers/tree/main/gps-server/src.

  1. Create the service as a LoadBalancer; this IP address will be used in our GPS reader services for each unit or truck:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    labels:
    app: gps-server
    name: gps-server-lb
    spec:
    ports:
    - port: 3000
    protocol: TCP
    targetPort: 3000
    selector:
    app: gps-server
    type: LoadBalancer
    status:
    loadBalancer: {}
    EOF
  2. Get the load balancer IP for our gps-server deployment with the following command:
    $ GPS_SERVER_IP="$(kubectl get svc gps-server-lb -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')"

You can see the value of the GPS_SERVER_IP environment variable by running the following:

$ echo $GPS_SERVER_IP

Note that it takes some time after the IP address of the load balancer is provisioned. You can check the state of the services by running the following:

$ kubectl get svc gps-server-lb

Wait until EXTERNAL_IP is provisioned. Also, note the $GPS_SERVER_IP value, which will be used to configure the gps-reader application on each edge device.

Now, you can set the stops for the first vehicle, represented with value 1. For this, follow the next steps:

  1. Use curl to store the stops:
    $ curl -X POST -H "Accept: application/json" \
    -H "Content-Type: application/json" \
    --data '{
    "stops":[
    {"name":"stop1","lat":1.633518,"lng": -90.591706},
    {"name":"stop2","lat":2.631566,"lng": -91.591529},
    {"name":"stop3","lat":3.635043,"lng": -92.589982}
    ]
    }' http://$GPS_SERVER_IP:3000/client/1/stops
  2. This will return the following:
    {"setStops":"done"}

Now, we have the gps-server application deployed and exposed using a load balancer. Let’s deploy our tracking-server, the one that stores logs about the received GPS positions.

Creating a service to log GPS positions and enable real-time tracking for your devices

Section titled “Creating a service to log GPS positions and enable real-time tracking for your devices”

Our tracking-server application will be in charge of logging all the received coordinates for each vehicle. This information will be used to show the route of a vehicle in the desired time range using the frontend application. Before deploying tracking-server, let’s understand the code of this application:

<Imported libraries>
<Application initialization>
<CORS configuration>
def mongoCon():
<return Mongo connection with tracking collection set>
@app.route("/client/<cid>/position", methods=["POST"])
def storePosition(cid):
<Get the position JSON values to store it
in the tracking collection>
<Get current time and store it using UTC>
<Call MongoCon function>
<Store data in the format:
{"cid":XX,"lat":XX,"lng":XX,"ts":XXXXXXX,"dtxt":XXXXXX}
Inside the tracking collection in the database
called mydatabase>
<return JSON {"client_id":cid,"positionStored":"done"}>
@app.route("/client/<cid>/positions/s/<sdate>/e/<edate>"
,methods=["GET"])
def getPositions(cid,sdate,edate):
<Get the start date to query in the format
dd-mm-yy-HH:MM:SS and convert it into UTC>
<get the end date to query in the format
dd-mm-yy-HH:MM:SS and convert it into UTC>
<Call MongoCon function>
<Query the tracking collection to get the
tracking data for a unit
or truck between the time range>
<Return the positions in an array called data>
return jsonify({"tracking":data})
<App initialization in port 3000>

In this code we can find the following functions:

  • MongoCon: This function connects to MongoDB and returns a MongoDB object connection, with the collection set to the tracking value.
  • storePosition: Each time our application receives a POST request in the /client/<cid>/position URL, the function will store the received GPS position in the {"cid":1,"lat":0.0,"lng":0.0,"ts":166666666,"dtxt":"01-01-22-23:59:59"} format. cid represents the client ID or the number of the vehicle, lat and lng are used to store the GPS position, ts represents the timestamp generated when the coordinate was received, and dtxt is the date in text format to reduce transformation time from the timestamp format to the UNIX date format. Once this data is stored in the database, mydatabase returns the next JSON: {"client_id":cid,"positionStored":"done"}.
  • getPositions: Each time our application receives a GET request in the URL with the /client/<cid>/positions/s/<sdate>/e/<edate> form, it returns a JSON response with all the GPS positions between the starting date, sdate, and the ending date, edate. For this, tracking-server connects to Mongo and returns the result of performing this query in this time range. The information will be returned in the following format:
    {
    "tracking":[
    {"lat":0.0,"lng":0.0,"ts":166666666
    ,"dtxt":"01-01-22-23:59:59"}
    ]
    }

Now we know how the tracking-server application works. Let’s deploy this application in the next section.

Deploying tracking-server to store logs from GPS coordinates to be used for vehicles routing report

Section titled “Deploying tracking-server to store logs from GPS coordinates to be used for vehicles routing report”

Our tracking-server will be used in our frontend application to show the route of a vehicle within the desired time range. Let’s deploy our application with the following steps:

  1. Deploy tracking-server by running the following:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    creationTimestamp: null
    labels:
    app: tracking-server
    name: tracking-server
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: tracking-server
    strategy: {}
    template:
    metadata:
    creationTimestamp: null
    labels:
    app: tracking-server
    spec:
    containers:
    - image: sergioarmgpl/tracking_server
    name: tracking-server
    imagePullPolicy: Always
    env:
    - name: MONGO_URI
    value: "mongodb://admin:YOUR_PASSWORD@mongo/mydatabase?authSource=admin"
    - name: MONGO_DB
    value: "mydatabase"
    - name: TIMEZONE
    value: "America/Guatemala"
    resources: {}
    status: {}
    EOF

This deployment uses the following environment variables:

  • MONGO_URI: This is the full URI that contains a string to be used to authenticate in MongoDB. It has the mongodb://USER:PASWORD@HOST/DATABASE?authSource=admin format. You can customize these credentials and store MONGO_URI as a secret.
  • MONGO_DB: This is the database created in MongoDB to store the tracking collection.
  • TIMEZONE: This is the time zone used to get the time when the GPS coordinate is stored in the tracking collection of MongoDB. Note that our Python code uses the pytz library and the ISO 3166 convention for country names. Check the Further reading section for more information to set your country’s time zone correctly. In this case, we set the country to America/Guatemala.

Important Note

You can find out more about the URI on the following page: https://www.mongodb.com/docs/manual/reference/connection-string. Remember that we are using hardcoded values to simplify the example, but it’s best practice to use secrets. Check out Chapter 10, SQL and NoSQL Databases at the Edge, for more details. To check out the code and create your own version of tracking-server, refer to the following link: https://github.com/sergioarmgpl/containers/tree/main/tracking-server/src.

  1. Create a service as a ClusterIP for tracking-server to call it inside gps-server:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    labels:
    app: tracking-server
    name: tracking-server
    spec:
    ports:
    - port: 3000
    protocol: TCP
    targetPort: 3000
    selector:
    app: tracking-server
    type: ClusterIP
    status:
    loadBalancer: {}
    EOF
  2. Create a service as a LoadBalancer for tracking-server to call it in our viewer application, which is accessible over the internet:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    labels:
    app: tracking-server
    name: tracking-server-lb
    spec:
    ports:
    - port: 3000
    protocol: TCP
    targetPort: 3000
    selector:
    app: tracking-server
    type: LoadBalancer
    status:
    loadBalancer: {}
    EOF
  3. Get the load balancer IP of our tracking-server deployment with the following command:
    $ TRACKING_SERVER_IP="$(kubectl get svc tracking-server-lb -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')"

You can see the value of the TRACKING_SERVER_IP environment variable by running the following:

$ echo $TRACKING_SERVER_IP

The tracking-server application has been deployed. Now, let’s configure our device to run our reader application.

Configuring your Raspberry Pi to track your device 
using GPS

Section titled “Configuring your Raspberry Pi to track your device 
using GPS”

Before using the GPS module on your Raspberry Pi, you have to follow the following steps:

  1. Install the Raspberry Pi OS Lite (64-bit) on your device; you can check out Chapter 2, K3s Installation and Configuration, for more details.
  2. Log in to your device and set an initial user name and password.
  3. Run raspi-config with the following command:
    $ sudo raspi-config

You will see a screen like the following:

Figure 13.2 – The raspi-config main menu

  1. To configure the wireless network, go to the System Options | Wireless LAN menu.
  2. You will see a Choose the country where your Raspberry will be used message, and then click Ok.
  3. After that, the Wireless LAN country message will appear. Select your country and then click Ok.
  4. The Please Enter SSID message will appear. Click Ok and press Enter.
  5. Now, the Please Enter passphrase message will appear. Click Ok and press Enter.
  6. Upon returning to the main menu, select Finish and press Enter to exit.
  7. Activate the SSH, choosing the Interface Options | SSH menu. This will show the Would you like the SSH server to be enabled? message. Choose Yes and press Enter. After that, the The SSH server is enabled message will appear.
  8. To check the IP of your Raspberry Pi, run the following command:
    $ ifconfig -a

The output will look like the following:

Figure 13.3 – The ifconfig output

Take note of the IP address next to the word inet word in the wlan0 network interface; this will be the IP address of your Raspberry Pi.

  1. Log in to your device using the previous IP address found using SSH:
    $ ssh YOUR_USER@RASPBERRY_IP
  2. Add the next kernel parameters to enable the use of container by adding these values in the /boot/cmdline.txt file; remember that you need root permissions to modify this file:
    cgroup_memory=1 cgroup_enable=memory
  3. Connect your VK-162 G-Mouse GPS module to one of the USB ports of your Raspberry; after some seconds, the /dev/ttyACM0 device will be ready to be used.
  4. Restart your device to apply these changes:
    $ sudo shutdown -r now
  5. (Optional) If you want to configure other features, log in to your device and run the following:
    $ sudo raspi-config
  6. (Optional) Activate the Inter-Integrated Circuit (I2C) support in your device – for example, to connect an OLED screen, go to the Interface Options | I2C menu after running raspi-config.
  7. (Optional) Then, a dialog will show Would you like the ARM I2C interface to be enabled?. Select Yes and press Enter.
  8. (Optional) After the previous dialog, the The ARM I2C interface is enabled message will appear. Press Enter to choose the Ok button.
  9. (Optional) Upon returning to the main menu, select Finish and press Enter to exit.
  10. To finish, let’s install K3s by running the following:
    $ curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="--write-kubeconfig-mode 644" sh -s -
  11. Run the following command to see whether your K3s single-node cluster is running:
    $ kubectl get nodes

This will show something like the following:

Figure 13.4 – The kubectl get nodes output

Important Note

You can find out more about how to use raspi-config at the following link: https://geek-university.com/raspi-config.

Now, you have your Raspberry Pi installed with Raspberry Pi OS Lite, which is ready to be used together with your GPS module. In the next section, let’s move to deploy the GPS reader application.

Understanding the GPS reader code to send GPS coordinates

Section titled “Understanding the GPS reader code to send GPS coordinates”

Now, the only remaining part is to install gps-reader in the K3s single-node cluster installed on your Raspberry. This application will run as a container using the Kubernetes Pods. However, before installing our gps-reader application, let’s understand the code first:

<Imported libraries>
while True:
<Set serial Device /dev/ttyACM0 with baud rate 9600>
ser=serial.Serial(device, baudrate=9600, timeout=0.5)
<Set the PynMEA2 reader>
<Read data from the device>
<Read for GRPMC lines>
<Extract latitude, longitude>
<Call /client/{cid}/position from GPS Server
To store the position in Redis>
<If cannot read data show
"No GPS data to send">

The previous code contains an infinite loop that reads the output of the /dev/ttyACM0 device every half second. Our VK-162 G-Mouse GPS module uses the National Marine Electronics Association (NMEA) specification to represent GPS coordinates. The previous code scans the output to look for the GRPMC field to get the latitude and longitude coordinates using the PynMEA2 library. Once the library extracts the coordinates, it calls the GPS server endpoint to store the current GPS position of the vehicle in Redis and log it in MongoDB.

Be aware that the GPS module delays a little bit after the module starts receiving a GPS coordinate. It could take some minutes before the GPS module starts to receive GPS coordinates.

To see what your device is doing, run the cat /dev/ttyACM0 command. If the module is not receiving coordinates yet, it will show something like the following:

$GPRMC,052326.00,V,,,,,,,,,,N*7D
$GPVTG,,,,,,,,,N*30
$GPGGA,052326.00,,,,,0,00,99.99,,,,,,*66
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPTXT,01,01,01,NMEA unknown msg*58
$GPTXT,01,01,01,NMEA unknown msg*58
$GPGSV,1,1,02,01,,,30,22,,,36*7C
$GPGLL,,,,,052326.00,V,N*4A

Important Note

The GPRMC or GPGLL fields are empty in some parts when the module is not receiving coordinates. These missing values contain the latitude and longitude obtained by the GPS module.

When the device starts to receive data, you will see something like the following:

$GPRMC,054003.00,A,1437.91511,N,09035.52679,W,0.077,,020622,,,D*6D
$GPVTG,,T,,M,0.077,N,0.142,K,D*21
$GPGGA,054003.00,1437.91511,N,09035.52679,W,2,06,2.54,1668.7,M,-4.9,M,,0000*68
$GPGSA,A,3,22,01,48,31,32,21,,,,,,,3.95,2.54,3.02*02
$GPTXT,01,01,01,NMEA unknown msg*58
$GPGSV,4,1,13,01,18,301,33,10,49,124,11,16,20,189,12,21,29,276,24*74
$GPGSV,4,2,13,22,39,008,32,23,18,135,,25,19,052,11,26,47,169,09*79
$GPGSV,4,3,13,27,02,204,18,31,64,342,30,32,35,037,29,46,43,252,*7A
$GPGSV,4,4,13,48,47,250,30*40
$GPGLL,1437.91511,N,09035.52679,W,054003.00,A,D*70

The GPGLL line contains all the information about latitude and longitude that we are looking for.

Important Note

Depending on your device configuration, the GPRMC line can include the elevation data. In the previous output, the elevation information is not configured, so the line will not include this information, but the device can be configured to get the elevation information too.

Now, we know how our application reads information from the GPS module. Let’s deploy our application in our device with K3s installed.

Deploying gps-reader to send GPS coordinates to the cloud

Section titled “Deploying gps-reader to send GPS coordinates to the cloud”

One advantage of using K3s is that if your application is complex, you can deploy your application separated as modules or microservices, and you can update these pieces without affecting the others. In this case, we are only using one piece called gps-reader. This application reads the GPS module from the device using a Pod. In this case, we are using a configuration that enables us to read the /dev folder from the device with just the necessary permissions to access the /dev/ttyACM0 device, where the GPS module shows the GPS coordinates. This device can change, depending on the GPS module that you are using.

To create a reader on your device, run the following steps:

  1. Create the gps-reader Pod to start reading GPS coordinates from your module:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Pod
    metadata:
    name: gps-reader
    spec:
    containers:
    - image: sergioarmgpl/gps_reader
    name: gpsreader
    imagePullPolicy: Always
    env:
    - name: DEVICE
    value: "/dev/ttyACM0"
    - name: CLIENT_ID
    value: "1"
    - name: ENDPOINT
    value: "http://<GPS_SERVER_IP>:3000"
    securityContext:
    privileged: true
    capabilities:
    add: ["SYS_ADMIN"]
    volumeMounts:
    - mountPath: /dev
    name: dev-volume
    volumes:
    - name: dev-volume
    hostPath:
    path: /dev
    type: Directory
    EOF

This Pod will use the following environment variables:

  • DEVICE: This contains the virtual device where the GPS module is listening. This could be different, depending on the GPS module that you are using. Check the Further reading section for more information.
  • CLIENT_ID: This is the vehicle number that this reader will represent in the system – in this case, 1, the first vehicle.
  • ENDPOINT: This is the endpoint of the GPS server. You have to use the value obtained in the GPS_SERVER_IP variable in the Deploying gps-server to store GPS coordinates section.

Important Note

To check the code and create your own container of gps-reader, refer to the following link: https://github.com/sergioarmgpl/containers/tree/main/gps-reader/src. If you want to use an OLED screen to show information, refer to the following link: https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/blob/main/ch13/code/python/oled.py. The code uses the OLED included in the Raspberry Pi 4B keyestudio Complete RFID Starter kit.

  1. You can check whether your device is reading information by running the following:
    $ kubectl logs pod/gps-reader -f

If you’re not sure whether you have access to your device, the way to test is by looking at the frontend and checking whether the device appears on the map.

The output will look like the following:

<Response [200]>
{'lat': 11.6318615, 'lng': -80.59205166666666, 'cid': '1'}
  1. Press Ctrl + C to cancel.
  2. Write exit and press Enter to exit from your Raspberry.

Now, we have all the backend services running and receiving data, but we need to visualize this information. Let’s move to the next section to deploy the frontend application.

Visualizing your devices using Open Street Maps in 
real time

Section titled “Visualizing your devices using Open Street Maps in 
real time”

Our application has two parts, one that visualizes the GPS coordinates of the vehicles and their near stops in real time and one that shows the past routes of the vehicle within a time range. So, let’s understand first the code of the geo-tracking map showing the devices in real time.

Understanding the geo-tracking map visualizer code

Section titled “Understanding the geo-tracking map visualizer code”

Let’s start with a map showing all the vehicles with their coordinates and near stops. We are using HTML, JavaScript, jQuery and the Leaflet library to create the map. Let’s look at the code of the map:

<!DOCTYPE html>
<html lang="en">
<head>
<Load Javascript libraries>
<Load page styles>
<body>
<div id='map'></div>
<script>
<Load Map in an initial GPS position>
var marker
var markers = []
var osm = L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
<Set Open Street Map Initial
Configuration using Leaflet>
});
osm.addTo(map);
setInterval(() => {
$.getJSON("URL",
function(pos) {
<Delete current markers>
<Get current positions for each unit or truck>
<For each position set a marker
in the map calling
the function markPosition>
});
}, 5000);
function markPosition(cid,lat,lng,near)
{
<Create a maker in the map with
Latitude, Longitude, Unit number and near destinies>
}
</script>
</body>
</html>

Our page loads some JavaScript libraries and CSS styles. After that, it loads an initial GPS position to show the map. This map is loaded in the <div id='map'></div> code.

The important functions in this code are the following:

  • setInterval: This function uses jQuery to call the endpoint of gps-server to get all the GPS coordinates. To do this, the setInterval function calls the http://GPS_SERVER_IP:3000/clients/positions/unit/km/r/0.1 URL, which returns the current GPS coordinates of each vehicle and their nearby stops in a radius of 0.1 kilometers. To do this, call the markPosition function every 5 seconds and send the client ID or vehicle number (cid), latency (lat), longitude (lng), and the near variable with the name of the stops. This function creates a mark object in the map.
  • markPosition: This function creates a Leaflet mark object with a PopUp window in the map. This function also resets the map when it’s called.

This application basically loads all the necessary libraries and calls the setInterval function to refresh the map every 5 seconds by calling the markPosition function. It is important to set an initial GPS position to center the map; this is customizable in the YAML file used to deploy the frontend application. Once the map is initialized, it will show all the tracked objects after 5 seconds:

Figure 13.5 – A map showing two tracked devices using GPS

If the connected devices are not sending data to the map, it will show an empty map; in this case, Figure 13.5 shows two devices connected and sending data. Now, let’s say, for example, that we are using the device or vehicle number 2 – in this case, represented as the second CID (client ID). If you click on the blue mark, it will show the current Latitude and Longitude coordinates and the near destinations or stops of the tracked vehicle. In this case, we set two stops, galeno_encinal and la_torre_encinal, which are 0.1 km from the current position of the tracked vehicle. If you click on the blue mark, you will see something like this:

Figure 13.6 – Near destinations showed when clicking the blue mark

This information is calculated every 5 seconds, updating the nearest position of your tracked vehicle in real time. You can customize the code to fit your needs; this is just a quick-start example to build a geo-tracking system using GPS. Let’s look at how our vehicles routes report works to show the collected data from the tracked vehicles.

This application creates a blue line, showing the tracking log stored in MongoDB. This represents the route of the vehicle within a date or time range. Before we take an in-depth look into how it works, let’s explore first the code of this page:

<!DOCTYPE html>
<html lang="en">
<head>
<Load Javascript libraries>
<Load page styles>
<body>
<form>
<input id="cid" name="cid"></input>
<input id="sdate" name="sdate"></input>
<input id="edate" name="edate"></input>
<button onclick="loadMap()"></button>
</form>
<div id='map'></div>
<script>
<Load Map in an initial GPS position>
var tiles = L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
<Set Open Street Map Initial
Configuration using Leaflet>
}).addTo(map);
function onEachFeature(feature, layer) {
<Set a popup with the line visualizing the route
of the vehicle>
}
var trip;
function loadMap(){
$.getJSON(<DYNAMIC_URL>, function(pos) {
var coordinates = [];
<Creating an array with the coordinates
between the time range>
this.trip = {
<The array with the coordinates and fields
to visualize in the map>
};
var tripLayer = L.geoJSON(this.trip, {
<Get the trip data and visualize it
into the map>
}).addTo(map);
});
}
</script>
</body>
</html>

Let’s analyze the next code sections:

  • trip: This variable contains all the coordinates to draw a line in the map with the routes covered by the vehicle within a time range.
  • form: This is an HTML form used to generate the dynamic called to get all the GPS positions between a selected time range.
  • DINAMIC_URL: This is a dynamic URL used to call tracking-server and get all the GPS positions. This URL has the following structure: http://TRACKING_SERVER_IP:3000/client/2/positions/s/25-05-22-04:39:58/e/25-05-22-04:40:00.
  • onEachFeature: This is a function that creates a line with the GPS positions of the vehicle.
  • LoadMap: This is a function that is called after clicking on the load button of the form to show the routes covered within a time range for a vehicle.

In general, this report page is generated when the Show Route History button is clicked, showing the route of the vehicle on the map as follows:

Figure 13.7 – Vehicles Routes Report

Our tracking-server service is configured to store and query the log tracking information of the vehicles within a time range using the timestamp captured when data arrives. This application is also configured to use localization times and UTC in different countries. This is a basic implementation of the vehicles routes report that you can customize.

Important Note

To know more about what is UTC time, you can check the next link: https://www.timeanddate.com/time/aboututc.html.

Another feature that this map has is that when you click on the map, it can show some information. In this case, we are showing a sample message, but you can customize it to show additional information, such as the time when the vehicle was in a particular position:

Figure 13.8 – Route information of the vehicle when clicking on the map

To reset the report, you have to reload the page. With this, we are ready to deploy our frontend application, which contains the real time map and this report, so finally, we can access the final application. To do this, let’s move on to the next section.

Deploying a real-time map and report application to track your devices

Section titled “Deploying a real-time map and report application to track your devices”

Now we have all the things ready, so we have to deploy the front application that contains our real time map and the report page. To do this, we use a simple Flask application with Python using templates; here is the code:

<imported libraries>
<app_initialization>
<CORS configuration>
@app.route("/")
def map():
return render_template(<Render map.html
Using environment variables)
@app.route("/report")
def report():
return render_template(<Render report.html
using environment variables>)
<Starting the application on port 3000>

This application renders the map.html page, which loads the Leaflet library to show the maps using the initial latitude and longitude variables. It also sets the endpoint of the gps-server that is called inside this static page. To deploy this application, follow these steps:

  1. Create the deployment by running the following:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    creationTimestamp: null
    labels:
    app: frontend
    name: frontend
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: frontend
    strategy: {}
    template:
    metadata:
    creationTimestamp: null
    labels:
    app: frontend
    spec:
    containers:
    - image: sergioarmgpl/frontend
    name: tracking-server
    imagePullPolicy: Always
    env:
    - name: LATITUDE
    value: "<YOUR_LATITUDE_COORDINATE>"
    - name: LONGITUDE
    value: "<YOUR_LONGITUDE_COORDINATE>"
    - name: GPS_SERVER
    value: "<YOUR_GPS_SERVER_IP>"
    - name: TRACKING_SERVER
    value: "<YOUR_TRACKING_SERVER_IP>"
    resources: {}
    status: {}
    EOF

This deployment has the following environment variables:

  • LATITUDE: The initial GPS latitude coordinate to center your map
  • LONGITUDE: The initial GPS longitude coordinate to center your map
  • GPS_SERVER: The IP address endpoint of the gps-server application.
  • TRACKING_SERVER: The IP address endpoint of your tracking-server application.

With these variables, you configure the initial loaded GPS coordinate to center the map and the endpoints to be called by the pages, to show the real-time map of the report routes of the frontend application.

Important Note

To check out the code and create your own container of frontend, refer to the following link: https://github.com/sergioarmgpl/containers/tree/main/frontend/src. To get some initial GPS coordinates to center the map when loading, refer to this website: https://www.gps-coordinates.net.

  1. Create a load balancer service for your application:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    labels:
    app: frontend
    name: frontend-lb
    spec:
    ports:
    - port: 3000
    protocol: TCP
    targetPort: 3000
    selector:
    app: frontend
    type: LoadBalancer
    status:
    loadBalancer: {}
    EOF
  2. Get the load balancer IP of our frontend deployment with the following command:
    $ FRONTEND_IP="$(kubectl get svc frontend-lb -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')"

You can see the value of the FRONTEND_IP environment variable by running the following:

$ echo $FRONTEND_IP

Important Note

We used a LoadBalancer service type to simplify the implementation, but a cheaper solution would be to use ingress definitions to expose the applications. You can explore the following link for more information: https://kubernetes.io/docs/concepts/services-networking/ingress.

  1. Now, access your application as http://<FRONTEND_IP>:3000 in your browser. The important endpoints of the URL are the following:
    • Geo-tracking map: http://<FRONTEND_IP>:3000
      • Vehicles routes report: http://<FRONTEND_IP>:3000/report
  2. Now, turn on your Raspberry Pi device in your vehicle and wait until your device starts sending GPS coordinates. Don’t forget to set your stops for each device. After some seconds or a couple of minutes, your map will start to show your devices in real time.
  3. Record some data by driving your equipped vehicle with your Raspberry Pi device and then test your reports.

Now, our simple geolocation system is ready and running. After finishing this chapter, it is important to mention that this is just a basic example that you can extend to fit your needs. Now, it’s time to recap what we learned.

In this chapter, we learned how to take advantage of MongoDB and Redis to store and query GPS coordinates to build a basic geolocalization system. We also learned how to integrate a GPS module to an edge device and send information to the cloud to finally visualize how a vehicle is moving in real time on a map, showing the near stops in a circle area, and simulating in that way a basic tracking delivery system. This shows how to implement a simple use case using geolocalization and how edge devices moving in real time interact in a geolocalization system. In the next chapter, we are going to learn how to use machine learning and computer vision to create a small smart traffic project.

Here are a few questions to validate your new knowledge:

  • How can I use GPS technologies to create a geolocalization system?
  • How can I use Redis to store GPS coordinates and do queries with this data?
  • How can I use MongoDB to store logs for a geolocalization system?
  • How can I design a real-time application that shows the GPS positions of moving vehicles?
  • How can I use edge computing and K3s to create a distributed system to track vehicles?

You can refer to the following references for more information on the topics covered in this chapter: