Advertisement
Guest User

Untitled

a guest
Aug 4th, 2015
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.66 KB | None | 0 0
  1. '''
  2. FitbitSleepHandler.py (class)
  3. 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.
  4.  
  5.  
  6. These are my current 4 keys:
  7. consumer: "66febeae096fe9442d10dd3e92d54de2"
  8. consumer secret: "b8b002ddf50dd3525f57b9a350051b97"
  9. reource owner: resource_owner_key='20eb22828f652f729002ba0f855d07f3'
  10. resource owner secret: resource_owner_secret='48eaa2e1e11ea551d1e3579c3274cccd')
  11.  
  12.  
  13. 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.
  14.  
  15. 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.
  16.  
  17. sleepUnitsDict['sleep']
  18. sleepUnitsDict['summary']
  19.  
  20. The 'sleep' is a dictionary with these 17 keys:
  21.  
  22. logId
  23. dateOfSleep
  24. minutesToFallAsleep
  25. awakeningsCount
  26. minutesAwake
  27. timeInBed
  28. minutesAsleep
  29. awakeDuration
  30. efficiency
  31. isMainSleep
  32. startTime
  33. restlessCount
  34. duration
  35. restlessDuration
  36. minuteData
  37. minutesAfterWakeup
  38. awakeCount
  39.  
  40. 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:
  41.  
  42.  
  43. totalTimeInBed
  44. totalMinutesAsleep
  45. totalSleepRecords
  46.  
  47. Therefore once you get the two parts of returned value you can get at the data directly by using these keys.
  48.  
  49. sleepUnitsDict = authd_client.get_sleep(datetime)
  50. sleepList = sleepUnitsDict['sleep']
  51. summaryDict = sleepUnitsDict['summary']
  52.  
  53. x = sleepList[0]
  54. dataitem = x['one of the sleep keys']
  55.  
  56. dataitem = summaryDict['one of the 3 summary keys']
  57.  
  58. '''
  59. class FitBitImpl:
  60. def __init__(self,ownerKey,ownerSecret,resourceOwnerKey,resourceOwnerSecret):
  61. import fitbit
  62. self.ownerKey = ownerKey
  63. self.ownerSecret = ownerSecret
  64. self.resourceOwnerKey = resourceOwnerKey
  65. self.resourceOwnerSecret =resourceOwnerSecret
  66. self.value1 = 0
  67. self.value2 = 0
  68. self.value3 = 0
  69.  
  70. # Class variable which should be visible to other methods
  71. self.authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
  72.  
  73.  
  74. # 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.
  75.  
  76. def printCurrentDeviceInfo(self):
  77. import fitbit
  78. authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
  79. devicesList = authd_client.get_devices()
  80.  
  81. print 'Number of devices:', len(devicesList)
  82.  
  83. myDevice = devicesList[0] # I personally have only one device currently.
  84. print 'Device Info'
  85. print '==========='
  86.  
  87. # more useful means to populate data fields is to reference by name.
  88. batteryLevel = myDevice['battery']
  89. print 'Battery level:',batteryLevel
  90. lastSyncTime = myDevice['lastSyncTime']
  91. print 'Last sync time:',lastSyncTime
  92. macAddress = myDevice['mac']
  93. print 'MAC Address:', macAddress
  94. deviceType = myDevice['type']
  95. print 'Device Type:',deviceType
  96. deviceId = myDevice['id']
  97. print 'Device Id:', deviceId
  98. deviceVersion = myDevice['deviceVersion']
  99. print 'Device Version: ', deviceVersion
  100.  
  101. # looping useful in case where you don't assume any keys
  102. # or you want to process all keys-values
  103. for key in myDevice:
  104. print key + ': ' + myDevice[key]
  105.  
  106. # Returns the sleep portion of result for a given datetime
  107. def sleepData(self,datetime):
  108. import fitbit
  109. authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
  110. sleepUnitsDict = authd_client.get_sleep(datetime)
  111. sleepList = sleepUnitsDict['sleep']
  112. sleepDict = sleepList[0] #there only is one item in this list, a dictionar
  113. return sleepDict
  114.  
  115. # Prints out the name-value pairs fom the minuteData name in sleep data record as the raw data has it.
  116. def dumpMinuteDataList(self, datetime):
  117. # minutesData is a list with integer indices
  118. minutesData = self.getMinutesData(datetime)
  119. for i in range(len(minutesData)):
  120. print i, minutesData[i]
  121.  
  122. '''
  123. todos:
  124. 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.
  125. '''
  126. def dumpMinuteData(self, datetime):
  127. # minutesData is a list with integer indices
  128. minuteData = self.getMinuteData(datetime)
  129. # I am currently unsure what the value that is associated with a dateTime
  130. # represents. You see 1,2 or 3 for each minute. What's it mean?
  131. for i in range(len(minuteData)):
  132. value = minuteData[i]['value']
  133. if value == '1':
  134. self.value1 = self.value1 + 1
  135. elif value == '2':
  136. self.value2 = self.value2 + 1
  137. elif value == '3':
  138. self.value3 = self.value3 + 1
  139.  
  140. print minuteData[i]['dateTime'], value
  141.  
  142. print
  143. print 'Minute Value Totals for Given DateTime'
  144. print '======================================'
  145. print 'Value 1 Total = ' + str(self.value1)
  146. print 'Value 2 Total = ' + str(self.value2)
  147. print 'Value 3 Total = ' + str(self.value3)
  148.  
  149. # This method returns a dictionary of value to value totals
  150. # over the entire sleep period. I am still figuring out what these
  151. # values of 1,2 or 3 for each minute in all minutes covered.
  152. def getSleepMinuteValuesTotals(self, datetime):
  153. # minutesData is a list with integer indices
  154. minuteData = self.getMinuteData(datetime)
  155. # I am currently unsure what the value that is associated with a dateTime
  156. # represents. You see 1,2 or 3 for each minute. What's it mean?
  157. for i in range(len(minuteData)):
  158. value = minuteData[i]['value']
  159. if value == '1':
  160. self.value1 = self.value1 + 1
  161. elif value == '2':
  162. self.value2 = self.value2 + 1
  163. elif value == '3':
  164. self.value3 = self.value3 + 1
  165.  
  166. valueTotalsDict ={1:self.value1, 2:self.value2, 3:self.value3}
  167. return valueTotalsDict
  168.  
  169.  
  170. def getMinuteData(self, datetime):
  171. import fitbit
  172. authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
  173. sleepUnitsDict = authd_client.get_sleep(datetime)
  174. sleepList = sleepUnitsDict['sleep']
  175. sleepDict = sleepList[0] # only is one item in this list.
  176. return sleepDict['minuteData']
  177.  
  178.  
  179. # Returns the summary part of result for a given datetime
  180. def getSleepSummary(self, datetime):
  181. import fitbit
  182. authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
  183. sleepDataDict = authd_client.get_sleep(datetime)
  184. summaryDict = sleepDataDict['summary']
  185. return summaryDict
  186.  
  187. # There are 3 summary keys and 17 sleep or 20 total keys to grab data
  188. # from a results object returned.This method tests them by accessing them.
  189.  
  190. def testAllSleepKeyvalues(self, datetime): #todo better method name
  191. import fitbit
  192. authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
  193. sleepUnitsDict = authd_client.get_sleep(datetime)
  194. sleepList = sleepUnitsDict['sleep']
  195. summaryDict = sleepUnitsDict['summary']
  196. sleepDataDict = sleepList[0] #only one item in this list which is a dictionary.
  197. print 'Sleep Names and Values by Direct Reference (17)'
  198. print '==============================================='
  199. print '1. logId: ' + str(sleepDataDict['logId'])
  200. print '2. dateOfSleep: ' + sleepDataDict['dateOfSleep']
  201. print '3. minutesToFallAsleep: ' + str(sleepDataDict['minutesToFallAsleep'])
  202. print '4. awakeningsCount: ' + str(sleepDataDict['awakeningsCount'])
  203. print '5. minutesAwake: ' + str(sleepDataDict['minutesAwake'])
  204. print '6. timeInBed: ' + str(sleepDataDict['timeInBed'])
  205. print '7. minutesAsleep: ' + str(sleepDataDict['minutesAsleep'])
  206. print '8. awakeDuration: ' + str(sleepDataDict['awakeDuration'])
  207. print '9. efficiency: ' + str(sleepDataDict['isMainSleep'])
  208. print '10. isMainSleep: ' + str(sleepDataDict['logId'])
  209. print '11. startTime: ' + sleepDataDict['startTime']
  210. print '12. restlessCount: ' + str(sleepDataDict['restlessCount'])
  211. print '13. duration: ' + str(sleepDataDict['duration'])
  212. print '14. restlessDuration: ' + str(sleepDataDict['restlessDuration'])
  213. print '15. minutesAfterWakeup: ' + str(sleepDataDict['minutesAfterWakeup'])
  214. print '16. awakeCount: ' + str(sleepDataDict['awakeCount'])
  215. print '17. minuteData: ' + str(sleepDataDict['minuteData'])
  216. print
  217. print 'Summary Names and Values by Direct Reference (3)'
  218. print '================================================'
  219. print '1. totalTimeInBed: ' + str(summaryDict['totalTimeInBed'])
  220. print '2. totalMinutesAsleep: ' + str(summaryDict['totalMinutesAsleep'])
  221. print '3. totalSleepRecords: ' + str(summaryDict['totalSleepRecords'])
  222.  
  223. # Diagnostic simply prints to screen demonstrating api
  224. def dumpSleepData(self,datetime):
  225. import fitbit
  226. authd_client = fitbit.Fitbit(ownerKey,ownerSecret,resource_owner_key=resourceOwnerKey,resource_owner_secret=resourceOwnerSecret)
  227. sleepUnitsDict = authd_client.get_sleep(datetime)
  228.  
  229. sleepList = sleepUnitsDict['sleep']
  230. summaryDict = sleepUnitsDict['summary']
  231.  
  232. print 'sleepList length: ',len(sleepList)
  233. print 'sleepList type:', type(sleepList)
  234. print 'summaryDict length: ',len(summaryDict)
  235. print 'summaryDict type ',type(summaryDict)
  236.  
  237. sleepDict = sleepList[0] #there only is one item in this list, a dictionary.
  238. print
  239. for key in sleepDict:
  240. print key + ':' + str(sleepDict[key])
  241. print
  242. for key in summaryDict:
  243. print key + ':' + str(summaryDict[key])
  244. print
  245.  
  246. #___________________________________________________________________________
  247. # Here we instantiate the class then invoke class methods
  248. ownerKey = '66febeae096fe9442d10dd3e92d54de2'
  249. ownerSecret = 'b8b002ddf50dd3525f57b9a350051b97'
  250. resourceOwnerKey = '20eb22828f652f729002ba0f855d07f3'
  251. resourceOwnerSecret = '48eaa2e1e11ea551d1e3579c3274cccd'
  252.  
  253. import datetime
  254. import console
  255. date = datetime.date(2015,7,9) # Change date here or set up a parameter.
  256.  
  257. # instantiate class then invoke some void methods (no return types)
  258. fitbitimpl = FitBitImpl(ownerKey,ownerSecret,resourceOwnerKey,resourceOwnerSecret)
  259. console.clear()
  260. #fitbitimpl.printAllSleepData(date)
  261. #fitbitimpl.sleepSummary(date)
  262. #fitbitimpl.testAllSleepKeyvalues(date)
  263. #fitbitimpl.dumpMinuteData(date)
  264. #fitbitimpl.dumpMinuteData(date)
  265. sleepValuesTotal = fitbitimpl.getSleepMinuteValuesTotals(date)
  266. print sleepValuesTotal
  267. #console.hide_output()
  268. #print 'Value 1 Total = ' + str(getSleepMinuteValuesTotals())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement