├── .DS_Store
├── .eslintrc.js
├── .gitignore
├── .graphqlconfig.yml
├── .vscode
└── settings.json
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── babel.config.js
├── docs
└── deployment_guide.md
├── images
├── architecture.jpg
├── architecture.png
├── geotrack-agent.png
├── geotrack-delivery.png
├── geotrack-home.png
├── home.png
└── map.png
├── lambdas
├── eventbridge
│ └── index.py
├── iot
│ └── index.py
└── simulation
│ ├── launchDeliveryFleet
│ └── index.py
│ └── pushVehiclePosition
│ └── index.py
├── layers
└── requests
│ └── requirements.txt
├── package-lock.json
├── public
├── favicon.ico
└── index.html
├── schema.graphql
├── template.yaml
├── webapp
├── .gitignore
├── .vscode
│ └── extensions.json
├── index.html
├── package-lock.json
├── package.json
├── public
│ └── favicon.ico
├── src
│ ├── App.vue
│ ├── assets
│ │ ├── base.css
│ │ ├── logo.svg
│ │ └── main.css
│ ├── components
│ │ ├── Header.vue
│ │ └── Map.vue
│ ├── configAmplify.js
│ ├── graphql
│ │ ├── mutations.js
│ │ ├── queries.js
│ │ └── subscriptions.js
│ ├── layouts
│ │ └── SimpleLayout.vue
│ ├── main.js
│ ├── resolvers
│ │ ├── addDriverTrip.js
│ │ ├── delById.js
│ │ ├── getById.js
│ │ ├── hydrateTrips.js
│ │ ├── listDrivers.js
│ │ ├── listTrips.js
│ │ ├── removeDriverTrip.js
│ │ ├── saveById.js
│ │ ├── statusTrips.js
│ │ └── updateById.js
│ ├── router
│ │ └── index.js
│ ├── stores
│ │ ├── geo.js
│ │ └── user.js
│ └── views
│ │ ├── AboutView.vue
│ │ ├── AuthView.vue
│ │ ├── DriversView.vue
│ │ ├── HomeView.vue
│ │ └── TripsView.vue
└── vite.config.js
└── webappconfig.sh
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/amazon-location-service-geotrack-vuejs/400380be7c834b58de69c70600a7fdd83d0303f5/.DS_Store
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: {
4 | node: true
5 | },
6 | 'extends': [
7 | 'plugin:vue/essential',
8 | 'eslint:recommended'
9 | ],
10 | parserOptions: {
11 | parser: 'babel-eslint'
12 | },
13 | rules: {
14 | 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
15 | 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
16 | }
17 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | #amplify-do-not-edit-begin
2 | amplify/\#current-cloud-backend
3 | amplify/.config/local-*
4 | amplify/logs
5 | amplify/mock-data
6 | amplify/backend/amplify-meta.json
7 | amplify/backend/.temp
8 | build/
9 | dist/
10 | node_modules/
11 | aws-exports.js
12 | awsconfiguration.json
13 | amplifyconfiguration.json
14 | amplifyconfiguration.dart
15 | amplify-build-config.json
16 | amplify-gradle-config.json
17 | amplifytools.xcconfig
18 | .secret-*
19 | **.sample
20 | #amplify-do-not-edit-end
21 | amplify/team-provider-info.json
22 | .secret-*
23 | samconfig.toml
24 | queries.txt
25 | .env*
26 | .aws-sam
--------------------------------------------------------------------------------
/.graphqlconfig.yml:
--------------------------------------------------------------------------------
1 | projects:
2 | geotrack:
3 | schemaPath: src/graphql/schema.json
4 | includes:
5 | - src/graphql/**/*.js
6 | excludes:
7 | - ./amplify/**
8 | extensions:
9 | amplify:
10 | codeGenTarget: javascript
11 | generatedFileName: ''
12 | docsFilePath: src/graphql
13 | extensions:
14 | amplify:
15 | version: 3
16 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "files.exclude": {
3 | "amplify/.config": true,
4 | "amplify/**/*-parameters.json": true,
5 | "amplify/**/amplify.state": true,
6 | "amplify/**/transform.conf.json": true,
7 | "amplify/#current-cloud-backend": true,
8 | "amplify/backend/amplify-meta.json": true,
9 | "amplify/backend/awscloudformation": true
10 | }
11 | }
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | ## Code of Conduct
2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
4 | opensource-codeofconduct@amazon.com with any additional questions or comments.
5 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
4 | documentation, we greatly value feedback and contributions from our community.
5 |
6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
7 | information to effectively respond to your bug report or contribution.
8 |
9 |
10 | ## Reporting Bugs/Feature Requests
11 |
12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features.
13 |
14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already
15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
16 |
17 | * A reproducible test case or series of steps
18 | * The version of our code being used
19 | * Any modifications you've made relevant to the bug
20 | * Anything unusual about your environment or deployment
21 |
22 |
23 | ## Contributing via Pull Requests
24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
25 |
26 | 1. You are working against the latest source on the *main* branch.
27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted.
29 |
30 | To send us a pull request, please:
31 |
32 | 1. Fork the repository.
33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
34 | 3. Ensure local tests pass.
35 | 4. Commit to your fork using clear commit messages.
36 | 5. Send us a pull request, answering any default questions in the pull request interface.
37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
38 |
39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
41 |
42 |
43 | ## Finding contributions to work on
44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start.
45 |
46 |
47 | ## Code of Conduct
48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
50 | opensource-codeofconduct@amazon.com with any additional questions or comments.
51 |
52 |
53 | ## Security issue notifications
54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
55 |
56 |
57 | ## Licensing
58 |
59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
60 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of
4 | this software and associated documentation files (the "Software"), to deal in
5 | the Software without restriction, including without limitation the rights to
6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7 | the Software, and to permit persons to whom the Software is furnished to do so.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
15 |
16 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Amazon Location Service GeoTrack Vue.js
2 |
3 | Location data is a vital ingredient in today's applications, enabling capabilities ranging from asset tracking to location-based marketing.
4 |
5 | With [Amazon Location Service](https://aws.amazon.com/location/), you can easily 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, so you can combine proprietary data with data from the service. Amazon Location provides cost-effective location-based services (LBS) using high-quality data from global, trusted providers Esri and HERE Technologies.
6 |
7 | This repo contains a Vue.js prototype that controls a delivery system. For the prototype to work you need to first create the agents and associate unique IoT device Ids to them. Once you have the delivery agents in the system, you can go add the routes they need to go. The form leverages Amazon Location Maps to display de map, Places to fing the latitute and longitute associated to the address typed, Geogence to define a perimeter at the destination so the person can receive a text message when the driver is near by, and Routes to calculate the estimated time and distance.
8 |
9 | At the toolbar there is a fire icon button. Upon clicking this button, the application will simulate the existent delivery routes. An AWS Lambda reads the start and end positions of each delivery route, calculates the route and sends IoT messages with the IoT devices associated to the delivery agents reporting their geo-location over time. The application does not prevent having two routes with the same IoT device, which will produce inconsistent position.
10 |
11 | ## Architecture Overview
12 |
13 |
14 |
15 | ## Stack
16 |
17 | * **Front-end** - Vue.js as the core framework, [Vuetify](https://vuetifyjs.com/en/) for UI, [MapLibre](https://github.com/maplibre) for map visualiztion, [AWS Amplify](https://aws.amazon.com/amplify/) libraries for Auth UI component and AWS integration.
18 | * **Data** - User data is saved in [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) via GraphQL using [AWS AppSync](https://aws.amazon.com/appsync/). Devices GPS positions are stored in Amazon Location Service Tracker.
19 | * **Auth** - [Amazon Cognito](https://aws.amazon.com/cognito/) provides JSON Web Tokens (JWT) and along with AppSync fine-grained authorization on what data types users can access.
20 | * **IoT** - [AWS IoT](https://aws.amazon.com/iot/) with topics and rules.
21 | * **Serverless** - [AWS Lambda](https://aws.amazon.com/lambda/) for backend processes.
22 |
23 | ## User Interface
24 |
25 | #### Real-time tracking visualization
26 |
27 |
28 | #### Managing Delivery Agents
29 |
30 |
31 | #### Managing Delivery Routes
32 |
33 |
34 | # Deployment
35 | To deploy this solution into your AWS Account please follow our [Deployment Guide](./docs/deployment_guide.md)
36 |
37 | ## Security
38 |
39 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
40 |
41 | ## License
42 |
43 | This library is licensed under the MIT-0 License. See the LICENSE file.
44 |
45 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: [
3 | '@vue/cli-plugin-babel/preset'
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/docs/deployment_guide.md:
--------------------------------------------------------------------------------
1 | # Requirements
2 | Before you deploy, you must have the following in place:
3 | * [AWS Account](https://aws.amazon.com/account/)
4 | * [GitHub Account](https://github.com/)
5 | * [AWS CLI](https://aws.amazon.com/cli/)
6 | * [AWS SAM](https://aws.amazon.com/serverless/sam/)
7 | * Python 3.9, NodeJs v18 and npm
8 |
9 |
10 |
11 | # Step 1: Deploy the Solution
12 |
13 | In this step we deploy all resources this solution requires, including AWS AppSync Schema and its resolvers, via AWS SAM.
14 |
15 | The first step is to execute **sam build** so the solution can prepare all the Python libraries to be installed.
16 |
17 | ```bash
18 | sam build
19 | ```
20 |
21 | Next step is to deploy the solution
22 |
23 | ```bash
24 | sam deploy -g --capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND CAPABILITY_NAMED_IAM
25 | ```
26 |
27 | In the questions, provide the stack-name as geotrack-backend the region you are deploying the solution and accept all the default options. The output should be similar to:
28 |
29 | ```bash
30 | Setting default arguments for 'sam deploy'
31 | =========================================
32 | Stack Name [geotrack-v2]:
33 | AWS Region [us-west-2]:
34 | Parameter ProjectName [geotrack]:
35 | Parameter EnvironmentName [dev]:
36 | #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
37 | Confirm changes before deploy [Y/n]: y
38 | #SAM needs permission to be able to create roles to connect to the resources in your template
39 | Allow SAM CLI IAM role creation [Y/n]: y
40 | #Preserves the state of previously provisioned resources when an operation fails
41 | Disable rollback [y/N]: n
42 | Save arguments to configuration file [Y/n]: y
43 | SAM configuration file [samconfig.toml]:
44 | SAM configuration environment [default]:
45 | ```
46 |
47 | Confirm the deploy of the changeset and wait for the to finish.
48 |
49 | # Step 2: Deploy the WebApp
50 |
51 | ```bash
52 | ./webappconfig.sh
53 | ```
--------------------------------------------------------------------------------
/images/architecture.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/amazon-location-service-geotrack-vuejs/400380be7c834b58de69c70600a7fdd83d0303f5/images/architecture.jpg
--------------------------------------------------------------------------------
/images/architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/amazon-location-service-geotrack-vuejs/400380be7c834b58de69c70600a7fdd83d0303f5/images/architecture.png
--------------------------------------------------------------------------------
/images/geotrack-agent.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/amazon-location-service-geotrack-vuejs/400380be7c834b58de69c70600a7fdd83d0303f5/images/geotrack-agent.png
--------------------------------------------------------------------------------
/images/geotrack-delivery.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/amazon-location-service-geotrack-vuejs/400380be7c834b58de69c70600a7fdd83d0303f5/images/geotrack-delivery.png
--------------------------------------------------------------------------------
/images/geotrack-home.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/amazon-location-service-geotrack-vuejs/400380be7c834b58de69c70600a7fdd83d0303f5/images/geotrack-home.png
--------------------------------------------------------------------------------
/images/home.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/amazon-location-service-geotrack-vuejs/400380be7c834b58de69c70600a7fdd83d0303f5/images/home.png
--------------------------------------------------------------------------------
/images/map.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/amazon-location-service-geotrack-vuejs/400380be7c834b58de69c70600a7fdd83d0303f5/images/map.png
--------------------------------------------------------------------------------
/lambdas/eventbridge/index.py:
--------------------------------------------------------------------------------
1 | from urllib import request
2 | from datetime import datetime
3 | import os
4 | import json
5 | import boto3
6 | import logging
7 | import requests
8 | from requests_aws4auth import AWS4Auth
9 |
10 | logger = logging.getLogger()
11 | logger.setLevel(logging.INFO)
12 |
13 | pinpoint = boto3.client('pinpoint')
14 | appsync = boto3.client('appsync')
15 |
16 | appsync_url = os.getenv('APPSYNC_URL')
17 | project_name = os.getenv('PROJECT_NAME')
18 | project_env = os.getenv('PROJECT_ENV')
19 | pinpoint_application_id = os.getenv('APPLICATION_ID')
20 |
21 | boto3_session = boto3.Session()
22 | credentials = boto3_session.get_credentials()
23 | credentials = credentials.get_frozen_credentials()
24 |
25 | auth = AWS4Auth(
26 | credentials.access_key,
27 | credentials.secret_key,
28 | boto3_session.region_name,
29 | 'appsync',
30 | session_token=credentials.token,
31 | )
32 |
33 | def getGeoFenceRecord(geoFenceId):
34 | graphqlQuery="""
35 | query listDeliveryInfos {
36 | listDeliveryInfos(filter: { and: [
37 | { status: { ne: "completed" }},
38 | { geoFenceId: { eq: "%s" }} ]}
39 | ) {
40 | items {
41 | id
42 | geoFenceId
43 | userPhone
44 | status
45 | deliveryAgent {
46 | id
47 | fullName
48 | device
49 | {
50 | id
51 | }
52 | }
53 | }
54 | }
55 | }
56 | """%(geoFenceId)
57 |
58 | session = requests.Session()
59 | session.auth = auth
60 |
61 | response = session.request(
62 | url=appsync_url,
63 | method='POST',
64 | json={'query': graphqlQuery}
65 | )
66 |
67 | print(response.json())
68 |
69 | if 'data' in response.json() and len(response.json()['data']['listDeliveryInfos']['items']) == 1:
70 | return response.json()['data']['listDeliveryInfos']['items'][0]
71 | else:
72 | logger.error(response)
73 | return []
74 |
75 | def handler(event, context):
76 | # event - Data from EventBridge
77 | # print(event)
78 |
79 | row = getGeoFenceRecord(event['detail']['GeofenceId'])
80 | if 'deliveryAgent' in row:
81 | deviceId = row['deliveryAgent']['device']['id']
82 |
83 | if event['detail']['DeviceId'] == deviceId:
84 | response = pinpoint.send_messages(
85 | ApplicationId=pinpoint_application_id,
86 | MessageRequest={
87 | 'Addresses': {
88 | 'string': {
89 | 'ChannelType': 'SMS',
90 | 'RawContent': 'string'
91 | }
92 | },
93 | 'MessageConfiguration': {
94 | 'SMSMessage': {
95 | 'Body': 'The driver should be arriving soon',
96 | 'Keyword': 'GeoTrack',
97 | 'MessageType': 'TRANSACTIONAL'
98 | },
99 | },
100 | 'TraceId': 'string'
101 | }
102 | )
103 |
104 | print(response)
105 |
106 | return {
107 | 'statusCode': 200,
108 | 'body': json.dumps('Success')
109 | }
110 | else:
111 | return {
112 | 'statusCode': 500,
113 | 'body': json.dumps('Error')
114 | }
115 |
116 |
--------------------------------------------------------------------------------
/lambdas/iot/index.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 | import boto3
4 | import logging
5 |
6 | logger = logging.getLogger()
7 | logger.setLevel(logging.INFO)
8 |
9 | project_name = os.getenv('PROJECT_NAME')
10 | project_env = os.getenv('PROJECT_ENV')
11 | TRACKER = os.getenv('TRACKER')
12 | location = boto3.client('location')
13 |
14 | def handler(event, context):
15 |
16 | response = location.batch_update_device_position(
17 | TrackerName=TRACKER,
18 | Updates=[
19 | {
20 | 'DeviceId': event['device_id'],
21 | 'Position': [
22 | event['longitude'], event['latitude']
23 | ],
24 | 'SampleTime': event['timestamp']
25 | },
26 | ]
27 | )
28 |
29 | return {
30 | 'statusCode': 200,
31 | 'body': json.dumps(response)
32 | }
33 |
--------------------------------------------------------------------------------
/lambdas/simulation/launchDeliveryFleet/index.py:
--------------------------------------------------------------------------------
1 | from urllib import request
2 | from datetime import datetime
3 | import os
4 | import json
5 | import boto3
6 | import logging
7 | import requests
8 | from requests_aws4auth import AWS4Auth
9 |
10 | logger = logging.getLogger()
11 | logger.setLevel(logging.INFO)
12 |
13 | lambda_client = boto3.client('lambda')
14 | appsync = boto3.client('appsync')
15 |
16 | appsync_url = os.getenv('APPSYNC_URL')
17 | project_name = os.getenv('PROJECT_NAME')
18 | project_env = os.getenv('PROJECT_ENC')
19 | pushVehicleLambda = os.getenv('PUSH_VEHICLE_LAMBDA_NAME')
20 |
21 | boto3_session = boto3.Session()
22 | credentials = boto3_session.get_credentials()
23 | credentials = credentials.get_frozen_credentials()
24 | items = []
25 |
26 | auth = AWS4Auth(
27 | credentials.access_key,
28 | credentials.secret_key,
29 | boto3_session.region_name,
30 | 'appsync',
31 | session_token=credentials.token,
32 | )
33 |
34 | graphqlQuery=""""
35 | query DeviceIdByTripStatus (
36 | $status: TripStatus
37 | ) {
38 | statusTrips(status: $status) {
39 | nextToken
40 | trips {
41 | id
42 | geoStart {
43 | lat
44 | lng
45 | }
46 | geoEnd {
47 | lat
48 | lng
49 | }
50 | duration
51 | distance
52 | status
53 | driver {
54 | fullName
55 | deviceId
56 | }
57 | }
58 | }
59 | }
60 | """
61 |
62 | def setProxyResponse(data):
63 | response = {}
64 | response["isBase64Encoded"] = False
65 | if "statusCode" in data:
66 | response["statusCode"] = data["statusCode"]
67 | else:
68 | response["statusCode"] = 200
69 | if "headers" in data:
70 | response["headers"] = data["headers"]
71 | else:
72 | response["headers"] = {
73 | 'Content-Type': 'application/json',
74 | 'Access-Control-Allow-Origin': '*'
75 | }
76 | response["body"] = json.dumps(data["body"])
77 | return response
78 |
79 | def handler(event, context):
80 |
81 | proxy_response = {}
82 |
83 | session = requests.Session()
84 | session.auth = auth
85 |
86 | response = session.request(
87 | url=appsync_url,
88 | method='POST',
89 | json={'query': graphqlQuery}
90 | )
91 |
92 | print(response.json())
93 |
94 | if 'data' in response.json():
95 | items = response.json()['data']['statusTrips']['trips']
96 | for row in items:
97 |
98 | response = lambda_client.invoke(
99 | FunctionName=str(pushVehicleLambda),
100 | InvocationType='Event',
101 | Payload=json.dumps(row)
102 | )
103 |
104 | proxy_response['statusCode']=200
105 | proxy_response["body"] = { 'msg': 'Processed ' + str(len(items)) + ' vehicles' }
106 |
107 | return setProxyResponse(proxy_response)
--------------------------------------------------------------------------------
/lambdas/simulation/pushVehiclePosition/index.py:
--------------------------------------------------------------------------------
1 | import random
2 | import uuid
3 | import os
4 | import sys
5 | import base64
6 | import json
7 | import urllib
8 | import logging
9 | import boto3
10 | from boto3.dynamodb.conditions import Key, Attr
11 | from time import sleep
12 | from datetime import datetime
13 |
14 | logger = logging.getLogger()
15 | logger.setLevel(logging.INFO)
16 |
17 | iot_topic = os.getenv('IOT_TOPIC')
18 | project_name = os.getenv('PROJECT_NAME')
19 | project_env = os.getenv('PROJECT_ENV')
20 | ROUTE_NAME = os.getenv('ROUTE_NAME')
21 | TRACKER_NAME = os.getenv('TRACKER_NAME')
22 |
23 | location = boto3.client('location')
24 | iot = boto3.client('iot-data')
25 |
26 | def route_calculation(departure, destination):
27 | return location.calculate_route(
28 | CalculatorName=ROUTE_NAME,
29 | DeparturePosition=[departure['lng'], departure['lat']],
30 | DestinationPosition=[destination['lng'], destination['lat']],
31 | DepartNow=True,
32 | DistanceUnit='Kilometers',
33 | TravelMode='Car',
34 | )
35 |
36 | def publish_location(trip_id, device_id, position):
37 | logger.info("Publishing device: " + str(device_id) + " at lng:" + str(position[0]) + " lat:" + str(position[1]))
38 | message = json.dumps(
39 | {
40 | "TrackerName": TRACKER_NAME,
41 | "DeviceID" :device_id,
42 | "position": [
43 | float(position[1]),
44 | float(position[0])
45 | ],
46 | "timestamp": datetime.now().isoformat(),
47 | "tripId": trip_id
48 | })
49 |
50 | try:
51 | iot.publish(
52 | topic=iot_topic,
53 | qos=0,
54 | payload=message
55 | )
56 |
57 | except iot.exceptions.InternalFailureException as e:
58 | logger.error("Location InternalFailureException function error: " + str(e))
59 | except iot.exceptions.InvalidRequestException as e:
60 | logger.error("Location InvalidRequestException function error: " + str(e))
61 | except iot.exceptions.UnauthorizedException as e:
62 | logger.error("Location UnauthorizedException function error: " + str(e))
63 | except iot.exceptions.MethodNotAllowedException as e:
64 | logger.error("Location MethodNotAllowedException function error: " + str(e))
65 | except Exception as e:
66 | logger.error(str(e))
67 |
68 |
69 | def get_random(min, max):
70 | num = round(random.uniform(min, max), 2)
71 | if (num.is_integer()):
72 | return num + 0.01
73 | else:
74 | return num
75 |
76 | def handler(event, context):
77 | print(event)
78 | route = route_calculation(event['geoStart'],event['geoEnd'])
79 | if 'Legs' in route:
80 | for step in route['Legs'][0]['Steps']:
81 | publish_location(event['id'], event['driver']['deviceId'], step['StartPosition'])
82 | if step['DurationSeconds'] >= 200:
83 | div=10
84 | elif step['DurationSeconds'] < 200 and step['DurationSeconds'] >= 100:
85 | div=6
86 | else:
87 | div=4
88 |
89 | logger.info("Sleeping: " + str(round(step['DurationSeconds']/div)) + " sec")
90 | sleep(round(step['DurationSeconds']/div))
91 | publish_location(event['id'], event['driver']['deviceId'], step['EndPosition'])
92 |
93 |
94 | response = {
95 | 'statusCode': 200,
96 | 'body': 'successfully read items!'
97 | }
98 |
99 | return response
--------------------------------------------------------------------------------
/layers/requests/requirements.txt:
--------------------------------------------------------------------------------
1 | requests==2.32.2
2 | requests_aws4auth
3 |
--------------------------------------------------------------------------------
/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "amazon-location-service-geotrack-vuejs",
3 | "lockfileVersion": 3,
4 | "requires": true,
5 | "packages": {}
6 | }
7 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/amazon-location-service-geotrack-vuejs/400380be7c834b58de69c70600a7fdd83d0303f5/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |