Private
Public Access
1
0

adding all new NK workouts

This commit is contained in:
Sander Roosendaal
2021-04-05 14:54:18 +02:00
parent f082d5f2b1
commit 84cefb31ab
4 changed files with 364 additions and 125 deletions

View File

@@ -53,6 +53,7 @@ from rowsandall_app.settings import PROGRESS_CACHE_SECRET
from rowsandall_app.settings import SETTINGS_NAME
from rowsandall_app.settings import workoutemailbox
from rowsandall_app.settings import UPLOAD_SERVICE_SECRET, UPLOAD_SERVICE_URL
from rowsandall_app.settings import NK_API_LOCATION
from requests_oauthlib import OAuth1, OAuth1Session
@@ -110,6 +111,8 @@ def safetimedelta(x):
siteurl = SITE_URL
from rowers.utils import get_nk_summary, get_nk_allstats, get_nk_intervalstats,getdict
# testing task
from rowers.emails import send_template_email
@@ -2952,6 +2955,149 @@ def handle_rp3_async_workout(userid,rp3token,rp3id,startdatetime,max_attempts,de
return workoutid
@app.task
def handle_nk_async_workout(alldata,userid,nktoken,nkid,delaysec,defaulttimezone,debug=False,**kwargs):
time.sleep(delaysec)
data = alldata[nkid]
params = {
'sessionIds': nkid,
}
authorizationstring = str('Bearer ' + nktoken)
headers = {'Authorization': authorizationstring,
'user-agent': 'sanderroosendaal',
'Content-Type': 'application/json',
}
# get strokes
url = NK_API_LOCATION+"api/v1/sessions/strokes"
response = requests.get(url,headers=headers,params=params)
if response.status_code != 200:
# error handling and logging
return 0
jsonData = response.json()
strokeData = jsonData[str(nkid)]
df = pd.DataFrame.from_dict(strokeData)
oarlockData = df['oarlockStrokes']
oarlockData = oarlockData.apply(lambda x:getdict(x, seatIndex=1))
df2 = pd.DataFrame.from_records(oarlockData.values)
df.set_index('timestamp')
if not df2.empty:
df2.set_index('timestamp')
df = df.merge(df2,left_index=True,right_index=True)
df = df.rename(columns={"timestamp_x":"timestamp"})
df = df.drop('oarlockStrokes',axis=1)
df.sort_values(by='timestamp',ascending=True,inplace=True)
df.fillna(inplace=True,method='ffill')
# get workout data
timestampbegin = df['timestamp'].min()
timestampend = df['timestamp'].max()
csvfilename = 'media/{code}_{nkid}.csv.gz'.format(
nkid=nkid,
code = uuid4().hex[:16]
)
df.to_csv(csvfilename, index_label='index', compression='gzip')
title = data["name"]
speedInput = data["speedInput"]
elapsedTime = data["elapsedTime"]
totalDistanceGps = data["totalDistanceGps"]
totalDistanceImp = data["totalDistanceImp"]
intervals = data["intervals"] # add intervals
oarlockSessions = data["oarlockSessions"]
deviceId = data["deviceId"] # you could get the firmware version
summary = get_nk_allstats(data,df)
# oarlock inboard, length, boat name
if oarlockSessions:
oarlocksession = oarlockSessions[0] # should take seatIndex
boatName = oarlocksession["boatName"]
oarLength = oarlocksession["oarLength"] # cm
oarInboardLength = oarlocksession["oarInboardLength"] # cm
seatNumber = oarlocksession["seatNumber"]
else:
boatName = ''
oarLength = 289
oarInboardLength = 88
seatNumber = 1
workouttype = "water"
boattype = "1x"
uploadoptions = {
'secret': UPLOAD_SERVICE_SECRET,
'user':userid,
'file': csvfilename,
'title': title,
'workouttype': workouttype,
'boattype': boattype,
'nkid':nkid,
'inboard': oarInboardLength/100.,
'oarlength': oarLength/100.,
'summary':summary,
}
session = requests.session()
newHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}
session.headers.update(newHeaders)
response = session.post(UPLOAD_SERVICE_URL,json=uploadoptions)
if response.status_code != 200:
return 0,response.text
try:
workoutid = response.json()['id']
except KeyError:
workoutid = 1
if debug:
engine = create_engine(database_url_debug, echo=False)
else:
engine = create_engine(database_url, echo=False)
query = 'SELECT uploadedtonk from rowers_workout WHERE id ={workoutid}'.format(workoutid=workoutid)
newnkid = 0
with engine.connect() as conn, conn.begin():
result = conn.execute(query)
tdata = result.fetchall()
if tdata:
newnkid = tdata[0][0]
conn.close()
parkedids = []
with open('nkblocked.json','r') as nkblocked:
jsondata = json.load(nkblocked)
parkedids = jsondata['ids']
newparkedids = [id for id in parkedids if id != newnkid]
with open('nkblocked.json','wt') as nkblocked:
tdata = {'ids':newparkedids}
nkblocked.seek(0)
json.dump(tdata,nkblocked)
# evt update workout summary
# return
return workoutid
@app.task
def handle_c2_async_workout(alldata,userid,c2token,c2id,delaysec,defaulttimezone,debug=False,**kwargs):
time.sleep(delaysec)