예제 #1
0
def withings_authorize_url(client):
    auth = WithingsAuth(WITHINGS_SETTINGS['CONSUMER_KEY'],
                        WITHINGS_SETTINGS['CONSUMER_SECRET'],
                        withings_get_callback_uri())
    authorize_url = auth.get_authorize_url()
    auth.oauth_token
    auth.oauth_secret
예제 #2
0
def withings_connect(client, oauth_verifier, oauth_token, oauth_secret):
    try:
        healthdevice = client.health_device
    except:
        healthdevice = HealthDevice(client=client)
    auth = WithingsAuth(WITHINGS_SETTINGS['CONSUMER_KEY'],
                        WITHINGS_SETTINGS['CONSUMER_SECRET'],
                        withings_get_callback_uri())
    auth.oauth_token = oauth_token
    auth.oauth_secret = oauth_secret
    print(oauth_verifier, oauth_token, oauth_secret)
    creds = auth.get_credentials(oauth_verifier)
    try:
        healthdevice = client.health_device
    except:
        healthdevice = HealthDevice(client=client)
    healthdevice.provider = HealthDevice.ProviderType.WITHINGS.value
    healthdevice.access_token = creds.access_token
    healthdevice.refresh_token = ''
    healthdevice.expires_at = datetime.now() + timedelta(days=365)
    healthdevice.meta = {
        'access_token_secret': creds.access_token_secret,
        'user_id': creds.user_id
    }
    healthdevice.save()
    return True
예제 #3
0
    def open_token(self, auth):
            try:
    	        with open(withing_config_file, 'r') as withing_token_file:
                    self._log.debug(u"Opening File")
                    self.creds = pickle.load(withing_token_file)
                    self._log.debug(u"Getting user")
		    self.client = WithingsApi(self.creds)
		    self.user = self.client.get_user()
                    if user == None :
                        self.auth = WithingsAuth(self.api_key, self.api_secret)
		        self.authorize_url = self.auth.get_authorize_url()
		        print("Go to %s allow the app and copy your oauth_verifier" %self.authorize_url)
		        self.oauth_verifier = raw_input('Please enter your oauth_verifier: ')
		        self.creds = auth.get_credentials(self.oauth_verifier)
		        self.client = WithingsApi(creds)
		        self.user = self.client.get_user()
                        if user == None :
                            self._log.error(u"Error getting user, from code")
                            self._log.error(error)
                            sys.exit("refreshing token failed from refresh_token")
                            #TODO stop plugin
                        else :
                            self._log.warning(u"Token succesfully refresh with token_refresh from file")
                with open(withing_config_file, 'w') as withing_token_file:
                    pickle.dump(self.creds, withing_token_file)

            except:
                self._log.error(u"Error with file saved or no file saved")
                self._log.error(u"Go to Advanced page to generate a new token file")
예제 #4
0
    def __init__(self, log, api_id, api_secret, period, dataPath):
        try:
            """
            Create a withing instance, allowing to use withing api
            """
            self._log = log
            self.api_id = api_id
            self.api_secret = api_secret
            self.period = period
	    self._sensors = []

	    self._dataPath = dataPath 

            if not os.path.exists(self._dataPath) :
                self._log.info(u"Directory data not exist, trying create : %s" , self._dataPath)
                try :
                    os.mkdir(self._dataPath)
                    self._log.info(u"Withings data directory created : %s"  %self._dataPath)
                except Exception as e:
                    self._log.error(e.message)
                    raise withingException ("Withings data directory not exist : %s" % self._dataPath)
	    if not os.access(self._dataPath, os.W_OK) :
                self._log.error("User %s haven't write access on data directory : %s"  %(user,  self._dataPath))
    	        raise withingException ("User %s haven't write access on data directory : %s"  %(user,  self._dataPath))

            self.withing_config_file = os.path.join(os.path.dirname(__file__), '../data/withings.json')
	    self.auth = WithingsAuth(self.api_id, self.api_secret)
#	    self.open_token(self.auth)

            try:
    	        with open(self.withing_config_file, 'r') as withing_token_file:
                    self._log.debug(u"Opening File")
                    self.creds = pickle.load(withing_token_file)
                    self._log.debug(u"Getting user")
		    self.client = WithingsApi(self.creds)
		    self.user = self.client.get_user()
                    if self.user == None :
                        self.auth = WithingsAuth(self.api_key, self.api_secret)
		        self.authorize_url = self.auth.get_authorize_url()
		        print("Go to %s allow the app and copy your oauth_verifier" %self.authorize_url)
		        self.oauth_verifier = raw_input('Please enter your oauth_verifier: ')
		        self.creds = auth.get_credentials(self.oauth_verifier)
		        self.client = WithingsApi(creds)
		        self.user = self.client.get_user()
                        if user == None :
                            self._log.error(u"Error getting user, from code")
                            self._log.error(error)
                            sys.exit("refreshing token failed from refresh_token")
                            #TODO stop plugin
                        else :
                            self._log.warning(u"Token succesfully refresh with token_refresh from file")
                with open(self.withing_config_file, 'w') as withing_token_file:
                    pickle.dump(self.creds, withing_token_file)

            except ValueError:
                self._log.error(u"error reading Withing.")
                return
        except ValueError:
            self._log.error(u"error reading Withing.")
예제 #5
0
def withings_redirect(request):
    auth = WithingsAuth(WITHINGS_SETTINGS['CONSUMER_KEY'],
                        WITHINGS_SETTINGS['CONSUMER_SECRET'],
                        healthdevice.withings_get_callback_uri())
    authorize_url = auth.get_authorize_url()
    request.session['withings_oauth_token'] = auth.oauth_token
    request.session['withings_oauth_secret'] = auth.oauth_secret
    context = {'authorize_url': authorize_url}
    return render(request, 'healthdevices/oauth_redirect.html', context)
 def test_get_authorize_url(self):
     """ Make sure the get_authorize_url function works as expected """
     auth = WithingsAuth(self.consumer_key, self.consumer_secret)
     # Returns the OAuth1Session.authorization_url results
     self.assertEqual(auth.get_authorize_url(), 'URL')
     # oauth_token and oauth_secret have now been set to the values
     # returned by OAuth1Session.fetch_request_token
     self.assertEqual(auth.oauth_token, 'fake_oauth_token')
     self.assertEqual(auth.oauth_secret, 'fake_oauth_token_secret')
예제 #7
0
def getWithingsClient():
    auth = WithingsAuth(CONSUMER_KEY, CONSUMER_SECRET)
    authorize_url = auth.get_authorize_url()
    print "Go to %s allow the app and copy your oauth_verifier" % authorize_url

    oauth_verifier = raw_input('Please enter your oauth_verifier: ')
    creds = auth.get_credentials(oauth_verifier)

    client = WithingsApi(creds)
    return client
 def test_get_credentials(self):
     """ Make sure the get_credentials function works as expected """
     auth = WithingsAuth(self.consumer_key, self.consumer_secret)
     # Returns an authorized WithingsCredentials object
     creds = auth.get_credentials('FAKE_OAUTH_VERIFIER')
     assert isinstance(creds, WithingsCredentials)
     # Check that the attributes of the WithingsCredentials object are
     # correct.
     self.assertEqual(creds.access_token, 'fake_oauth_token')
     self.assertEqual(creds.access_token_secret, 'fake_oauth_token_secret')
     self.assertEqual(creds.consumer_key, self.consumer_key)
     self.assertEqual(creds.consumer_secret, self.consumer_secret)
     self.assertEqual(creds.user_id, 'FAKEID')
 def test_attribute_defaults(self):
     """ Make sure WithingsAuth attributes have the proper defaults """
     self.assertEqual(WithingsAuth.URL,
                      'https://oauth.withings.com/account')
     auth = WithingsAuth(self.consumer_key, self.consumer_secret)
     self.assertEqual(auth.oauth_token, None)
     self.assertEqual(auth.oauth_secret, None)
예제 #10
0
 def test_attributes(self):
     """ Make sure the WithingsAuth objects have the right attributes """
     assert hasattr(WithingsAuth, 'URL')
     auth = WithingsAuth(self.consumer_key, self.consumer_secret)
     assert hasattr(auth, 'consumer_key')
     self.assertEqual(auth.consumer_key, self.consumer_key)
     assert hasattr(auth, 'consumer_secret')
     self.assertEqual(auth.consumer_secret, self.consumer_secret)
예제 #11
0
파일: app.py 프로젝트: jiivan/wykresik
def get_authorizer(token=None):
    back_url = '%s://%s/withings/comeback' % (
        request.get_header('url_scheme', 'http'),
        request.get_header('HTTP_HOST', request.get_header('SERVER_NAME', 'wykresik.genoomy.com')),
    )
    sys.stderr.write('back_url: %s\n' % (back_url,))
    auth = WithingsAuth(settings.WITHINGS['key'], settings.WITHINGS['secret'], back_url)
    if token:
        with db_connection() as db_conn:
            with db_conn.cursor() as c:
                c.execute('SELECT * FROM withings_credentials WHERE token=%s ORDER BY created_at DESC', (token,))
                db_result = c.fetchone()
        if db_result is None:
            raise InvalidToken
        secret = db_result['secret']
        auth.oauth_token = token
        auth.oauth_secret = secret
    return auth
예제 #12
0
# copied from https://github.com/maximebf/python-withings/blob/master/README.md

from withings import WithingsAuth, WithingsApi
from settings import CONSUMER_KEY, CONSUMER_SECRET

auth = WithingsAuth(CONSUMER_KEY, CONSUMER_SECRET)
authorize_url = auth.get_authorize_url()
print "Go to %s allow the app and copy your oauth_verifier" % authorize_url

oauth_verifier = raw_input('Please enter your oauth_verifier: ')
creds = auth.get_credentials(oauth_verifier)

client = WithingsApi(creds)
measures = client.get_measures(limit=1)
print "Your last measured weight: %skg" % measures[0].weight
def get_auth(CONSUMER_KEY,CONSUMER_SECRET):
    auth = WithingsAuth(CONSUMER_KEY, CONSUMER_SECRET)
    with open(withing_temp_file, 'w') as withing_auth_file:
        pickle.dump(auth, withing_auth_file)
    return auth
예제 #14
0
class WITHINGclass:
    """
    Get informations about withing
    """
    # -------------------------------------------------------------------------------------------------
    def __init__(self, log, api_id, api_secret, period, dataPath):
        try:
            """
            Create a withing instance, allowing to use withing api
            """
            self._log = log
            self.api_id = api_id
            self.api_secret = api_secret
            self.period = period
	    self._sensors = []

	    self._dataPath = dataPath 

            if not os.path.exists(self._dataPath) :
                self._log.info(u"Directory data not exist, trying create : %s" , self._dataPath)
                try :
                    os.mkdir(self._dataPath)
                    self._log.info(u"Withings data directory created : %s"  %self._dataPath)
                except Exception as e:
                    self._log.error(e.message)
                    raise withingException ("Withings data directory not exist : %s" % self._dataPath)
	    if not os.access(self._dataPath, os.W_OK) :
                self._log.error("User %s haven't write access on data directory : %s"  %(user,  self._dataPath))
    	        raise withingException ("User %s haven't write access on data directory : %s"  %(user,  self._dataPath))

            self.withing_config_file = os.path.join(os.path.dirname(__file__), '../data/withings.json')
	    self.auth = WithingsAuth(self.api_id, self.api_secret)
#	    self.open_token(self.auth)

            try:
    	        with open(self.withing_config_file, 'r') as withing_token_file:
                    self._log.debug(u"Opening File")
                    self.creds = pickle.load(withing_token_file)
                    self._log.debug(u"Getting user")
		    self.client = WithingsApi(self.creds)
		    self.user = self.client.get_user()
                    if self.user == None :
                        self.auth = WithingsAuth(self.api_key, self.api_secret)
		        self.authorize_url = self.auth.get_authorize_url()
		        print("Go to %s allow the app and copy your oauth_verifier" %self.authorize_url)
		        self.oauth_verifier = raw_input('Please enter your oauth_verifier: ')
		        self.creds = auth.get_credentials(self.oauth_verifier)
		        self.client = WithingsApi(creds)
		        self.user = self.client.get_user()
                        if user == None :
                            self._log.error(u"Error getting user, from code")
                            self._log.error(error)
                            sys.exit("refreshing token failed from refresh_token")
                            #TODO stop plugin
                        else :
                            self._log.warning(u"Token succesfully refresh with token_refresh from file")
                with open(self.withing_config_file, 'w') as withing_token_file:
                    pickle.dump(self.creds, withing_token_file)

            except ValueError:
                self._log.error(u"error reading Withing.")
                return
        except ValueError:
            self._log.error(u"error reading Withing.")


    def open_token(self, auth):
            try:
    	        with open(withing_config_file, 'r') as withing_token_file:
                    self._log.debug(u"Opening File")
                    self.creds = pickle.load(withing_token_file)
                    self._log.debug(u"Getting user")
		    self.client = WithingsApi(self.creds)
		    self.user = self.client.get_user()
                    if user == None :
                        self.auth = WithingsAuth(self.api_key, self.api_secret)
		        self.authorize_url = self.auth.get_authorize_url()
		        print("Go to %s allow the app and copy your oauth_verifier" %self.authorize_url)
		        self.oauth_verifier = raw_input('Please enter your oauth_verifier: ')
		        self.creds = auth.get_credentials(self.oauth_verifier)
		        self.client = WithingsApi(creds)
		        self.user = self.client.get_user()
                        if user == None :
                            self._log.error(u"Error getting user, from code")
                            self._log.error(error)
                            sys.exit("refreshing token failed from refresh_token")
                            #TODO stop plugin
                        else :
                            self._log.warning(u"Token succesfully refresh with token_refresh from file")
                with open(withing_config_file, 'w') as withing_token_file:
                    pickle.dump(self.creds, withing_token_file)

            except:
                self._log.error(u"Error with file saved or no file saved")
                self._log.error(u"Go to Advanced page to generate a new token file")
                #TODO stop plugin

    # -------------------------------------------------------------------------------------------------
    def add_sensor(self, device_id, device_name, device_type, user_id):
        """
        Add a sensor to sensors list.
        """
        self._sensors.append({'device_id': device_id, 'device_name': device_name, 'device_type': device_type,
                              'user_id': user_id})


    # -------------------------------------------------------------------------------------------------
    def readWithingApi(self, userid):
        """
        read the withing api for user information
        """
        try:
            user = self.client.get_user()
            self._log.debug(user)
            return user
        except AttributeError:
            self._log.error(u"### USERid '%s', ERROR while reading client value." % userid)
            return "failed"

    # -------------------------------------------------------------------------------------------------
    def readWithingMeasureApi(self, userid):
        """
        read the withing measure api information
        """
        try:
            measures = self.client.get_measures()
            return measures[0].data
        except AttributeError:
            self._log.error(u"### USERid '%s', ERROR while reading measure value." % userid)
            return "failed"


    # -------------------------------------------------------------------------------------------------
    def loop_read_sensor(self, send, send_sensor, stop):
        """
        """
        while not stop.isSet():
	    for sensor in self._sensors:
		self._log.debug(sensor)
                if sensor['device_type'] == "withing.user":
                    val = self.readWithingApi(sensor['user_id'])
		    self._log.debug(val)
                    if val != "failed":
			self._log.debug(val)
			self._log.debug(sensor)
                        send(sensor['device_id'], {'firstname': val['users'][0]['firstname'], 'lastname': val['users'][0]['lastname'], 'id': val['users'][0]['id']})
                elif sensor['device_type'] == "withing.measure":
                    val = self.readWithingMeasureApi(sensor['user_id'])
		    self._log.debug(val)
                    if val != "failed":
			timestamp = val['date']
			for measure in val['measures']:
                            sensor_name = u''
			    self._log.debug(measure)
                            if measure['type'] == 1:
                                sensor_name = "weight"
                            elif measure['type'] == 4:
                                sensor_name = "height"
                            elif measure['type'] == 5:
                                sensor_name = "fat_free_mass"
                            elif measure['type'] == 6:
                                sensor_name = "fat_ratio"
                            elif measure['type'] == 8:
                                sensor_name = "fat_free_mass"
                            elif measure['type'] == 9:
                                sensor_name = "diastolic_blood_pressure"
                            elif measure['type'] == 10:
                                sensor_name = "systolic_blood_pressure"
                            elif measure['type'] == 11:
                                sensor_name = "heart_pulse"
                            if sensor_name != u'':
                                #timestamp = calendar.timegm(sensors.date.timetuple())
				#timestamp=time.time()
				self._log.debug("Sending value to binary")
				value=float(measure['value'])/pow(10, abs(measure['unit']))
			        send_sensor(sensor['device_id'], sensor_name, value, timestamp)

                self._log.debug(u"=> '{0}' : wait for {1} seconds".format(sensor['device_name'], self.period))
    	    stop.wait(self.period)
예제 #15
0
from withings import WithingsAuth, WithingsApi

auth = WithingsAuth("53384734f261f01e1b5e728f36d77242bdf48eef43f76b19786b12eef5866", "b084dd376872378236d3d56191e5de52e3b054d01989551d1464e2d8e7b222")
#authorize_url = auth.get_authorize_url()
#print "Go to %s allow the app and copy your oauth_verifier" % authorize_url

#oauth_verifier = raw_input('Please enter your oauth_verifier: ')
creds = auth.get_credentials("IKfIyVSF1KU")

client = WithingsApi(creds)
measures = client.get_measures(limit=1)
print "Your last measured weight: %skg" % measures[0].weight