Last active
July 13, 2018 16:37
-
-
Save laurivaltteri/adcdd88618270f8afcdb to your computer and use it in GitHub Desktop.
Beddit cloudapi data wrapper to .csv-file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## python snippet to extract some elements from BEDDIT couldapi json struct | |
## and save them to .csv-file | |
## USAGE: beddit_cloud_to_csv.py <number_of_days_included> | |
## number of days defaults to seven | |
## CC laurivaltteri | |
import sys, os | |
import requests, csv | |
from datetime import date, timedelta, datetime | |
apiurl = "https://cloudapi.beddit.com/" | |
outpath = <PATH TO FOR EXAMPLE MY PHYSIODATA FOLDER> | |
def main(argv): | |
if len(argv) >= 1: | |
daycount = int(argv[0]) | |
else: | |
daycount = 7 | |
url = apiurl+"api/v1/auth/authorize" | |
loginops = {'username': <USERNAME HERE>, 'password': <PASSWORD HERE>, 'grant_type' :'password'} | |
r = requests.post(url, data=loginops) | |
user_token = r.json()['access_token'] | |
url = apiurl+"api/v1/auth/token_info" | |
authent = {'Authorization': 'UserToken '+str(user_token)} | |
r = requests.get(url,headers=authent) | |
user_id = r.json()['user'] | |
url = apiurl+"api/v1/user/"+str(user_id)+"/sleep" | |
# get dates | |
lastdate = str(date.today() - timedelta(days=daycount)) | |
nowdate = str(date.today()) | |
dateops = {'start_date': lastdate, 'end_date': nowdate} | |
sleepdata = requests.get(url, headers=authent, params=dateops) | |
sleeparse = sleepdata.json() | |
# comprehensible names for collected variables # 'time_arrived_to_bed','time_to_leave_bed', <-not properties but included | |
headdata = ['sleep_time','sleep_latency','resting_HR','short_HR','all_night_HRV_index','evening_HRV_index','morning_HRV_index'] | |
# beddit struct names for corresponding variables # 'to_bed_time','from_bed_time', | |
bedheads = ['stage_duration_S','sleep_latency','resting_heart_rate','short_term_resting_heart_rate','all_night_HRV_index','evening_HRV_index','morning_HRV_index'] | |
# init new list of dictionaries | |
beddata = [] | |
# write list of dictionaries with selected variables | |
for dailymeas in sleeparse: | |
beddict = {} | |
if len(dailymeas['time_value_tracks']['presence']['items']) != 0: | |
beddict['to_bed_time'] = datetime.fromtimestamp(dailymeas['time_value_tracks']['presence']['items'][0][0]).strftime('%Y%m%dT%H%M%S') | |
beddict['from_bed_time'] = datetime.fromtimestamp(dailymeas['time_value_tracks']['presence']['items'][-1][0]).strftime('%Y%m%dT%H%M%S') | |
else: | |
beddict['to_bed_time'] = 'NA' | |
beddict['from_bed_time'] = 'NA' | |
for bedditem in bedheads: | |
if bedditem in dailymeas['properties'].keys(): | |
beddict[bedditem] = dailymeas['properties'][bedditem] | |
else: | |
beddict[bedditem] = 'NA' | |
beddata.append(beddict) | |
# initiate and write csv file | |
os.chdir(outpath) | |
fname = "%s_sleepdata.csv" % str(date.today()) | |
with open(fname,"wb") as csvf: | |
spamwriter = csv.DictWriter(csvf, bedheads,delimiter=';') | |
# order header line | |
bedheads = ['to_bed_time','from_bed_time','stage_duration_S','sleep_latency','resting_heart_rate','short_term_resting_heart_rate','all_night_HRV_index','evening_HRV_index','morning_HRV_index'] | |
# write header line | |
spamwriter.writeheader() | |
for dailymeas in beddata: | |
spamwriter.writerow(dailymeas) | |
if __name__=='__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment