DEV Community

HarmonyOS
HarmonyOS

Posted on

Get heart rate with Sensor Kit and show on the watch with particle background

Read the original article:Get heart rate with Sensor Kit and show on the watch with particle background

Requirement Description

Get heart rate with the Sensor Kit, and show on the wearable watch screen with the particle animation background.

Background Knowledge

Sensor Service Kit enables applications to obtain raw data from sensors and provides vibration control capabilities.

Implementation Steps

1) Get permission from the user

2) Get heart rate with sensor

3) Create the UI. Add a particle background (optional) and show the heart rate on the screen in real time.

Code Snippet / Configuration

1) Get permission from the user

@Entry
@Component
export struct HeartRatePage {
  @State heartRate: number = 0;

  aboutToAppear() {
    this.requestHealthPermission(); // get permission when app open
  }
}

  // get permissions
  async requestHealthPermission() {
    const context = getContext(this);
    const atManager = abilityAccessCtrl.createAtManager();
    const permissions: Permissions[] = [
      'ohos.permission.READ_HEALTH_DATA',
      'ohos.permission.GET_NETWORK_INFO',
      'ohos.permission.INTERNET'
    ];

    try {
      const result = await atManager.requestPermissionsFromUser(context, permissions);
      console.info('Permissions granted: ' + JSON.stringify(result));
      if (result.authResults.every(r => r === 0)) {
        console.info('All permissions granted');
        this.subscribeHeartRateSensor();
      } else {
        console.error('One or more permission rejected.');
      }
    } catch (err) {
      console.error('Failed to get permission: ' + JSON.stringify(err));
    }
  }
Enter fullscreen mode Exit fullscreen mode

2) get heart rate with sensor

  // get heart rate sensor
  subscribeHeartRateSensor() {
    sensor.getSensorList((error: BusinessError, data: Array<sensor.Sensor>) => {
      if (error) {
        console.error('getSensorList error: ' + JSON.stringify(error));
        return;
      }

      const heartRateSensor = data.find(s => s.sensorName.toLowerCase().includes('heart'));
      if (!heartRateSensor) {
        console.error('Heart rate sensor cannot be found');
        return;
      }

      console.info('Heart rate sensor found ' + JSON.stringify(heartRateSensor));

      // Continuous data retrieval
      sensor.on(sensor.SensorId.HEART_RATE, (data: sensor.HeartRateResponse) => {
        if (data && data.heartRate !== undefined) {
          this.heartRate = data.heartRate;
          console.info("HeartRate: " + data.heartRate);
        }
      }, { interval: 100000000 }); // 100ms (nano)
    });
  }
Enter fullscreen mode Exit fullscreen mode

3) Create the UI. Add a particle background (optional) and show the heart rate on the screen in real time.

  build() {
    Column() {
      Stack() {
        Text()
          .width(300).height(300).backgroundColor(Color.Black)
        Particle({
          particles: [
            {
              emitter: {
                particle: {
                  type: ParticleType.POINT, // Particle type.
                  config: {
                    radius: 5 // Point radius.
                  },
                  count: 255, // Total number of particles.
                },
              },
              color: {
                range: [Color.White, Color.Red], // Initial color range.
              },
            },
          ]
        }).width(200).height(200)
      }.width("10%").height("10%").align(Alignment.Top)

      Image($r('app.media.heartrate')).width(50).height(50).margin({ bottom: 10 })
      Text("Heart Rate: " + this.heartRate + " bpm")
        .fontSize(18)
        .fontWeight(FontWeight.Bold)
        .fontColor(Color.White)
    }
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
    .width('100%')
    .height('100%')
    .backgroundColor(Color.Black)
  }
Enter fullscreen mode Exit fullscreen mode

Test Results

Tested on the Huawei Watch 5 device. It works as expected.

Output(it's from the previewer to show the result UI) - you need to test on a real device.

Limitations or Considerations

  • To obtain data from some sensors, you need to request the required permissions.
      {
        "name": "ohos.permission.READ_HEALTH_DATA",
        "reason": "$string:READ_HEALTH_DATA",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "inuse"
        }
      }
Enter fullscreen mode Exit fullscreen mode
  • To use sensor functions, ensure that the device where your application runs has the required sensor components.
  • Run this project on a real device.

Related Documents or Links

https://developer.huawei.com/consumer/en/doc/harmonyos-guides/sensor-guidelines

Written by Merve Yonetci

Top comments (0)