SlideShare una empresa de Scribd logo
1 de 12
GPS TRACKING APP
Stipe Vicković
Mentor: Ivan Pašić
App concept
2
Sensor
Gateway
TCP request
Publish on MQTT channel Subscribe to
MQTT Channel
Save in database
Publish to
WebSocket
channel
Subscribe to
WebSocket
Update location
on message
MQTT
▰ Subscribing to MQTT channel
• broker address: eu.thethings.network
• broker port: 1883
• username: gps_tracker_lora
• password: <app_access_key>
• topic to subcribe to:
gps_tracker_lora/devices/<dev_id>/up
3
{"app_id":"gps_tracker_lora","dev_id":"rak811_tracker","hardware_serial":"00679391F46E8D8E","port":1,"counter":0,"payl
oad_raw":"AYgFN6kQnVsAwPgAFg==","payload_fields":{"gps":{"altitude":4.94,"latitude":34.1929,"longitude":108.8859,"sn":"0
001"}},"metadata":{"time":"2019-07-25T09:38:32.956669447Z"}}
Save in databse
4
def on_message(client, userdata, message):
"""Save recived payload in database and send it on websocket """
SQL = """INSERT INTO gps_tracking_app_log(gps_id, location, date_time)
VALUES (%s, ST_GeometryFromText('POINT(%s %s)', 4326), %s);"""
# Extracting from payload
gps_payload = json.loads(message.payload.decode())
gps_serial = gps_payload['hardware_serial']
gps_lat = gps_payload['payload_fields']['gps']['latitude']
gps_long = gps_payload['payload_fields']['gps']['longitude']
gps_time = gps_payload['metadata']['time’]
# Connecting to database and executing SQL
cur = connection.cursor()
cur.execute(SQL, (gps_device.id, gps_long, gps_lat, gps_time))
connection.commit()
cur.close()
5
Publish to WebSocket channel
6
# Send payload to websocket
channel_layer = get_channel_layer()
group_name = 'device_{}'.format(gps_serial)
data = {'type': 'location update', 'long': gps_long, 'lat': gps_lat}
async_to_sync(channel_layer.group_send)(
group_name,
{
'type': 'location_update',
'message': json.dumps(data)
}
)
var ws = new WebSocket("ws://127.0.0.1:8000/ws/gps/<sn>/");
ws.onmessage = function (event) {
…;
}
Create API endpoints
7
Background channel task
8
# Send payload to locatin-check channels
async_to_sync(channel_layer.send)('location-check', {'type': 'position_check’,
'gps_serial': gps_serial, 'long': gps_long, 'lat': gps_lat})
class PositionCheckConsumer(SyncConsumer):
def position_check(self, message):
"""
Check if there are zones in wich GPS device is not
located and send those location on websocket
"""
# Filter associated Geofence zones in which device is not located
exclude_zones = GeofenceZone.objects.filter(gps=gps_device).exclude(geom__contains=last_location)
# If there are zones without GPS signal, send their ID via websocket
if exclude_zones.exists():
# Send payload to websocket
channel_layer = get_channel_layer()
group_name = 'device_{}'.format(message['gps_serial'])
data = {'type': 'zone warning', 'long': message['long'],
'lat': message['lat'], 'zone': [zone.id for zone in exclude_zones]}
async_to_sync(channel_layer.group_send)(
group_name,
{
'type': 'location_update',
'message': json.dumps(data)
}
)
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter([
url(r'^ws/gps/(?P<serial_number>[-w]+)/$', GpsLogConsumer)
])
),
'channel': ChannelNameRouter({
'location-check': PositionCheckConsumer,
})
})
Leaflet map
9
Subscribe to WebSocket
10
var gps_sn = event.target.id;
var ws = new WebSocket(`ws://127.0.0.1:8000/ws/gps/${gps_sn}/`);
ws.open;
var locationMarkers = L.layerGroup().addTo(mymap);
if (event.target.classList.value == 'activated') {
ws.onmessage = function (event) {
locationMarkers.clearLayers();
var message = JSON.parse(event.data);
if (message.type == 'zone warning') {
L.marker(
[message.lat, message.long], {icon: outsideIcon}
).addTo(locationMarkers).bindPopup(`<b>Device ${gps_sn} is out of zone: ${message.zone}</b>`).openPopup();
} else {
L.marker(
[message.lat, message.long], {icon: insideIcon}
).addTo(locationMarkers).bindPopup(`<b>Device ${gps_sn}</b>`).openPopup();;
}
if (mymap.getZoom() < 13) {mymap.flyTo([message.lat, message.long], 13)
} else {mymap.flyTo([message.lat, message.long])}
}
11
12
Thank you!

Más contenido relacionado

Similar a Vickovic gps tracking_app

maXbox starter 34 GPS Tutorial
maXbox starter 34 GPS TutorialmaXbox starter 34 GPS Tutorial
maXbox starter 34 GPS TutorialMax Kleiner
 
Paolo Stagno - A Drone Tale: All Your Drones Belong To Us
Paolo Stagno - A Drone Tale: All Your Drones Belong To UsPaolo Stagno - A Drone Tale: All Your Drones Belong To Us
Paolo Stagno - A Drone Tale: All Your Drones Belong To Ushacktivity
 
Gmaps Railscamp2008
Gmaps Railscamp2008Gmaps Railscamp2008
Gmaps Railscamp2008xilinus
 
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)Jakub Botwicz
 
SensorWeb SOS Pilot RIVM/Geonovum - Status
SensorWeb SOS Pilot RIVM/Geonovum - StatusSensorWeb SOS Pilot RIVM/Geonovum - Status
SensorWeb SOS Pilot RIVM/Geonovum - StatusJust van den Broecke
 
Warp 10 Platform Presentation - Criteo Beer & Tech 2016-02-03
Warp 10 Platform Presentation - Criteo Beer & Tech 2016-02-03Warp 10 Platform Presentation - Criteo Beer & Tech 2016-02-03
Warp 10 Platform Presentation - Criteo Beer & Tech 2016-02-03Mathias Herberts
 
Fiware io t_ul20_cpbr8
Fiware io t_ul20_cpbr8Fiware io t_ul20_cpbr8
Fiware io t_ul20_cpbr8FIWARE
 
(120303) #fitalk ip finder and geo ip for fun
(120303) #fitalk   ip finder and geo ip for fun(120303) #fitalk   ip finder and geo ip for fun
(120303) #fitalk ip finder and geo ip for funINSIGHT FORENSIC
 
(120303) #fitalk ip finder and geo ip for fun
(120303) #fitalk   ip finder and geo ip for fun(120303) #fitalk   ip finder and geo ip for fun
(120303) #fitalk ip finder and geo ip for funINSIGHT FORENSIC
 
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】tsuchimon
 
Opentalk at Large - StS 2005
Opentalk at Large - StS 2005Opentalk at Large - StS 2005
Opentalk at Large - StS 2005Martin Kobetic
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixInfluxData
 
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware AnalysisBGA Cyber Security
 
Black Hat Europe 2015 - Time and Position Spoofing with Open Source Projects
Black Hat Europe 2015 - Time and Position Spoofing with Open Source ProjectsBlack Hat Europe 2015 - Time and Position Spoofing with Open Source Projects
Black Hat Europe 2015 - Time and Position Spoofing with Open Source ProjectsWang Kang
 
IPv4 Multicast Application Development
IPv4 Multicast Application DevelopmentIPv4 Multicast Application Development
IPv4 Multicast Application DevelopmentBob Quinn
 
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...Athens IoT Meetup
 

Similar a Vickovic gps tracking_app (20)

maXbox starter 34 GPS Tutorial
maXbox starter 34 GPS TutorialmaXbox starter 34 GPS Tutorial
maXbox starter 34 GPS Tutorial
 
Paolo Stagno - A Drone Tale: All Your Drones Belong To Us
Paolo Stagno - A Drone Tale: All Your Drones Belong To UsPaolo Stagno - A Drone Tale: All Your Drones Belong To Us
Paolo Stagno - A Drone Tale: All Your Drones Belong To Us
 
Gmaps Railscamp2008
Gmaps Railscamp2008Gmaps Railscamp2008
Gmaps Railscamp2008
 
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
 
SensorWeb SOS Pilot RIVM/Geonovum - Status
SensorWeb SOS Pilot RIVM/Geonovum - StatusSensorWeb SOS Pilot RIVM/Geonovum - Status
SensorWeb SOS Pilot RIVM/Geonovum - Status
 
MSI UI Software Design Report
MSI UI Software Design ReportMSI UI Software Design Report
MSI UI Software Design Report
 
Warp 10 Platform Presentation - Criteo Beer & Tech 2016-02-03
Warp 10 Platform Presentation - Criteo Beer & Tech 2016-02-03Warp 10 Platform Presentation - Criteo Beer & Tech 2016-02-03
Warp 10 Platform Presentation - Criteo Beer & Tech 2016-02-03
 
Fiware io t_ul20_cpbr8
Fiware io t_ul20_cpbr8Fiware io t_ul20_cpbr8
Fiware io t_ul20_cpbr8
 
(120303) #fitalk ip finder and geo ip for fun
(120303) #fitalk   ip finder and geo ip for fun(120303) #fitalk   ip finder and geo ip for fun
(120303) #fitalk ip finder and geo ip for fun
 
(120303) #fitalk ip finder and geo ip for fun
(120303) #fitalk   ip finder and geo ip for fun(120303) #fitalk   ip finder and geo ip for fun
(120303) #fitalk ip finder and geo ip for fun
 
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
 
Opentalk at Large - StS 2005
Opentalk at Large - StS 2005Opentalk at Large - StS 2005
Opentalk at Large - StS 2005
 
Kinect de-theremin
Kinect de-thereminKinect de-theremin
Kinect de-theremin
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul Dix
 
TripThru_API_Doc_v1
TripThru_API_Doc_v1TripThru_API_Doc_v1
TripThru_API_Doc_v1
 
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
 
Black Hat Europe 2015 - Time and Position Spoofing with Open Source Projects
Black Hat Europe 2015 - Time and Position Spoofing with Open Source ProjectsBlack Hat Europe 2015 - Time and Position Spoofing with Open Source Projects
Black Hat Europe 2015 - Time and Position Spoofing with Open Source Projects
 
Who moved my pixels?!
Who moved my pixels?!Who moved my pixels?!
Who moved my pixels?!
 
IPv4 Multicast Application Development
IPv4 Multicast Application DevelopmentIPv4 Multicast Application Development
IPv4 Multicast Application Development
 
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
 

Último

Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 

Último (20)

Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Vickovic gps tracking_app

  • 1. GPS TRACKING APP Stipe Vicković Mentor: Ivan Pašić
  • 2. App concept 2 Sensor Gateway TCP request Publish on MQTT channel Subscribe to MQTT Channel Save in database Publish to WebSocket channel Subscribe to WebSocket Update location on message
  • 3. MQTT ▰ Subscribing to MQTT channel • broker address: eu.thethings.network • broker port: 1883 • username: gps_tracker_lora • password: <app_access_key> • topic to subcribe to: gps_tracker_lora/devices/<dev_id>/up 3 {"app_id":"gps_tracker_lora","dev_id":"rak811_tracker","hardware_serial":"00679391F46E8D8E","port":1,"counter":0,"payl oad_raw":"AYgFN6kQnVsAwPgAFg==","payload_fields":{"gps":{"altitude":4.94,"latitude":34.1929,"longitude":108.8859,"sn":"0 001"}},"metadata":{"time":"2019-07-25T09:38:32.956669447Z"}}
  • 5. def on_message(client, userdata, message): """Save recived payload in database and send it on websocket """ SQL = """INSERT INTO gps_tracking_app_log(gps_id, location, date_time) VALUES (%s, ST_GeometryFromText('POINT(%s %s)', 4326), %s);""" # Extracting from payload gps_payload = json.loads(message.payload.decode()) gps_serial = gps_payload['hardware_serial'] gps_lat = gps_payload['payload_fields']['gps']['latitude'] gps_long = gps_payload['payload_fields']['gps']['longitude'] gps_time = gps_payload['metadata']['time’] # Connecting to database and executing SQL cur = connection.cursor() cur.execute(SQL, (gps_device.id, gps_long, gps_lat, gps_time)) connection.commit() cur.close() 5
  • 6. Publish to WebSocket channel 6 # Send payload to websocket channel_layer = get_channel_layer() group_name = 'device_{}'.format(gps_serial) data = {'type': 'location update', 'long': gps_long, 'lat': gps_lat} async_to_sync(channel_layer.group_send)( group_name, { 'type': 'location_update', 'message': json.dumps(data) } ) var ws = new WebSocket("ws://127.0.0.1:8000/ws/gps/<sn>/"); ws.onmessage = function (event) { …; }
  • 8. Background channel task 8 # Send payload to locatin-check channels async_to_sync(channel_layer.send)('location-check', {'type': 'position_check’, 'gps_serial': gps_serial, 'long': gps_long, 'lat': gps_lat}) class PositionCheckConsumer(SyncConsumer): def position_check(self, message): """ Check if there are zones in wich GPS device is not located and send those location on websocket """ # Filter associated Geofence zones in which device is not located exclude_zones = GeofenceZone.objects.filter(gps=gps_device).exclude(geom__contains=last_location) # If there are zones without GPS signal, send their ID via websocket if exclude_zones.exists(): # Send payload to websocket channel_layer = get_channel_layer() group_name = 'device_{}'.format(message['gps_serial']) data = {'type': 'zone warning', 'long': message['long'], 'lat': message['lat'], 'zone': [zone.id for zone in exclude_zones]} async_to_sync(channel_layer.group_send)( group_name, { 'type': 'location_update', 'message': json.dumps(data) } ) application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter([ url(r'^ws/gps/(?P<serial_number>[-w]+)/$', GpsLogConsumer) ]) ), 'channel': ChannelNameRouter({ 'location-check': PositionCheckConsumer, }) })
  • 10. Subscribe to WebSocket 10 var gps_sn = event.target.id; var ws = new WebSocket(`ws://127.0.0.1:8000/ws/gps/${gps_sn}/`); ws.open; var locationMarkers = L.layerGroup().addTo(mymap); if (event.target.classList.value == 'activated') { ws.onmessage = function (event) { locationMarkers.clearLayers(); var message = JSON.parse(event.data); if (message.type == 'zone warning') { L.marker( [message.lat, message.long], {icon: outsideIcon} ).addTo(locationMarkers).bindPopup(`<b>Device ${gps_sn} is out of zone: ${message.zone}</b>`).openPopup(); } else { L.marker( [message.lat, message.long], {icon: insideIcon} ).addTo(locationMarkers).bindPopup(`<b>Device ${gps_sn}</b>`).openPopup();; } if (mymap.getZoom() < 13) {mymap.flyTo([message.lat, message.long], 13) } else {mymap.flyTo([message.lat, message.long])} }
  • 11. 11