cyberjunky / home-assistant-google_fit

:hearts: This component tracks your Google Fit activities.
MIT License
99 stars 20 forks source link

Bug: getting the latest weight might not really get the latest weight #6

Open think-nice-things opened 3 years ago

think-nice-things commented 3 years ago

Hi,

I just observed a situation where not the latest weight is returned but the third but last point.

The latest 5 datapoints together with the relevant timestamps were (sorted from newest to older)

1. Entry
74.35
modifiedTimeMillis=1618809864359   # same timestamp as 2. and 3. Entry
startTimeNanos=1618805176000000000 # just a few secons newer than 2. Entry (was weighting two consecutive times)
endTimeNanos=1618805176000000000

2. Entry
74.35
modifiedTimeMillis=1618809864359   # same timestamp as 1. and 3. Entry
startTimeNanos=1618805151000000000 # just a few seconds older than 1. Entry
endTimeNanos=1618805151000000000

3. Entry
73.55
modifiedTimeMillis=1618809864359   # same timestamp as 2. and 3. Entry
startTimeNanos=1618766540000000000 # some hours older than 2. and 2. Entry
endTimeNanos=1618766540000000000

4. Entry
74.95
modifiedTimeMillis=1618733932941
startTimeNanos=1618733799000000000
endTimeNanos=1618733799000000000

5. Entry
75.1
modifiedTimeMillis=1618727511647
startTimeNanos=1618725662927000000
endTimeNanos=1618725662927000000

Apparently, the modifiedTimeMillis for the latest three data points (Entry 1, 2 and 3) are the same. I suspect that this is due to the fact that the weight was updated from a Mi Scale 2 from the mi app to google fit. I guess that the mi fit app only synchronizes the weights from time to time to google fit. My guess is that the latest data points were synchronized from the mi app to google fit at the same time.

What happend now is that the google_fit integration's GoogleFitWeightSensor.update() read Entry 1, 2 and 3 in this order and as modifiedTimeMillis is used as key for storing the values, only the third entry was stored in the dict (overwriting Entry 1 and 2 as their modifiedTimeMillis is the same)

Solution

Apparently the startTimeNanos and endTimeNanos are correct and different between these three latest entries. Therefore, to solve the problem GoogleFitWeightSensor.update() should rather use either startTimeNanos or endTimeNanos as key for storing the weight and later sorting.

somewhere around line 330 it should then

# OLD: last_update_milis = int(datapoint.get('modifiedTimeMillis', 0))
startTimeNanos = int(datapoint.get('startTimeNanos', 0))

I just confirmed that this works and yields then the correct latest entry.

Btw. I didn't check for other sensors but I believe that probably everywhere modifiedTimeMillis should be replace by startTimeNanos.