Skip to content

Commit

Permalink
Merge pull request #13 from Xaldimo/pr/1
Browse files Browse the repository at this point in the history
Add margin for GPS deviation
  • Loading branch information
iantrich authored Nov 19, 2019
2 parents 8a1e81c + de31183 commit 44c1e4a
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions custom_components/places/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@
import logging, json, requests
from datetime import datetime, timedelta
from requests import get
from math import radians, cos, sin, asin, sqrt

import voluptuous as vol
import homeassistant.helpers.location as location
Expand Down Expand Up @@ -431,6 +432,22 @@ def update(self):
""" Call the do_update function based on scan interval and throttle """
self.do_update("Scan Interval")

def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r

def do_update(self, reason):
"""Get the latest data and updates the states."""

Expand Down Expand Up @@ -466,8 +483,11 @@ def do_update(self, reason):
distance_km = round(distance_m / 1000, 2)
distance_from_home = str(distance_km)+' km'

if last_distance_m > distance_m:
direction = "towards home"
deviation = haversine(old_latitude, old_longitude, new_latitude, new_longitude)
if deviation <= '0.2': # in kilometers
direction = "stationary"
elif last_distance_m > distance_m:
direction = "towards home"
elif last_distance_m < distance_m:
direction = "away from home"
else:
Expand Down

0 comments on commit 44c1e4a

Please sign in to comment.