8 Commits

Author SHA1 Message Date
82b5692de1 Umgate GeoRide trademark wording 2020-05-26 23:46:21 +02:00
1275ffa882 Fix socket init error 2019-11-03 20:26:00 +01:00
9923f45a95 Add pypi badge 2019-11-02 17:51:25 +01:00
9bb33b6020 Fix exception bug 2019-11-02 17:40:53 +01:00
b0caa42ca2 Fix data on callback function 2019-10-30 20:33:07 +01:00
0368c17321 Add tracker setter for some useful properties 2019-10-29 22:44:29 +01:00
3e53a339ba Update example and some tweak 2019-10-29 21:51:41 +01:00
c548a789a8 Add support of socket 2019-10-28 22:18:32 +01:00
8 changed files with 450 additions and 73 deletions

View File

@@ -1,8 +1,10 @@
# Georideapilib # georideapilib
![Logo Georide](georide-logo.png) ![Logo GeoRide](georide-logo.png)
⚠️ this is not an official implementation ⚠️ this is not an official implementation
[![pypi_badge](https://img.shields.io/pypi/v/georideapilib?style=for-the-badge)](https://pypi.org/project/georideapilib/)
Official georide website: https://georide.fr/ Official georide website: https://georide.fr/
This library can control your georide tracker tracker This library can control your georide tracker tracker
@@ -10,7 +12,7 @@ This library can control your georide tracker tracker
Some code have been taken from @alexmohr https://github.com/alexmohr/sonyapilib Some code have been taken from @alexmohr https://github.com/alexmohr/sonyapilib
This library is used as communication interface in a home assistant component to control media players, which can be found here:(Not ready yet ;)) This library is used as communication interface in a home assistant component to control media players, which can be found here: https://github.com/ptimatth/GeorideHA
At the moment not all functions offered by the api are implemented. If you miss a function feel free to create a pull request or open a feature request. At the moment not all functions offered by the api are implemented. If you miss a function feel free to create a pull request or open a feature request.
@@ -28,5 +30,4 @@ This library has been tested with python 3.7 and above, functionality for older
- https://github.com/ptimatth/pyGeoride - https://github.com/ptimatth/pyGeoride
## Todo ## Todo
- [ ] Add support of SocketIO connection
- [ ] Add support of "Get a shared trip" endpoint - [ ] Add support of "Get a shared trip" endpoint

View File

@@ -4,69 +4,92 @@
import time import time
import datetime import datetime
from georideapilib.objects import GeorideAccount logging.config.fileConfig('logging.conf')
import georideapilib.api as GeorideApi from georideapilib.objects import GeoRideAccount
import georideapilib.api as GeoRideApi
from georideapilib.socket import GeoRideSocket
from threading import Thread
_LOGGER = logging.getLogger('example')
def example(): def example():
""" simple example function """ """ simple example function """
token = "<your_token>"# pylint: disable=C0301 # token = "<your_token>"# pylint: disable=C0301
"""account = GeorideAccount(0, "<your_email>", False, token)""" # account = GeorideAccount(0, "<your_email>", False, token)
account = GeorideApi.get_authorisation_token("<your_email>", "<your_password>") account = GeoRideApi.get_authorisation_token("<your_email>", "<your_password>")
print("token 1: ", account.auth_token) print("token 1: ", account.auth_token)
_LOGGER.info("token 1: %s", account.auth_token)
# pylint: disable=W0105 # pylint: disable=W0105
def locked_locked(data):
_LOGGER.info("Lock received")
def connect_socket(account):
socket = GeoRideSocket()
socket.subscribe_locked(locked_locked)
socket.init()
socket.connect(account.auth_token)
time.sleep(10)
socket.disconnect()
thread = Thread(target=connect_socket, args=(account))
thread.start()
""" """
account.auth_token = GeorideApi.renew_token(account.auth_token) account.auth_token = GeorideApi.renewToken(account.auth_token)
print("token 2: ", account.auth_token) print("token 2: ", account.auth_token)
""" # pylint: disable=W0105 """ # pylint: disable=W0105
user = GeorideApi.get_user(account.auth_token) user = GeoRideApi.get_user(account.auth_token)
print("User: ", user.first_name) _LOGGER.info("User: %s", user.first_name)
trackers = GeorideApi.get_trackers(account.auth_token) trackers = GeoRideApi.get_trackers(account.auth_token)
tracker = trackers[0] tracker = trackers[0]
print("Tracker name: ", tracker.tracker_name) _LOGGER.info("Tracker name: %s", tracker.tracker_name)
trips = GeorideApi.get_trips(account.auth_token, tracker.tracker_id, "2019-10-10", "2019-10-24") trips = GeoRideApi.get_trips(account.auth_token, tracker.tracker_id, "2019-10-10", "2019-10-24")
trip = trips[0] trip = trips[0]
trip_date = datetime.datetime.strptime("2019-10-10T06:45:34.000Z", '%Y-%m-%dT%H:%M:%S.%fZ') trip_date = datetime.datetime.strptime("2019-10-10T06:45:34.000Z", '%Y-%m-%dT%H:%M:%S.%fZ')
print("Trip date: {}, from: {}, to: {}".format(trip_date, trip.nice_start_address, _LOGGER.info("Trip date: %s, from: %s, to: %s", trip_date, trip.nice_start_address,
trip.nice_end_address)) trip.nice_end_address)
positions = GeorideApi.get_positions(account.auth_token, tracker.tracker_id, positions = GeoRideApi.get_positions(account.auth_token, tracker.tracker_id,
"2019-10-10", "2019-10-24") "2019-10-10", "2019-10-24")
position = positions[0] position = positions[0]
print("Position speed: {}, lon: {}, lat: {}".format(position.speed, position.longitude, _LOGGER.info("Position speed: %s, lon: %s, lat: %s", position.speed, position.longitude,
position.latitude)) position.latitude)
trip_shared = GeorideApi.share_a_trip_by_date(account.auth_token, tracker.tracker_id, trip_shared = GeoRideApi.share_a_trip_by_date(account.auth_token, tracker.tracker_id,
"2019-10-10", "2019-10-24") "2019-10-10", "2019-10-24")
print("tripShared url: {}, id: {}".format(trip_shared.url, trip_shared.share_id)) _LOGGER.info("tripShared url: %s, id: %s", trip_shared.url, trip_shared.share_id)
time.sleep(10) time.sleep(10)
have_been_locked = GeorideApi.lock_tracker(account.auth_token, tracker.tracker_id) have_been_locked = GeoRideApi.lock_tracker(account.auth_token, tracker.tracker_id)
print("Tracker have been locked: ", have_been_locked) _LOGGER.info("Tracker have been locked: %s", have_been_locked)
time.sleep(10) time.sleep(10)
have_been_unlocked = GeorideApi.unlock_tracker(account.auth_token, tracker.tracker_id) have_been_unlocked = GeoRideApi.unlock_tracker(account.auth_token, tracker.tracker_id)
print("Tracker have been unlocked: ", have_been_unlocked) _LOGGER.info("Tracker have been unlocked: %s", have_been_unlocked)
time.sleep(10) time.sleep(10)
is_locked = GeorideApi.toogle_lock_tracker(account.auth_token, tracker.tracker_id) is_locked = GeoRideApi.toogle_lock_tracker(account.auth_token, tracker.tracker_id)
print("Tracker is locked: ", is_locked) _LOGGER.info("Tracker is locked: %s", is_locked)
time.sleep(10) time.sleep(10)
trackers = GeorideApi.get_trackers(account.auth_token) trackers = GeoRideApi.get_trackers(account.auth_token)
tracker = trackers[0] tracker = trackers[0]
print("Tracker name: ", tracker.tracker_name, " is locked: ", tracker.is_locked) _LOGGER.info("Tracker name: %s is locked: %s", tracker.tracker_name, tracker.is_locked)
""" """
GeorideApi.revokeToken(account.auth_token) GeorideApi.revokeToken(account.auth_token)
""" # pylint: disable=W0105 """ # pylint: disable=W0105
example() example()

View File

@@ -8,12 +8,18 @@ import logging
import requests import requests
from georideapilib.objects import ( from georideapilib.objects import (
GeorideTracker, GeoRideTracker,
GeorideAccount, GeoRideAccount,
GeorideUser, GeoRideUser,
GeorideTrackerTrip, GeoRideTrackerTrip,
GeorideTrackerPosition, GeoRideTrackerPosition,
GeorideSharedTrip GeoRideSharedTrip
)
from georideapilib.exception import (
LoginException,
SeverException,
UnauthorizedException
) )
GEORIDE_API_HOST = "https://api.georide.fr" GEORIDE_API_HOST = "https://api.georide.fr"
@@ -33,16 +39,26 @@ _SESSION = requests.Session()
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
def get_authorisation_token(email, password): def get_authorisation_token(email, password):
""" return an authorization token """ """ return an authorization token or no"""
data = {"email": email, "password": password} data = {"email": email, "password": password}
encoded_data = json.dumps(data).encode('utf-8') encoded_data = json.dumps(data).encode('utf-8')
response = _SESSION.post( response = _SESSION.post(
GEORIDE_API_HOST + GEORIDE_API_ENDPOINT_LOGIN, GEORIDE_API_HOST + GEORIDE_API_ENDPOINT_LOGIN,
data=encoded_data, data=encoded_data,
headers={'Content-Type': 'application/json'}) headers={'Content-Type': 'application/json'})
response_data = response.json()
_LOGGER.debug(response_data) if response.status_code == 200:
account = GeorideAccount.from_json(response_data) _LOGGER.debug("Login success")
response_data = response.json()
account = GeoRideAccount.from_json(response_data)
elif response.status_code == 403:
_LOGGER.warning("Login failed")
raise LoginException(get_authorisation_token, "Login failed")
else:
_LOGGER.error("Georide login, http error code: %s", response.status_code)
raise SeverException(get_authorisation_token,
"Georide login, http error code: {}".format(response.status_code))
return account return account
@@ -52,19 +68,30 @@ def renew_token(token):
response = _SESSION.get( response = _SESSION.get(
GEORIDE_API_HOST + GEORIDE_API_ENDPOINT_NEW_TOKEN, GEORIDE_API_HOST + GEORIDE_API_ENDPOINT_NEW_TOKEN,
headers=headers) headers=headers)
response_data = response.json() if response.status_code == 200:
_LOGGER.debug(response_data) _LOGGER.debug("Token updated")
new_token = response_data['authToken'] response_data = response.json()
new_token = response_data['authToken']
elif response.status_code == 401:
_LOGGER.warnning("Renew token refused")
raise UnauthorizedException(renew_token, "Renew token refused")
else:
_LOGGER.error("Georide login, http error code: %s", response.status_code)
raise SeverException(renew_token,
"Georide login, http error code: {}".format(response.status_code))
return new_token return new_token
def revoke_token(token): def revoke_token(token):
""" invalidate the authorization token """ """ invalidate the authorization token """
headers = {"Authorization": "Bearer " + token} headers = {"Authorization": "Bearer " + token}
response = _SESSION.post( response = _SESSION.post(
GEORIDE_API_HOST + GEORIDE_API_ENDPOINT_LOGOUT, GEORIDE_API_HOST + GEORIDE_API_ENDPOINT_LOGOUT,
headers=headers) headers=headers)
if response.status_code != 204: if response.status_code == 401:
_LOGGER.warnning("Token allready revoked")
raise UnauthorizedException(revoke_token, "Token allready revoked")
if response.status_code == 401:
_LOGGER.warnning("Token allready revoked")
return False return False
return True return True
@@ -77,7 +104,7 @@ def get_user(token):
headers=headers) headers=headers)
response_data = response.json() response_data = response.json()
_LOGGER.debug(response_data) _LOGGER.debug(response_data)
account = GeorideUser.from_json(response_data) account = GeoRideUser.from_json(response_data)
return account return account
def get_trackers(token): def get_trackers(token):
@@ -90,7 +117,7 @@ def get_trackers(token):
response_data = response.json() response_data = response.json()
trackers = [] trackers = []
for json_tracker in response_data: for json_tracker in response_data:
trackers.append(GeorideTracker.from_json(json_tracker)) trackers.append(GeoRideTracker.from_json(json_tracker))
return trackers return trackers
@@ -105,7 +132,7 @@ def get_trips(token, tracker_id, from_date, to_date):
response_data = response.json() response_data = response.json()
trips = [] trips = []
for json_trip in response_data: for json_trip in response_data:
trips.append(GeorideTrackerTrip.from_json(json_trip)) trips.append(GeoRideTrackerTrip.from_json(json_trip))
return trips return trips
def get_positions(token, tracker_id, from_date, to_date): def get_positions(token, tracker_id, from_date, to_date):
@@ -119,7 +146,7 @@ def get_positions(token, tracker_id, from_date, to_date):
response_data = response.json() response_data = response.json()
positions = [] positions = []
for json_position in response_data: for json_position in response_data:
positions.append(GeorideTrackerPosition.from_json(json_position)) positions.append(GeoRideTrackerPosition.from_json(json_position))
return positions return positions
def share_a_trip_by_trip_id(token, tracker_id, trip_id): def share_a_trip_by_trip_id(token, tracker_id, trip_id):
@@ -157,7 +184,7 @@ def _share_a_trip(token, tracker_id, trip_id=None, from_date=None, # pylint: dis
headers=headers) headers=headers)
response_data = response.json() response_data = response.json()
return GeorideSharedTrip.from_json(response_data) return GeoRideSharedTrip.from_json(response_data)
def lock_tracker(token, tracker_id): def lock_tracker(token, tracker_id):
""" used to lock a tracker """ """ used to lock a tracker """

View File

@@ -0,0 +1,23 @@
""" all GeoRide exception """
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class LoginException(Error):
"""loggin exception"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class UnauthorizedException(Error):
"""loggin exception"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class SeverException(Error):
"""loggin exception"""
def __init__(self, expression, message):
self.expression = expression
self.message = message

View File

@@ -3,7 +3,12 @@ Georide objects implementation
@author Matthieu DUVAL <matthieu@duval-dev.fr> @author Matthieu DUVAL <matthieu@duval-dev.fr>
""" """
class GeorideSharedTrip: import logging
_LOGGER = logging.getLogger(__name__)
class GeoRideSharedTrip:
""" Shared trip object representation """ """ Shared trip object representation """
def __init__(self, url, shareId): def __init__(self, url, shareId):
self._url = url self._url = url
@@ -22,12 +27,12 @@ class GeorideSharedTrip:
@staticmethod @staticmethod
def from_json(json): def from_json(json):
"""return new object fromjson""" """return new object fromjson"""
return GeorideSharedTrip( return GeoRideSharedTrip(
json['url'], json['url'],
json['shareId'] json['shareId']
) )
class GeorideTrackerTrip: # pylint: disable=too-many-instance-attributes class GeoRideTrackerTrip: # pylint: disable=too-many-instance-attributes
""" Trip object representation """ """ Trip object representation """
def __init__(self, trip_id, tracker_id, average_speed, max_speed, distance, duration, # pylint: disable=R0914, R0913 def __init__(self, trip_id, tracker_id, average_speed, max_speed, distance, duration, # pylint: disable=R0914, R0913
start_address, nice_start_address, start_lat, start_lon, end_address, start_address, nice_start_address, start_lat, start_lon, end_address,
@@ -134,7 +139,7 @@ class GeorideTrackerTrip: # pylint: disable=too-many-instance-attributes
@staticmethod @staticmethod
def from_json(json): def from_json(json):
"""return new object from json""" """return new object from json"""
return GeorideTrackerTrip( return GeoRideTrackerTrip(
json['id'], json['id'],
json['trackerId'], json['trackerId'],
json['averageSpeed'], json['averageSpeed'],
@@ -153,8 +158,7 @@ class GeorideTrackerTrip: # pylint: disable=too-many-instance-attributes
json['endTime'] json['endTime']
) )
class GeoRideTrackerPosition:
class GeorideTrackerPosition:
""" Tracker position object representation """ """ Tracker position object representation """
def __init__(self, fixtime, latitude, longitude, altitude, speed, address): # pylint: disable= R0913 def __init__(self, fixtime, latitude, longitude, altitude, speed, address): # pylint: disable= R0913
self._fixtime = fixtime self._fixtime = fixtime
@@ -197,7 +201,7 @@ class GeorideTrackerPosition:
@staticmethod @staticmethod
def from_json(json): def from_json(json):
"""return new object fromjson""" """return new object fromjson"""
return GeorideTrackerPosition( return GeoRideTrackerPosition(
json['fixtime'], json['fixtime'],
json['latitude'], json['latitude'],
json['longitude'], json['longitude'],
@@ -206,10 +210,7 @@ class GeorideTrackerPosition:
json['address'] json['address']
) )
class GeoRideTracker: # pylint: disable=R0904,R0902
class GeorideTracker: # pylint: disable=R0904,R0902
""" Tracker position object representation """ """ Tracker position object representation """
def __init__(self, tracker_id, tracker_name, device_button_action, device_button_delay, # pylint: disable= R0913, R0914, R0915 def __init__(self, tracker_id, tracker_name, device_button_action, device_button_delay, # pylint: disable= R0913, R0914, R0915
vibration_level, is_old_tracker, auto_lock_freezed_to, fixtime, role, vibration_level, is_old_tracker, auto_lock_freezed_to, fixtime, role,
@@ -297,6 +298,11 @@ class GeorideTracker: # pylint: disable=R0904,R0902
""" fixtime """ """ fixtime """
return self._fixtime return self._fixtime
@fixtime.setter
def fixtime(self, fixtime):
""" fixtime """
self._fixtime = fixtime
@property @property
def role(self): def role(self):
""" role """ """ role """
@@ -347,11 +353,21 @@ class GeorideTracker: # pylint: disable=R0904,R0902
""" speed """ """ speed """
return self._speed return self._speed
@speed.setter
def speed(self, speed):
""" speed """
self._speed = speed
@property @property
def moving(self): def moving(self):
""" moving """ """ moving """
return self._moving return self._moving
@moving.setter
def moving(self, moving):
""" moving """
self._moving = moving
@property @property
def position_id(self): def position_id(self):
""" position_id """ """ position_id """
@@ -362,11 +378,21 @@ class GeorideTracker: # pylint: disable=R0904,R0902
""" latitude """ """ latitude """
return self._latitude return self._latitude
@latitude.setter
def latitude(self, latitude):
""" latitude """
self._latitude = latitude
@property @property
def longitude(self): def longitude(self):
""" longitude """ """ longitude """
return self._longitude return self._longitude
@longitude.setter
def longitude(self, longitude):
""" longitude """
self._longitude = longitude
@property @property
def altitude(self): def altitude(self):
""" altitude """ """ altitude """
@@ -382,16 +408,31 @@ class GeorideTracker: # pylint: disable=R0904,R0902
""" locked_latitude """ """ locked_latitude """
return self._locked_latitude return self._locked_latitude
@locked_latitude.setter
def locked_latitude(self, locked_latitude):
""" locked_latitude """
self._locked_latitude = locked_latitude
@property @property
def locked_longitude(self): def locked_longitude(self):
""" locked_longitude """ """ locked_longitude """
return self._locked_longitude return self._locked_longitude
@locked_longitude.setter
def locked_longitude(self, locked_longitude):
""" locked_longitude """
self._locked_longitude = locked_longitude
@property @property
def is_locked(self): def is_locked(self):
""" is_locked """ """ is_locked """
return self._is_locked return self._is_locked
@is_locked.setter
def is_locked(self, is_locked):
""" is_locked """
self._is_locked = is_locked
@property @property
def can_see_position(self): def can_see_position(self):
""" can_see_position """ """ can_see_position """
@@ -442,10 +483,15 @@ class GeorideTracker: # pylint: disable=R0904,R0902
""" status """ """ status """
return self._status return self._status
@status.setter
def status(self, status):
""" status """
self._status = status
@staticmethod @staticmethod
def from_json(json): def from_json(json):
"""return new object fromjson""" """return new object fromjson"""
return GeorideTracker( return GeoRideTracker(
json['trackerId'], json['trackerId'],
json['trackerName'], json['trackerName'],
json['deviceButtonAction'], json['deviceButtonAction'],
@@ -485,8 +531,7 @@ class GeorideTracker: # pylint: disable=R0904,R0902
json['status'] json['status']
) )
class GeoRideAccount:
class GeorideAccount:
""" Account object representation """ """ Account object representation """
def __init__(self, account_id, email, is_admin, auth_token): def __init__(self, account_id, email, is_admin, auth_token):
self._account_id = account_id self._account_id = account_id
@@ -522,7 +567,7 @@ class GeorideAccount:
@staticmethod @staticmethod
def from_json(json): def from_json(json):
"""return new object from_json""" """return new object from_json"""
return GeorideAccount( return GeoRideAccount(
json['id'], json['id'],
json['email'], json['email'],
json['isAdmin'], json['isAdmin'],
@@ -530,7 +575,8 @@ class GeorideAccount:
) )
class GeorideUser: # pylint: disable= R0902
class GeoRideUser: # pylint: disable= R0902
""" User object representation """ """ User object representation """
def __init__(self, user_id, email, first_name, created_at, phone_number, # pylint: disable= R0913 def __init__(self, user_id, email, first_name, created_at, phone_number, # pylint: disable= R0913
push_user_token, legal, date_of_birth): push_user_token, legal, date_of_birth):
@@ -586,7 +632,7 @@ class GeorideUser: # pylint: disable= R0902
@staticmethod @staticmethod
def from_json(json): def from_json(json):
"""return new object fromjson""" """return new object fromjson"""
return GeorideUser( return GeoRideUser(
json['id'], json['id'],
json['email'], json['email'],
json['firstName'], json['firstName'],
@@ -596,3 +642,95 @@ class GeorideUser: # pylint: disable= R0902
json['legal'], json['legal'],
json['dateOfBirth'] json['dateOfBirth']
) )
#TODO: remove in v0.8.0
class GeorideSharedTrip(GeoRideSharedTrip):
""" Shared trip object representation """
def __init_subclass__(cls, **kwargs):
"""Print deprecation warning."""
super().__init_subclass__(**kwargs)
_LOGGER.warning(
"GeorideSharedTrip is deprecated, modify %s to use GeoRideSharedTrip",
cls.__name__,
)
def __init__(self, *argv):
"""Print deprecation warning."""
super().__init__(*argv)
_LOGGER.warning("GeorideSharedTrip is deprecated, modify your code to use GeoRideSharedTrip")
class GeorideTrackerTrip(GeoRideTrackerTrip):
""" Trip object representation """
def __init_subclass__(cls, **kwargs):
"""Print deprecation warning."""
super().__init_subclass__(**kwargs)
_LOGGER.warning(
"GeorideTrackerTrip is deprecated, modify %s to use GeoRideTrackerTrip",
cls.__name__,
)
def __init__(self, *argv):
"""Print deprecation warning."""
super().__init__(*argv)
_LOGGER.warning("GeorideTrackerTrip is deprecated, modify your code to use GeoRideTrackerTrip")
class GeorideTrackerPosition(GeoRideTrackerPosition):
""" Trip object representation """
def __init_subclass__(cls, **kwargs):
"""Print deprecation warning."""
super().__init_subclass__(**kwargs)
_LOGGER.warning(
"GeorideTrackerPosition is deprecated, modify %s to use GeoRideTrackerPosition",
cls.__name__,
)
def __init__(self, *argv):
"""Print deprecation warning."""
super().__init__(*argv)
_LOGGER.warning("GeorideTrackerPosition is deprecated, modify your code to use GeoRideTrackerPosition")
class GeorideTracker(GeoRideTracker):
""" Trip object representation """
def __init_subclass__(cls, **kwargs):
"""Print deprecation warning."""
super().__init_subclass__(**kwargs)
_LOGGER.warning(
"GeorideTracker is deprecated, modify %s to use GeoRideTracker",
cls.__name__,
)
def __init__(self, *argv):
"""Print deprecation warning."""
super().__init__(*argv)
_LOGGER.warning("GeorideTracker is deprecated, modify your code to use GeoRideTracker")
class GeorideAccount(GeoRideAccount):
""" Trip object representation """
def __init_subclass__(cls, **kwargs):
"""Print deprecation warning."""
super().__init_subclass__(**kwargs)
_LOGGER.warning(
"GeorideAccount is deprecated, modify %s to use GeoRideAccount",
cls.__name__,
)
def __init__(self, *argv):
"""Print deprecation warning."""
super().__init__(*argv)
_LOGGER.warning("GeorideAccount is deprecated, modify your code to use GeoRideAccount")
class GeorideUser(GeoRideUser):
""" Trip object representation """
def __init_subclass__(cls, **kwargs):
"""Print deprecation warning."""
super().__init_subclass__(**kwargs)
_LOGGER.warning(
"GeorideUser is deprecated, modify %s to use GeoRideUser",
cls.__name__,
)
def __init__(self, *argv):
"""Print deprecation warning."""
super().__init__(*argv)
_LOGGER.warning("GeorideUser is deprecated, modify your code to use GeoRideUser")

130
georideapilib/socket.py Normal file
View File

@@ -0,0 +1,130 @@
""" GeoRide socket-io implementation """
import logging
import socketio
from georideapilib.api import GEORIDE_API_HOST
_LOGGER = logging.getLogger(__name__)
sio = socketio.Client(reconnection=True) # pylint: disable=C0103
@sio.on('connect')
def on_connect():
""" event: connected """
_LOGGER.debug('GeoRide socket connected')
@sio.on('disconnect')
def on_disconnect():
""" event: disconnected """
_LOGGER.debug('GeoRide socket disconnected')
class GeoRideSocket():
"""docstring for GeoRideSocket"""
def __init__(self):
self._on_message_callback = None
self._on_device_callback = None
self._on_position_callback = None
self._on_alarm_callback = None
self._on_refresh_tracker_callback = None
self._on_locked_callback = None
self._initialised = False
def subscribe_on_message(self, callback_function):
"""event: tells you authentication informations."""
self._on_message_callback = callback_function
def subscribe_device(self, callback_function):
"""event: tells you when a device is added to the account."""
self._on_device_callback = callback_function
def subscribe_position(self, callback_function):
"""event: tells you when a device sent a position."""
self._on_position_callback = callback_function
def subscribe_alarm(self, callback_function):
"""event: tells you when a device trigger an alarm."""
self._on_alarm_callback = callback_function
def subscribe_refresh_tracker(self, callback_function):
"""event: tells you when you need to refresh your list of trackers"""
self._on_refresh_tracker_callback = callback_function
def subscribe_locked(self, callback_function):
"""event: tells you when a device has been locked or unlocked."""
self._on_locked_callback = callback_function
def init(self):
"""init the context"""
@sio.on('message')
def on_message(data):
""" on_message """
_LOGGER.debug('Message received: %s', data)
if self._on_message_callback is not None:
self._on_message_callback(data)
@sio.on('device')
def on_device(data):
""" on_device """
_LOGGER.debug('Device received: %s', data)
if self._on_device_callback is not None:
self._on_device_callback(data)
@sio.on('position')
def on_position(data):
""" on_position """
_LOGGER.debug('Position received:%s', data)
if self._on_position_callback is not None:
self._on_position_callback(data)
@sio.on('alarm')
def on_alarm(data):
""" on_alarm """
_LOGGER.debug('Alarm received: %s', data)
if self._on_alarm_callback is not None:
self._on_alarm_callback(data)
@sio.on('refreshTrackersInstruction')
def on_refresh_tracker():
""" on_refresh_tracker """
_LOGGER.debug('Refresh tracker received')
if self._on_refresh_tracker_callback is not None:
self._on_refresh_tracker_callback()
@sio.on('lockedPosition')
def on_locked(data):
""" on_locked """
_LOGGER.debug('Locked received: %s', data)
if self._on_locked_callback is not None:
self._on_locked_callback(data)
self._initialised = True
def connect(self, auth_token):
""" connect to the georide socket"""
if self._initialised is not False:
sio.connect(GEORIDE_API_HOST, headers={'token': auth_token})
sio.wait()
else:
_LOGGER.error("Please call init() before")
def disconnect(self):
"""disconnect from the georide socket"""
sio.disconnect()
#TODO: remove in v0.8.0
class GeorideSocket(GeoRideSocket):
""" Trip object representation """
def __init_subclass__(cls, **kwargs):
"""Print deprecation warning."""
super().__init_subclass__(**kwargs)
_LOGGER.warning(
"GeorideSocket is deprecated, modify %s to use GeoRideSocket",
cls.__name__,
)
def __init__(self, *argv):
"""Print deprecation warning."""
super().__init__(*argv)
_LOGGER.warning("GeorideSocket is deprecated, modify your code to use GeoRideSocket")

35
logging.conf Normal file
View File

@@ -0,0 +1,35 @@
[loggers]
keys=root,example
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_example]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[logger_engine_io]
level=ERROR
handlers=consoleHandler
qualname=engineio.client
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

View File

@@ -19,16 +19,16 @@ CURRENT_DIR = os.path.dirname(__file__)
setup( setup(
name='georideapilib', name='georideapilib',
packages=['georideapilib'], # this must be the same as the name above packages=['georideapilib'], # this must be the same as the name above
version='0.2.0', version='0.5.0',
description='Lib to control georide tracker devices with their rest api', description='Lib to control GeoRide tracker devices with their rest api',
author='Matthieu DUVAL', author='Matthieu DUVAL',
author_email='georideapilib@duval-dev.fr', author_email='georideapilib@duval-dev.fr',
# use the URL to the github repo # use the URL to the github repo
url='https://github.com/ptimatth/pyGeoride', url='https://github.com/ptimatth/pyGeoride',
download_url='https://codeload.github.com/ptimatth/pyGeoride/tar.gz/0.1.0', download_url='https://codeload.github.com/ptimatth/pyGeoride/tar.gz/0.1.0',
keywords=['rest', 'georide', 'api', 'grutier'], # arbitrary keywords keywords=['rest', 'georide', 'api', 'grutier', 'GeoRide'], # arbitrary keywords
classifiers=[], classifiers=[],
install_requires=[], install_requires=["python-socketio[client]"],
tests_require=[ tests_require=[
'pytest>=3.7', 'pytest>=3.7',
'pytest-pep8', 'pytest-pep8',