Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Toybox.Lang;
- import Toybox.WatchUi;
- import Toybox.Activity;
- // implements a rolling average for numerical values
- class RollingAverage {
- // circular "queue" for rolling average data
- // (it's actually a simplified queue which is sufficient for our purposes)
- private var _data as Array<Numeric?>;
- private var _startIndex as Number = 0; // current start index of the queue
- private var _maxSize as Number; // max size of queue
- private var _currentSize as Number = 0; // current size of queue
- function initialize(windowSize as Number) {
- _maxSize = windowSize;
- _data = new Array<Numeric>[_maxSize];
- }
- public function reset() {
- _data = new Array<Numeric>[_maxSize];
- _currentSize = 0;
- _startIndex = 0;
- }
- public function addValue(value as Numeric) {
- var currentIndex = (_startIndex + _currentSize) % _maxSize;
- _data[currentIndex] = value;
- if (_currentSize < _maxSize) {
- _currentSize++;
- } else {
- _startIndex = (_startIndex + 1) % _maxSize;
- }
- }
- // Get the rolling average for the current data set.
- // If the data set is not full, return null
- public function getAverage() as Float? {
- if (_currentSize < _maxSize) {
- return null;
- }
- var total = 0;
- for (var i = 0; i < _maxSize; i++) {
- total += _data[i];
- }
- return total.toFloat() / _maxSize;
- }
- }
- class MyDataFieldView extends WatchUi.DataField {
- // ...
- var _power3s = new RollingAverage(3);
- // ...
- function compute(info as Activity.Info) as Void {
- // ...
- if (info has :currentPower) {
- var power = info.currentPower;
- if (power == null) {
- _power3s.reset();
- } else {
- _power3s.addValue(power);
- }
- System.println("3s power = " + _power3s.getAverage());
- }
- // ...
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment