Example #1
0
    def __init__(self, hass, config: ConfigType, see) -> None:
        """Initialize the scanner."""
        from locationsharinglib import Service
        from locationsharinglib.locationsharinglibexceptions import \
            InvalidCookies

        self.see = see
        self.username = config[CONF_USERNAME]
        self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY]
        self.scan_interval = timedelta(seconds=config[CONF_SCAN_INTERVAL])

        try:
            credfile = "{}.{}".format(hass.config.path(CREDENTIALS_FILE),
                                      slugify(self.username))
            self.service = Service(credfile, self.username)
            self._update_info()

            track_time_interval(
                hass, self._update_info, self.scan_interval)

            self.success_init = True

        except InvalidCookies:
            _LOGGER.error("You have specified invalid login credentials")
            self.success_init = False
    def __init__(self, hass, config: ConfigType, see) -> None:
        """Initialize the scanner."""
        self.see = see
        self.username = config[CONF_USERNAME]
        self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY]
        self.scan_interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=60)

        credfile = "{}.{}".format(
            hass.config.path(CREDENTIALS_FILE), slugify(self.username)
        )
        try:
            self.service = Service(credfile, self.username)
            self._update_info()

            track_time_interval(hass, self._update_info, self.scan_interval)

            self.success_init = True

        except InvalidCookies:
            _LOGGER.error(
                "You have specified invalid login credentials. "
                "Please make sure you have saved your credentials"
                " in the following file: %s",
                credfile,
            )
            self.success_init = False
Example #3
0
def string_distances():
    from locationsharinglib import Service
    from spatial import vincenty_inverse as vi
    with open("coordinates.txt", "r") as f:
        data = f.readlines()
    home = [float(data[1].split(":", 1)[1]), float(data[2].split(":", 1)[1])]
    cookies_file = 'cookies.txt'
    google_email = '*****@*****.**'
    service = Service(cookies_file=cookies_file,
                      authenticating_account=google_email)
    names = []
    distances = []
    for person in service.get_all_people():
        names.append(person.nickname)
        pp = [person.latitude, person.longitude]
        distances.append(vi(home, pp).km())
    dictionary = dict(zip(names, distances))
    sortednames = []
    sorteddists = []
    for elem in sorted(dictionary.items()):
        sortednames.append(elem[0])
        sorteddists.append(str(elem[1]))
    allnames = str(",".join(sortednames))
    alldistances = str(",".join(sorteddists))
    return str(",".join([alldistances, allnames]))
Example #4
0
def get_people_latlons():
    service = Service(cookies_file='cookies.txt',
                      authenticating_account=os.getenv('GOOGLE_ACCOUNT_EMAIL'))
    people = {}
    for person in service.get_all_people():
        people[person.nickname] = {
            'lat': person.latitude,
            'lon': person.longitude
        }
        print(person.nickname, person.latitude, person.longitude)
    return people
Example #5
0
def get_location():
  cookies_file = 'location_sharing.cookies'
  google_email = '*****@*****.**'


  service = Service(cookies_file=cookies_file, authenticating_account=google_email)

  person = list(service.get_all_people())[0]
  for location in settings.locations:
    dist = geodesic((person.latitude,person.longitude),location[1]).miles 
    if dist <= location[2]:
      return location[0]
Example #6
0
 def __init__(self, username, cookie):
     try:
         self.service = Service(cookie, username)
     except InvalidCookies:
         print("Invalid cookie.")
         raise InvalidCookies
     print("Authenticated.\n")
     print(list(self.service.get_all_people()))
     self.now = None
     self.you = None
     self.people = []
     # dictionary of people by id
     self.person_d = {}
     self.person_n = {}
     self.load()
     self.auto_update()
Example #7
0
    def __init__(self, hass, config: ConfigType, see: SeeCallback) -> None:
        """Initialize the scanner."""
        self.see = see
        self.username = config[CONF_USERNAME]
        self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY]
        self.scan_interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=60)
        self._prev_seen: dict[str, str] = {}

        credfile = f"{hass.config.path(CREDENTIALS_FILE)}.{slugify(self.username)}"
        try:
            self.service = Service(credfile, self.username)
            self._update_info()

            track_time_interval(hass, self._update_info, self.scan_interval)

            self.success_init = True

        except InvalidCookies:
            _LOGGER.error(
                "The cookie file provided does not provide a valid session. Please create another one and try again"
            )
            self.success_init = False
Example #8
0
    def __init__(self, hass, config: ConfigType, see) -> None:
        """Initialize the scanner."""
        from locationsharinglib import Service
        from locationsharinglib.locationsharinglibexceptions import InvalidUser

        self.see = see
        self.username = config[CONF_USERNAME]
        self.password = config[CONF_PASSWORD]

        try:
            self.service = Service(self.username, self.password,
                                   hass.config.path(CREDENTIALS_FILE))
            self._update_info()

            track_time_interval(hass, self._update_info,
                                MIN_TIME_BETWEEN_SCANS)

            self.success_init = True

        except InvalidUser:
            _LOGGER.error("You have specified invalid login credentials")
            self.success_init = False
Example #9
0
    return int(round(time.time() * 1000))


def getPersons():
    global service
    return list(service.get_all_people())


app = Flask(__name__)

http_server_port = int(sys.argv[1])
google_email = sys.argv[2]
cookies_file = sys.argv[3]
time_window_ms = 500

service = Service(cookies_file=cookies_file,
                  authenticating_account=google_email)
persons = getPersons()
last_update_time = millis()


@app.route('/users/<user>', methods=['GET'])
def personDataRoute(user):
    global persons
    global last_update_time
    now = millis()
    if (now - last_update_time) > time_window_ms:
        persons = getPersons()
        last_update_time = millis()

    result = 'null'
    for person in persons:
Example #10
0
import re
from locationsharinglib import Service
service = Service("*****@*****.**",
                  "3BUnwejC4BwDkTjP",
                  cookies_file=".google_maps_location_sharing.cookies")
for person in service.get_all_people():
    print(person)
Example #11
0
email = os.environ['EMAIL']
password = os.environ['PASSWORD']
mqtt_server = os.environ['MQTT_SERVER']
poll_interval = os.environ['POLL_INTERVAL']
home_latitude = os.environ['HOME_LATITUDE']
home_longitude = os.environ['HOME_LONGITUDE']

print("Pulling locations for", email)

client = mqtt.Client()
client.connect(mqtt_server, 1883, 60)
client.loop_start()

print("Connected to", mqtt_server)

service = Service(email, password)

home = (float(home_latitude), float(home_longitude))

while True:
    people = service.get_all_people()
    print("Found " + str(len(people)) + " people.")
    for person in people:
        # ignore locations that are not at least accurate within 1000 meters
        if person._accuracy > 1000:
            continue
        mqtt_topic = 'google/location/' + person.full_name.lower().replace(
            " ", "_")
        mqtt_data = {
            "latitude": person.latitude,
            "longitude": person.longitude,
Example #12
0
        else:
            presence[zone] = "CLOSED"

    # logger.info("Nickname: {}, Zone: {}, distance: {}, presence: {}".format(
    #    nickname, zone, distance, presence[zone]))
    logger.info("Presence for {}: {}".format(nickname, presence))
    payload = "{presence:" + str(presence) + "}"
    MQTT_CLIENT.publish(prefix, payload)


def send_heartbeat(client):
    now = datetime.now()
    time = now.strftime(ZULU_DATE_FORMAT_STRING)
    prefix = "{}/{}".format(MESSAGE_PREFIX, "heartbeat")
    payload = "{time:" + str(time) + "}"
    logger.info("Heartbeat {}: {}".format(prefix, payload))
    MQTT_CLIENT.publish(prefix, payload)


setup()
service = Service(cookies_file=COOKIES_FILE,
                  authenticating_account=GOOGLE_EMAIL)

for person in service.get_all_people():
    send_person_location(MQTT_CLIENT, person)
    send_person_zones(MQTT_CLIENT, person)

send_heartbeat(MQTT_CLIENT)

# /usr/bin/python3 /opt/openhab/conf/scripts/GOOGLELOCATION/location.py