import Toybox.Lang; import Toybox.Sensor; import Toybox.UserProfile; // Wraps the heart-rate sensor and maps the current bpm to a zone (1..5). // Returns null bpm when no reading is available (e.g. simulator without data // simulation), so the view can show a placeholder. class HeartRateProvider { private var _hr as Number?; private var _zones as Array?; public function initialize() { _hr = null; _zones = null; } public function onStart() as Void { Sensor.setEnabledSensors([Sensor.SENSOR_HEARTRATE]); Sensor.enableSensorEvents(method(:onSensor)); _zones = UserProfile.getHeartRateZones(UserProfile.HR_ZONE_SPORT_GENERIC); } public function onStop() as Void { Sensor.enableSensorEvents(null); } public function onSensor(info as Sensor.Info) as Void { _hr = info.heartRate; } public function getHeartRate() as Number? { return _hr; } // Returns 1..5, or 0 if HR/zones unavailable. public function getZone() as Number { if (_hr == null || _zones == null) { return 0; } var z = _zones as Array; var hr = _hr as Number; // _zones holds 6 boundaries: [z1lo, z2lo, z3lo, z4lo, z5lo, max] for (var i = z.size() - 2; i >= 0; i -= 1) { if (hr >= z[i]) { return i + 1 > 5 ? 5 : i + 1; } } return 1; } }