AWS Architecture Blog

Field Notes: Fleet Tracking Using Amazon Location Service with AWS IoT

Location-based intelligence is vital in today’s applications, enabling capabilities ranging from fleet tracking to hyperlocal marketing. However, developers face significant barriers when integrating location data into their applications. These include cost, privacy and security compromises, and tedious and slow integration work.

With Amazon Location Service, you can add capabilities such as maps, points of interest, geocoding, routing, geofences, and tracking to applications. You retain control of your location data with Amazon Location Service, so you can combine proprietary data with data from the service. With Amazon Location you can bring sophisticated location-enabled applications to production quickly, without the high cost of custom development.

In this post, I walk through the process of using Amazon Location tracking and AWS IoT to initiate an Amazon EventBridge event. This sends a notification based on an asset entering a geofence. For example, this can be used to notify a receiving department to prepare for a shipment arriving and reduce processing time.

The following diagram shows the high-level architecture of an example scenario. The client sends GPS location information to AWS IoT Core which triggers an AWS Lambda function. This sends the coordinates to Amazon Location Service. When the location coordinates show that the asset has entered a predefined geofence, Amazon EventBridge triggers a notification using Amazon Simple Notification Service (Amazon SNS).

Architecture overview

Amazon Location Service Ref Architecture

 

This walkthrough shows you how to:

  1. Create a location tracker and geofence collection.
  2. Create an IoT certificate.
  3. Create and secure IoT thing and policy.
  4. Create IoT rule and Lambda function.
  5. Create EventBridge rule and notification.
  6. Validate by running script to send location coordinates to IoT.

Steps 2-4 create and configure the AWS resources using the AWS Serverless Application Model (AWS SAM). To set up the sample application, visit the GitHub repo and follow the instructions in the README.md file.

Prerequisites

This walkthrough requires:

Create location tracker and geofence collection

A tracker is an AWS resource that receives location updates from devices. The tracker resource provides support for location queries, such as current and historic device location. When a tracker resource is linked to a geofence collection, all the location updates sent to it will be automatically evaluated against all geofences in the linked collection.

Create a location tracker using the following command:

aws location create-tracker \
  --tracker-name "myfleettracker" \
  --description "Track my incoming fleet" \
  --pricing-plan "MobileAssetTracking"

Create a geofence collection:

aws location create-geofence-collection \
 --collection-name "myfleetgeocollection" \
 --pricing-plan "MobileAssetTracking"

A geofencing application evaluates a tracked device’s position relative to previously registered areas of interest. This enables actions to be taken based on position updates. For example, you can trigger an event that prompts a notification when a customer who ordered coffee on their mobile app is near a store. Geofences contain points and vertices that form a closed boundary, which defines an area of interest. Geofence collections store and manage one or multiple geofences.

Amazon Location geofence collections stores geofences defined by using a standard geospatial data format called GeoJSON (RFC 7946). You can use tools, such as geojson.io, at no charge to draw your geofences graphically and save the output GeoJSON file.

Complete the following steps to create a geofence:

1. Navigate to geojson.io and zoom in to the point of interest around which the geofence will be created.

geofence picture

2. Choose Draw a polygon from the right-hand panel.

3. Click on the points around the reference point which will form the vertices of the polygon

The JSON with the coordinates of the vertices of the polygon will be displayed on the right-hand panel. Use these coordinates to create the geofence in the geofence collection created previously (replace the polygon location coordinates with your location coordinates):

aws location put-geofence \
  --collection-name "myfleetgeocollection" \
  --geofence-id "mywarehouse" \
  --geometry \
"{ \
 \"Polygon\":[ \
       [ \
         [-78.68702173233032,35.80437950161731], \
         [-78.68918895721436,35.80328313138334], \
         [-78.6893606185913,35.80168205560281], \
         [-78.68803024291991,35.80002873696329], \
         [-78.68579864501953,35.79999392988527], \
         [-78.68358850479126,35.8014732172523], \
         [-78.68354558944702,35.80305689437216], \
         [-78.68494033813477,35.804309891258725], \
         [-78.68702173233032,35.80437950161731] \
       ] \
     ] \
} "

coordinates image

Create AWS IoT certificate

Run the following command, which will create the certificate file, the private, and public key to the folder:

aws iot create-keys-and-certificate ^
    --set-as-active ^
    --certificate-pem-outfile "myfleetiot.cert.pem" ^
    --public-key-outfile "myfleetiot.public.key" ^
    --private-key-outfile "myfleetiot.private.key"

It will output the Amazon Resource Name (ARN) of the certificate created which will be used in step 3 while running the SAM template.

This command, however, does not download the Amazon Root CA certificate file. You can download the Amazon Root CA certificate file from CA certificates for server authentication.

Create AWS IoT Thing, Lambda, and Amazon EventBridge (steps 3 to 5)

Next, use the AWS SAM template to create the event bus, Lambda function, and event rule.

  1. Clone the GitHub repo.
  2. From the command line, run:
8cd ./amazon-eventbridge-partnerevent-example
sam build

Once the build completes, run the following to deploy the stack:

sam deploy --guided

Choose a stack name, enter the following parameters:

  • LocationGeofenceCollection – ARN of the Location geofence collection created earlier.
  • LocationTracker – ARN of the Location tracker created earlier.
  • IoTCertificate – ARN of the AWS IoT certificate created earlier.
  • NotificationEmail – Email ID to send Amazon EventBridge notification to.

These are the steps that are performed by the AWS SAM template:

Create AWS IoT thing

  MyFleetIoT:
    Type: AWS::IoT::Thing
    Properties:
      ThingName: myfleetiot

Create AWS IoT policy

MyIoTPolicy:
    Type: AWS::IoT::Policy
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Action:
          - iot:Connect
          - iot:Receive
          - iot:Publish
          - iot:Subscribe
          Resource: '*'
      PolicyName: myfleetiotpolicy

Attach AWS IoT policy to Certificate

  MyPolicyCertAttachment:
    Type: AWS::IoT::PolicyPrincipalAttachment
    Properties:
      PolicyName: !Ref MyIoTPolicy
      Principal: !Ref IoTCertificate

Attach AWS IoT certificate to AWS IoT thing

MyThingCertAttachment:
    Type: AWS::IoT::ThingPrincipalAttachment
    Properties:
      Principal: !Ref IoTCertificate
      ThingName: !Ref MyFleetIoT

Create SNS Topic

  MyFleetLocationTopic:
    Type: AWS::SNS::Topic
    Properties:
      FifoTopic: false
      Subscription:
        - Endpoint: !Ref NotificationEmail
          Protocol: "Email"
      TopicName: "myfleetlocationtopic"            

Create Amazon EventBridge event rule

MyFleetEventRule:
    Type: 'AWS::Events::Rule'
    Properties:
      Description: Test Events Rule
      EventPattern: 
        source: 
          - "aws.geo"
        account: [!Ref AWS::AccountId]
        resources: [
          !Ref LocationGeofenceCollection,
          !Ref LocationTracker
          ]
        detail-type: 
          - "Location Geofence Event"
        detail: 
          EventType: 
            - "ENTER"
            - "EXIT"
          GeofenceId: 
            - "mywarehouse"
      Name: myfleeteventrule
      State: ENABLED
      Targets:
        - 
         Arn: !Ref MyFleetLocationTopic
         Id: "idmyeventrule"

Create Lambda function

MyFleetLocation:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: LambdaFunction/
      Handler: lambda_function.lambda_handler
      Runtime: python3.8
      FunctionName: myfleetlocation
      Policies:
       - Statement:
         - Sid: WriteDevicePosition
           Effect: Allow
           Action:
           - geo:BatchUpdateDevicePosition
           Resource: 'arn:aws:geo:*:*:tracker/*'

Create AWS IoT topic rule

MyTopicRule:
    Type: AWS::IoT::TopicRule
    Properties:
      RuleName: topicrule
      TopicRulePayload:
        RuleDisabled: 'false'
        Sql: SELECT * FROM 'iot/fleet/location'
        Actions:
        - Lambda:
            FunctionArn: !GetAtt MyFleetLocation.Arn

Provide AWS IoT permission to invoke Lambda

PermissionForIoTToInvokeLambda: 
    Type: AWS::Lambda::Permission
    Properties: 
      FunctionName: 
        Ref: "MyFleetLocation"
      Action: "lambda:InvokeFunction"
      Principal: "iot.amazonaws.com"
      SourceArn: 
        Fn::GetAtt: 
          - "MyTopicRule"
          - "Arn"

Validate by sending location coordinates to IoT

The status of the CloudFormation stack can be checked by the following command (replace sam-app with your application name):

aws cloudformation describe-stacks --stack-name sam-app

  • When complete, the Stack Status in the output would show as CREATE_COMPLETE.
  • After successful completion, Amazon SNS will send you a subscription confirmation email to the email id specified when creating the stack.
  • Open the email and choose Confirm Subscription to confirm your subscription to SNS emails.

Open the LocationIoT.py file which you downloaded from the github repo. This python code when run, will publish location coordinates to the AWS IoT thing using MQTT client. The published coordinates will mimic an AWS IoT asset entering a geofence. You can plot your own trajectory and send the location coordinates by the following steps:

  1. Navigate to geojson.io.
  2. Open the previous geofence polygon created.
  3. Choose Draw a marker from the panel.
  4. Choose points on your trajectory path to mimic an asset entering the geofence.

geofence polygon image

  1. Replace the coordinates in the switcher statement in the getlocation function.

 

geo code

Open a command prompt and navigate to the folder which has the LocationIoT.py file. Run the following command:

./LocationIoT.py

The python function will send location coordinates to AWS IoT core, which will send them to Amazon Location service using a Lambda function. Once the published location falls within the geofence, Amazon EventBridge will raise an event to send a notification to the email id specified.

Cleaning Up

To avoid incurring future charges, delete all resources created. Replace the resource identifiers in the following commands with the ID/name of the resources you created.

  • Delete the SAM application stack created:

aws cloudformation delete-stack --stack-name 'sam-app'

  • Delete the location tracker:

aws location delete-tracker --tracker-name 'myfleettracker'

  • Delete the geofence collection:

aws location delete-geofence-collection --collection-name 'myfleetgeocollection'

Conclusion

This post demonstrates the process of using Amazon Location tracking and AWS IoT to initiate an Amazon EventBridge event to send notification based on an asset entering a geofence. This helps to optimize remote staffing, secure en-route shipment, maximize dispatch efficiency, and more. Location-based services help delivery applications store, track, and coordinate the source locations, delivery vehicles, and the destinations. For more ways to use Amazon Location service visit Amazon Location Service.

Field Notes provides hands-on technical guidance from AWS Solutions Architects, consultants, and technical account managers, based on their experiences in the field solving real-world business problems for customers.
TAGS:
Gopalakrishnan Ramaswamy

Gopalakrishnan Ramaswamy

Gopalakrishnan is a Solutions Architect at AWS with extensive background in database, analytics, and machine learning. He helps customers of all sizes solve complex challenges by providing solutions using AWS products and services.