Weighted circular average for wind direction computation

I have a weather station that reports the wind direction and speed on a regular basis via publishing to MQTT topic that openHAB is subscribed to.
This works just fine, I have one channel for each value and items linked to them allow me to see the persisted values.

Getting the average speed over a given period of time is easily done with the Javascript persistence extension method averageBetween as described here.
And if I’m not mistaken, it’s already a time-weighted average which is fine by me as the speed does not change every time a report is sent by the weather station.

Now, I’d like to be able to get a mean wind direction over a given period of time, but I’m quite sure averageBetween does not compute a circular mean as it would need to know the stored values are angles.
And even if it did, it wouldn’t give me a mean weighted both by time and wind speed, as it’s quite important that the higher wind speed get the most impact on the wind direction mean over a given period of time.

Looking at the ItemHistory class, I see that I can get all recorded steps for a given period via the getAllStatesBetween method.
But this gives me the exact recorded elements, without any synchronization between two items.
Here is an example

Time Wind speed (km/h) Wind direction (°)
00:00 50
00:01 12 10
00:10 21 8
00:12 2
00:20 170
00:30 25
00:42 350
01:01 1

Blanks in that table are when there is no data given in the returned HistoricItem array.
This is where I’m struggling a bit with how to reconstruct the history so that I always have the two values for any given time.

I thought about repeatedly calling historicState with regular time intervals in the past, but it’s quite slow and does not seem very effecient when I could get all values at once and compute elements along the way.

I looked here and could not find any similar discussion with a solution.

Any suggestion is most welcome.

Maybe instead of everychange/everyupdate, do a cron based persistence for both wind speed and direction?

Or alternatively, don’t automatically persist wind direction, but create a rule on every update of wind speed, also persist wind direction.

A third way is to use whatever the last wind direction that was last persisted. This can be done in your loop after getting allStates instead of repeatedly calling historicState.

Ah, I see, having a cron based persistence, I would always get both values at the same time, regardless of whether changes happened. And then it’s much easier as I would be sure to have both values for the same timestamp.

Well, of course, this leaves the manual circular mean computation but it removes one part of the complexity.

Thanks for the hint, I’ll see what I can come up with