Fitbit+Python(3)

睡眠・歩数・RHR・HRVデータの処理
 1週間、1ヶ月といった単位で、行動・生理指標の変化を追う場合は、睡眠・歩数・RHR(安静時心拍)・HRV(心拍変動)データの日単位の取得が必要になります。

睡眠データの取得
 ClientIDとClientSecretを用いて,過去4日分の睡眠データを取得し,csv形式で保存する。40~46行目の関数は,それぞれ「総睡眠時間,目覚め後の時間,入眠時間,覚醒時間,寝返りの回数,寝返り時間,睡眠効率」の7つを取得している。

「合計睡眠時間=Awake(起きている時間)+MainLen(寝ている時間)」
"""
getSleepSmple.py
ClientIDとClientSecretで、Sleep関連データを取得するプログラム
"""
import sys
import fitbit
import pandas as pd
import gather_keys_oauth2 as Oauth2
from datetime import datetime, date, timedelta
     
print('Hello FitbitSleepAPP1') 
   
USER_ID     = "hoge"
CLIENT_SECRET = "hoge"
     
def requestFitbit(DATE):
    rval=""
    global auth2_client
    
    #fitbit_stats = auth2_client.intraday_time_series('activities/minutesSedentary', DATE, detail_level='1min')
    #HRstats = fitbit_stats['activities-minutesSedentary-intraday']['dataset']
       
    sleep_data = auth2_client.sleep(date=DATE)    
    #print(DATE+"睡眠データ取得実行しました") 
   
    OUTPUT_FILE = "SLEEP.csv"
    csv_file = open(OUTPUT_FILE, 'a')
    csv_file.write(DATE+",")
   
    sleepcnt=len(sleep_data["sleep"])
    #print(str(sleepcnt)+"回眠っています") 
   
    totallength=0;
    TAfter=0;
    TFall=0;
    TAwake=0;
    TLessCnt=0;
    TLessDur=0;
    TEffi=0;
    for var in range(0, sleepcnt):
        #print("睡眠:"+str(var)) 
        totallength+=sleep_data["sleep"][var]["minutesAsleep"] #総睡眠時間
        TAfter+=sleep_data["sleep"][var]["minutesAfterWakeup"]
        TFall+=sleep_data["sleep"][var]["minutesToFallAsleep"]
        TAwake+=sleep_data["sleep"][var]["minutesAwake"]
        TLessCnt+=sleep_data["sleep"][var]["restlessCount"]
        TLessDur+=sleep_data["sleep"][var]["restlessDuration"]
        TEffi+=sleep_data["sleep"][var]["efficiency"]
          
    AvgEffi=1
    if sleepcnt!=0:
        AvgEffi=TEffi/sleepcnt;    
      
    print(str(sleepcnt)+"回の睡眠で総睡眠時間は"+str(totallength)+"分です") 
    csv_file.write(str(totallength)+","+str(sleepcnt)+","+str(TAfter)+","+str(TFall)+","+str(TAwake)+","+str(TLessCnt)+","+str(TLessDur)+","+str(AvgEffi)+",")
   
    for var in range(0, sleepcnt):
        if sleep_data["sleep"][var]["isMainSleep"] == True:
            csv_file.write(sleep_data["sleep"][var]["startTime"]+","+str(sleep_data["sleep"][var]["minutesAsleep"])+","+str(sleep_data["sleep"][var]["efficiency"]))
   
    csv_file.write("\n")
    csv_file.close()
       
    return rval
##################################################
    
def writeindex():   
    OUTPUT_FILE = "SLEEP.csv"
    csv_file = open(OUTPUT_FILE, 'a')
                     
    csv_file.write("date,totallength,count,AfterWakeup,FallAsleep,Awake,restlessCount,restlessDur,AvgEffic,MainStart,MainLen,MainEffic\n")
    csv_file.close()
##################################################
    
"""Get tokens"""
server = Oauth2.OAuth2Server(USER_ID, CLIENT_SECRET)
server.browser_authorize()
ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
     
print(ACCESS_TOKEN)  
print(REFRESH_TOKEN)
    
"""Authorization"""
auth2_client = fitbit.Fitbit(USER_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
     
"""request"""
#requestFitbit("2022-02-22")
writeindex();   #インデックス記入
today = datetime.today()
for var in range(0,4):
    #day=today + timedelta(days=1)
    #print(var+":" + datetime.strftime(yesterday, '%Y-%m-%d'))
    stamp=datetime.strftime(today - timedelta(days=var), '%Y-%m-%d')
    print("target: " + stamp, end=' ')
    requestFitbit(stamp)

歩数データの取得
1日あたりの歩数を取得する

"""
getStepSample.py
個人の1日の歩数データを取得するプログラム
"""
import sys
import fitbit
import gather_keys_oauth2 as Oauth2
from datetime import datetime, timedelta
import json
 
print('Hello FitbitDailyStepsAPP')
 
USER_ID = "hoge"
CLIENT_SECRET = "hoge"
 
def requestFitbit(DATE):
    global auth2_client
 
    # APIエンドポイントを使用して1日の歩数データを取得
    steps_data = auth2_client.make_request(f'https://api.fitbit.com/1/user/-/activities/steps/date/{DATE}/1d.json')
 
    OUTPUT_FILE = "Steps.csv"
    with open(OUTPUT_FILE, 'a') as csv_file:
        csv_file.write(f"{DATE},")
        if "activities-steps" in steps_data and len(steps_data["activities-steps"]) > 0:
            steps_info = steps_data["activities-steps"][0]  # リストの最初の要素を取得
            csv_file.write(f"{steps_info['value']}\n")
        else:
            csv_file.write("No steps data\n")
 
def writeindex():
    OUTPUT_FILE = "Steps.csv"
    with open(OUTPUT_FILE, 'w') as csv_file:
        csv_file.write("date,steps\n")
 
# トークンの取得
server = Oauth2.OAuth2Server(USER_ID, CLIENT_SECRET)
server.browser_authorize()
ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
 
print("AT:"+ACCESS_TOKEN)
print("RT:"+REFRESH_TOKEN)
 
# 認証
auth2_client = fitbit.Fitbit(USER_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
 
# インデックスの書き込み
writeindex()
 
# 1日の歩数データのリクエスト
today = datetime.today()
for var in range(0, 7):
    stamp = datetime.strftime(today - timedelta(days=var), '%Y-%m-%d')
    print(f"target: {stamp}", end=' ')
    requestFitbit(stamp)

RHR(安静時心拍数)の取得
RHRはその日の安静時の心拍数の評価値

"""
getRHRsample.py
個人のHRVデータを取得するプログラム
"""import sys
import fitbit
import gather_keys_oauth2 as Oauth2
from datetime import datetime, timedelta
import json

print('Hello FitbitRHRAPP')

USER_ID = "hoge"
CLIENT_SECRET = "hoge"

def requestFitbitRHR(DATE, ID):
    global auth2_client

    # APIエンドポイントを使用して安静時心拍数データを取得
    heart_data = auth2_client.make_request(f'https://api.fitbit.com/1/user/-/activities/heart/date/{DATE}/1d.json')

    OUTPUT_FILE = ID + "_RHR.csv"

    with open(OUTPUT_FILE, 'a') as csv_file:
        csv_file.write(f"{DATE},")
        if "activities-heart" in heart_data and len(heart_data["activities-heart"]) > 0:
            heart_info = heart_data["activities-heart"][0]['value']
            if 'restingHeartRate' in heart_info:
                rhr = heart_info['restingHeartRate']
                csv_file.write(f"{rhr}\n")
            else:
                csv_file.write("No resting heart rate data\n")
        else:
            csv_file.write("No heart rate data\n")

def writeindex(ID):
    OUTPUT_FILE = ID + "_RHR.csv"
    with open(OUTPUT_FILE, 'w') as csv_file:
        csv_file.write("date,restingHeartRate\n")

# トークンの取得
server = Oauth2.OAuth2Server(USER_ID, CLIENT_SECRET)
server.browser_authorize()
ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])

print(ACCESS_TOKEN)
print(REFRESH_TOKEN)

# 認証
auth2_client = fitbit.Fitbit(USER_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

# インデックスの書き込み
writeindex(USER_ID)

# 安静時心拍数データのリクエスト
today = datetime.today()
for var in range(0, 7):
    stamp = datetime.strftime(today - timedelta(days=var), '%Y-%m-%d')
    print(f"target: {stamp}", end=' ')
    requestFitbitRHR(stamp, USER_ID)

HRV(心拍変動)データの取得
HRVは睡眠時のものとなるため、1日あたり一つ。評価値はrMSSDを示し単位はms。

"""
getHRVsample.py
個人のHRVデータを取得するプログラム
"""
import sys
import fitbit
import gather_keys_oauth2 as Oauth2
from datetime import datetime, timedelta
import json
 
print('Hello FitbitHRVAPP')
 
USER_ID = "hoge"
CLIENT_SECRET = "hoge"
 
def requestFitbit(DATE):
    global auth2_client
 
    # APIエンドポイントを使用してHRVデータを取得
    hrv_data = auth2_client.make_request(f'https://api.fitbit.com/1/user/-/hrv/date/{DATE}.json')
 
    OUTPUT_FILE = "HRV.csv"
    with open(OUTPUT_FILE, 'a') as csv_file:
        csv_file.write(f"{DATE},")
        if "hrv" in hrv_data and len(hrv_data["hrv"]) > 0:
            hrv_info = hrv_data["hrv"][0]  # リストの最初の要素を取得
            csv_file.write(f"{hrv_info['value']['dailyRmssd']},{hrv_info['value']['deepRmssd']}\n")
        else:
            csv_file.write("No HRV data\n")
 
def writeindex():
    OUTPUT_FILE = "HRV.csv"
    with open(OUTPUT_FILE, 'w') as csv_file:
        csv_file.write("date,dailyRmssd,deepRmssd\n")
 
# トークンの取得
server = Oauth2.OAuth2Server(USER_ID, CLIENT_SECRET)
server.browser_authorize()
ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
 
print(ACCESS_TOKEN)
print(REFRESH_TOKEN)
 
# 認証
auth2_client = fitbit.Fitbit(USER_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
 
# インデックスの書き込み
writeindex()
 
# HRVデータのリクエスト
today = datetime.today()
for var in range(0, 4):
    stamp = datetime.strftime(today - timedelta(days=var), '%Y-%m-%d')
    print(f"target: {stamp}", end=' ')
    requestFitbit(stamp)

コメントを残す