Advertisement
Guest User

Untitled

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