Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- FitbitSleepHandler.py (class)
- This module is meant to utilize all of the capability of the exposed python sleep api to analyze sleep patterns perhaps above and beyond what fitbit itself does.
- These are my current 4 keys:
- consumer: "66febeae096fe9442d10dd3e92d54de2"
- consumer secret: "b8b002ddf50dd3525f57b9a350051b97"
- reource owner: resource_owner_key='20eb22828f652f729002ba0f855d07f3'
- resource owner secret: resource_owner_secret='48eaa2e1e11ea551d1e3579c3274cccd')
- There is only one single sleep-related call made from an authorized client and that function signature is get_sleep(Datetime dt). This function returns a conglomerate data type of embedded lists and dictionaries.
- If sleepUnitsDict is the main dictionary returned it has two keys, 'sleep' and 'summary'. sleepUnitsDict['sleep'] returns a list of one element which contains a number of dictionaries.
- sleepUnitsDict['sleep']
- sleepUnitsDict['summary']
- The 'sleep' is a dictionary with these 17 keys:
- logId
- dateOfSleep
- minutesToFallAsleep
- awakeningsCount
- minutesAwake
- timeInBed
- minutesAsleep
- awakeDuration
- efficiency
- isMainSleep
- startTime
- restlessCount
- duration
- restlessDuration
- minuteData
- minutesAfterWakeup
- awakeCount
- Each key has a single value except 'minuteData' which is a dictionary of time values presumably used by other calculations. The 'summary'is another dictionary with these 3 keys:
- totalTimeInBed
- totalMinutesAsleep
- totalSleepRecords
- Therefore once you get the two parts of returned value you can get at the data directly by using these keys.
- sleepUnitsDict = authd_client.get_sleep(datetime)
- sleepList = sleepUnitsDict['sleep']
- summaryDict = sleepUnitsDict['summary']
- x = sleepList[0]
- dataitem = x['one of the sleep keys']
- dataitem = summaryDict['one of the 3 summary keys']
- '''
- class FitBitImpl:
- def __init__(self,ownerKey,ownerSecret,resourceOwnerKey,resourceOwnerSecret):
- import fitbit
- self.ownerKey = ownerKey
- self.ownerSecret = ownerSecret
- self.resourceOwnerKey = resourceOwnerKey
- self.resourceOwnerSecret =resourceOwnerSecret
- self.value1 = 0
- self.value2 = 0
- self.value3 = 0
- # Class variable which should be visible to other methods
- self.authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
- # todo add check for bad dates or no data for a given day and decide how to best handle the situation gracefully. May need to do this in a called method or, make the connection here in the init. Yes get the auth client here and save it as class variable like the others here. Then in each method check if client is null or not usable, if so get it again.
- def printCurrentDeviceInfo(self):
- import fitbit
- authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
- devicesList = authd_client.get_devices()
- print 'Number of devices:', len(devicesList)
- myDevice = devicesList[0] # I personally have only one device currently.
- print 'Device Info'
- print '==========='
- # more useful means to populate data fields is to reference by name.
- batteryLevel = myDevice['battery']
- print 'Battery level:',batteryLevel
- lastSyncTime = myDevice['lastSyncTime']
- print 'Last sync time:',lastSyncTime
- macAddress = myDevice['mac']
- print 'MAC Address:', macAddress
- deviceType = myDevice['type']
- print 'Device Type:',deviceType
- deviceId = myDevice['id']
- print 'Device Id:', deviceId
- deviceVersion = myDevice['deviceVersion']
- print 'Device Version: ', deviceVersion
- # looping useful in case where you don't assume any keys
- # or you want to process all keys-values
- for key in myDevice:
- print key + ': ' + myDevice[key]
- # Returns the sleep portion of result for a given datetime
- def sleepData(self,datetime):
- import fitbit
- authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
- sleepUnitsDict = authd_client.get_sleep(datetime)
- sleepList = sleepUnitsDict['sleep']
- sleepDict = sleepList[0] #there only is one item in this list, a dictionar
- return sleepDict
- # Prints out the name-value pairs fom the minuteData name in sleep data record as the raw data has it.
- def dumpMinuteDataList(self, datetime):
- # minutesData is a list with integer indices
- minutesData = self.getMinutesData(datetime)
- for i in range(len(minutesData)):
- print i, minutesData[i]
- '''
- todos:
- 1. change to use authn client we got in init; check that its usable if not THEN try to get a fresh one. Do this in all methods that use client. Other error handling to add.
- '''
- def dumpMinuteData(self, datetime):
- # minutesData is a list with integer indices
- minuteData = self.getMinuteData(datetime)
- # I am currently unsure what the value that is associated with a dateTime
- # represents. You see 1,2 or 3 for each minute. What's it mean?
- for i in range(len(minuteData)):
- value = minuteData[i]['value']
- if value == '1':
- self.value1 = self.value1 + 1
- elif value == '2':
- self.value2 = self.value2 + 1
- elif value == '3':
- self.value3 = self.value3 + 1
- print minuteData[i]['dateTime'], value
- print
- print 'Minute Value Totals for Given DateTime'
- print '======================================'
- print 'Value 1 Total = ' + str(self.value1)
- print 'Value 2 Total = ' + str(self.value2)
- print 'Value 3 Total = ' + str(self.value3)
- # This method returns a dictionary of value to value totals
- # over the entire sleep period. I am still figuring out what these
- # values of 1,2 or 3 for each minute in all minutes covered.
- def getSleepMinuteValuesTotals(self, datetime):
- # minutesData is a list with integer indices
- minuteData = self.getMinuteData(datetime)
- # I am currently unsure what the value that is associated with a dateTime
- # represents. You see 1,2 or 3 for each minute. What's it mean?
- for i in range(len(minuteData)):
- value = minuteData[i]['value']
- if value == '1':
- self.value1 = self.value1 + 1
- elif value == '2':
- self.value2 = self.value2 + 1
- elif value == '3':
- self.value3 = self.value3 + 1
- valueTotalsDict ={1:self.value1, 2:self.value2, 3:self.value3}
- return valueTotalsDict
- def getMinuteData(self, datetime):
- import fitbit
- authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
- sleepUnitsDict = authd_client.get_sleep(datetime)
- sleepList = sleepUnitsDict['sleep']
- sleepDict = sleepList[0] # only is one item in this list.
- return sleepDict['minuteData']
- # Returns the summary part of result for a given datetime
- def getSleepSummary(self, datetime):
- import fitbit
- authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
- sleepDataDict = authd_client.get_sleep(datetime)
- summaryDict = sleepDataDict['summary']
- return summaryDict
- # There are 3 summary keys and 17 sleep or 20 total keys to grab data
- # from a results object returned.This method tests them by accessing them.
- def testAllSleepKeyvalues(self, datetime): #todo better method name
- import fitbit
- authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
- sleepUnitsDict = authd_client.get_sleep(datetime)
- sleepList = sleepUnitsDict['sleep']
- summaryDict = sleepUnitsDict['summary']
- sleepDataDict = sleepList[0] #only one item in this list which is a dictionary.
- print 'Sleep Names and Values by Direct Reference (17)'
- print '==============================================='
- print '1. logId: ' + str(sleepDataDict['logId'])
- print '2. dateOfSleep: ' + sleepDataDict['dateOfSleep']
- print '3. minutesToFallAsleep: ' + str(sleepDataDict['minutesToFallAsleep'])
- print '4. awakeningsCount: ' + str(sleepDataDict['awakeningsCount'])
- print '5. minutesAwake: ' + str(sleepDataDict['minutesAwake'])
- print '6. timeInBed: ' + str(sleepDataDict['timeInBed'])
- print '7. minutesAsleep: ' + str(sleepDataDict['minutesAsleep'])
- print '8. awakeDuration: ' + str(sleepDataDict['awakeDuration'])
- print '9. efficiency: ' + str(sleepDataDict['isMainSleep'])
- print '10. isMainSleep: ' + str(sleepDataDict['logId'])
- print '11. startTime: ' + sleepDataDict['startTime']
- print '12. restlessCount: ' + str(sleepDataDict['restlessCount'])
- print '13. duration: ' + str(sleepDataDict['duration'])
- print '14. restlessDuration: ' + str(sleepDataDict['restlessDuration'])
- print '15. minutesAfterWakeup: ' + str(sleepDataDict['minutesAfterWakeup'])
- print '16. awakeCount: ' + str(sleepDataDict['awakeCount'])
- print '17. minuteData: ' + str(sleepDataDict['minuteData'])
- print
- print 'Summary Names and Values by Direct Reference (3)'
- print '================================================'
- print '1. totalTimeInBed: ' + str(summaryDict['totalTimeInBed'])
- print '2. totalMinutesAsleep: ' + str(summaryDict['totalMinutesAsleep'])
- print '3. totalSleepRecords: ' + str(summaryDict['totalSleepRecords'])
- # Diagnostic simply prints to screen demonstrating api
- def dumpSleepData(self,datetime):
- import fitbit
- authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
- sleepUnitsDict = authd_client.get_sleep(datetime)
- sleepList = sleepUnitsDict['sleep']
- summaryDict = sleepUnitsDict['summary']
- print 'sleepList length: ',len(sleepList)
- print 'sleepList type:', type(sleepList)
- print 'summaryDict length: ',len(summaryDict)
- print 'summaryDict type ',type(summaryDict)
- sleepDict = sleepList[0] #there only is one item in this list, a dictionary.
- print
- for key in sleepDict:
- print key + ':' + str(sleepDict[key])
- print
- for key in summaryDict:
- print key + ':' + str(summaryDict[key])
- print
- #___________________________________________________________________________
- # Here we instantiate the class then invoke class methods
- ownerKey = '66febeae096fe9442d10dd3e92d54de2'
- ownerSecret = 'b8b002ddf50dd3525f57b9a350051b97'
- resourceOwnerKey = '20eb22828f652f729002ba0f855d07f3'
- resourceOwnerSecret = '48eaa2e1e11ea551d1e3579c3274cccd'
- import datetime
- import console
- date = datetime.date(2015,7,9) # Change date here or set up a parameter.
- # instantiate class then invoke some void methods (no return types)
- fitbitimpl = FitBitImpl(ownerKey,ownerSecret,resourceOwnerKey,resourceOwnerSecret)
- console.clear()
- #fitbitimpl.printAllSleepData(date)
- #fitbitimpl.sleepSummary(date)
- #fitbitimpl.testAllSleepKeyvalues(date)
- #fitbitimpl.dumpMinuteData(date)
- #fitbitimpl.dumpMinuteData(date)
- sleepValuesTotal = fitbitimpl.getSleepMinuteValuesTotals(date)
- print sleepValuesTotal
- #console.hide_output()
- #print 'Value 1 Total = ' + str(getSleepMinuteValuesTotals())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement