Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Toybox.Lang;
- import Toybox.WatchUi;
- import Toybox.Activity;
- import Toybox.Graphics;
- // implements a rolling average for numerical values
- class RollingAverage {
- // options for calculating rolling average
- const RESET_ROLLING_AVERAGE_ON_NULL_VALUE = true;
- const RETURN_NULL_WHEN_ROLLING_AVERAGE_HAS_INCOMPLETE_DATA = true;
- // circular "queue" for rolling average data
- 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() {
- _currentSize = 0;
- _startIndex = 0;
- }
- public function addValue(value as Numeric?) {
- if (value == null) {
- if (RESET_ROLLING_AVERAGE_ON_NULL_VALUE) {
- reset();
- }
- return;
- }
- 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 == 0) {
- return null;
- }
- if (RETURN_NULL_WHEN_ROLLING_AVERAGE_HAS_INCOMPLETE_DATA && _currentSize < _maxSize) {
- return null;
- }
- var total = 0;
- for (var i = 0; i < _currentSize; i++) {
- total += _data[i];
- }
- return total.toFloat() / _currentSize;
- }
- }
- class MyDataFieldView extends WatchUi.DataField {
- // ...
- var _power3s as RollingAverage = new RollingAverage(3); // member variable
- var _power3sAverage as Float?; // member variable
- // ...
- function initialize() {
- DataField.initialize();
- // ...
- }
- function compute(info as Activity.Info) as Void {
- // ...
- if (info has :currentPower) {
- var power = info.currentPower;
- _power3s.addValue(power);
- _power3sAverage = _power3s.getAverage();
- System.println("3s power = " + _power3sAverage);
- }
- // ...
- }
- function onUpdate(dc as Dc) as Void {
- // ...
- if (_power3sAverage != null) {
- var power3sAverageFormatted = _power3sAverage.format("%.2f"); // format with 2 decimal places - e.g. "123.45"
- // draw _power3sAverage on the screen
- dc.drawText(x, y, Graphics.FONT_LARGE, power3sAverageFormatted, Graphics.TEXT_JUSTIFY_CENTER | Graphics.TEXT_JUSTIFY_VCENTER);
- } else {
- // draw "--" on the screen
- dc.drawText(x, y, Graphics.FONT_LARGE, "--", Graphics.TEXT_JUSTIFY_CENTER | Graphics.TEXT_JUSTIFY_VCENTER);
- }
- // ...
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement