読者です 読者をやめる 読者になる 読者になる

しっぽを追いかけて

ぐるぐるしながら考えています

Unity と猫の話題が中心   掲載内容は個人の私見であり、所属組織の見解ではありません

Xamarin.Forms で Micorosft Band の歩数値を取得する

今回は Xamarin.Forms で歩数値を取得してみます

ソースコードの一式は下記にあります!

細かい実装などはこちらを参照ください

github.com

※ 順次改修していく予定なので、この記事の内容が現時点のソースより古い可能性があります

いつものようにセンサー系クラスを作ります

/// <summary>
/// iOS 用歩数センサー
/// </summary>
public class NativeBandPedometer : NativeBandSensorBase<IBandPedometerReading>
{
    /// <summary>
    /// 歩数センサー
    /// </summary>
    private Native.Sensors.PedometerSensor sensor = null;

    /// <summary>
    /// センサー値変更イベント
    /// </summary>
    public override event EventHandler<BandSensorReadingEventArgs<IBandPedometerReading>> ReadingChanged;

    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="manager">Band センサー管理クラス</param>
    public NativeBandPedometer(Native.Sensors.IBandSensorManager manager)
        : base(manager)
    {
        this.sensor = Native.Sensors.BandSensorManagerExtensions.CreatePedometerSensor(manager);
        this.sensor.ReadingChanged += this.OnReadingChanged;
    }

    /// <summary>
    /// センサー値変更イベントハンドラ
    /// </summary>
    /// <param name="sender">イベント発行者</param>
    /// <param name="e">イベント引数</param>
    protected void OnReadingChanged(object sender, Native.Sensors.BandSensorDataEventArgs<Native.Sensors.BandSensorPedometerData> e)
    {
        if (this.ReadingChanged == null)
        {
            return;
        }
        this.ReadingChanged.Invoke(
            this, new BandSensorReadingEventArgs<IBandPedometerReading>(new NativeBandPedometerReading(e.SensorReading)));
    }

    /// <summary>
    /// センサー検知を開始する
    /// </summary>
    /// <returns>Task</returns>
    public override Task StartReadingsAsync()
    {
        return Task.Run(() => this.sensor.StartReadings());
    }

    /// <summary>
    /// センサー検知を停止する
    /// </summary>
    /// <returns>Task</returns>
    public override Task StopReadingsAsync()
    {
        return Task.Run(() => this.sensor.StopReadings());
    }
}

こっちが iOS

/// <summary>
/// Android 用歩数データ
/// </summary>
public class NativeBandPedometer : NativeBandSensorBase<IBandPedometerReading>
{
    /// <summary>
    /// 歩数センサー
    /// </summary>
    private Native.Sensors.PedometerSensor sensor = null;

    /// <summary>
    /// センサー値変更イベント
    /// </summary>
    public override event EventHandler<BandSensorReadingEventArgs<IBandPedometerReading>> ReadingChanged;

    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="manager">Band センサー管理クラス</param>
    public NativeBandPedometer(Native.Sensors.IBandSensorManager manager)
        : base(manager)
    {
        this.sensor = Native.Sensors.BandSensorManagerExtensions.CreatePedometerSensor(manager);
        this.sensor.ReadingChanged += this.OnReadingChanged;
    }

    /// <summary>
    /// センサー値変更イベントハンドラ
    /// </summary>
    /// <param name="sender">イベント発行者</param>
    /// <param name="e">イベント引数</param>
    protected void OnReadingChanged(object sender, Native.Sensors.IBandSensorEventEventArgs<Native.Sensors.IBandPedometerEvent> e)
    {
        if (this.ReadingChanged == null)
        {
            return;
        }
        this.ReadingChanged.Invoke(
            this, new BandSensorReadingEventArgs<IBandPedometerReading>(new NativeBandPedometerReading(e.SensorReading)));
    }

    /// <summary>
    /// センサー検知を開始する
    /// </summary>
    /// <returns>Task</returns>
    public override Task StartReadingsAsync()
    {
        return this.sensor.StartReadingsTaskAsync();
    }

    /// <summary>
    /// センサー検知を停止する
    /// </summary>
    /// <returns>Task</returns>
    public override Task StopReadingsAsync()
    {
        return this.sensor.StopReadingsTaskAsync();
    }
}

そして Android

歩数のいれものはほぼ共通

/// <summary>
/// iOS 用歩数データ
/// </summary>
public class NativeBandPedometerReading : IBandPedometerReading
{
    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="data">センサーデータ</param>
    public NativeBandPedometerReading(Native.Sensors.BandSensorPedometerData data)
    {
        this.Timestamp = DateTime.Now;
        this.TotalSteps = (long) data.TotalSteps;
    }

    /// <summary>
    /// 検出日時
    /// </summary>
    public DateTimeOffset Timestamp { get; private set; }

    /// <summary>
    /// 歩数合計
    /// </summary>
    public long TotalSteps { get; private set; }
}

なぜか iOS の場合歩数合計以外に下記の値も取れるのですが、他のプラットフォームでは用意されないので泣く泣く未実装

  [Register("MSBSensorPedometerData", true)]
  public class BandSensorPedometerData : BandSensorData
  {
    public override IntPtr ClassHandle { get; } = Class.GetHandle("MSBSensorPedometerData");

    [CompilerGenerated]
    public virtual int MovementMode
    {
      [Export("movementMode")] get
      {
        if (this.IsDirectBinding)
          return ApiDefinition.Messaging.int_objc_msgSend(this.Handle, Selector.GetHandle("movementMode"));
        return ApiDefinition.Messaging.int_objc_msgSendSuper(this.SuperHandle, Selector.GetHandle("movementMode"));
      }
    }

    [CompilerGenerated]
    public virtual int MovementRate
    {
      [Export("movementRate")] get
      {
        if (this.IsDirectBinding)
          return ApiDefinition.Messaging.int_objc_msgSend(this.Handle, Selector.GetHandle("movementRate"));
        return ApiDefinition.Messaging.int_objc_msgSendSuper(this.SuperHandle, Selector.GetHandle("movementRate"));
      }
    }

    [CompilerGenerated]
    public virtual int StepRate
    {
      [Export("stepRate")] get
      {
        if (this.IsDirectBinding)
          return ApiDefinition.Messaging.int_objc_msgSend(this.Handle, Selector.GetHandle("stepRate"));
        return ApiDefinition.Messaging.int_objc_msgSendSuper(this.SuperHandle, Selector.GetHandle("stepRate"));
      }
    }

    [CompilerGenerated]
    public virtual int TotalMovements
    {
      [Export("totalMovements")] get
      {
        if (this.IsDirectBinding)
          return ApiDefinition.Messaging.int_objc_msgSend(this.Handle, Selector.GetHandle("totalMovements"));
        return ApiDefinition.Messaging.int_objc_msgSendSuper(this.SuperHandle, Selector.GetHandle("totalMovements"));
      }
    }

    [CompilerGenerated]
    public virtual int TotalSteps
    {
      [Export("totalSteps")] get
      {
        if (this.IsDirectBinding)
          return ApiDefinition.Messaging.int_objc_msgSend(this.Handle, Selector.GetHandle("totalSteps"));
        return ApiDefinition.Messaging.int_objc_msgSendSuper(this.SuperHandle, Selector.GetHandle("totalSteps"));
      }
    }
  }

そして ViewModel

/// <summary>
/// センサー情報 ViewModel
/// </summary>
public class SensorReadingViewModel : BindableBase
{
    ~ 中略 ~

    #region Pedometer

    /// <summary>
    /// 歩数合計
    /// </summary>
    private long totalSteps = 0;

    /// <summary>
    /// 歩数合計
    /// </summary>
    public long TotalSteps
    {
        get { return this.totalSteps; }
        set { this.SetProperty<long>(ref this.totalSteps, value); }
    }

    #endregion //Pedometer

    ~ 中略 ~

    /// <summary>
    /// センサー監視切替
    /// </summary>
    /// <param name="detecting">センサー監視フラグ</param>
    /// <returns>Task</returns>
    private async Task ChangeDetectSensors(bool detecting)
    {
        if (detecting)
        {
            // 加速度センサーの検知開始
            if (this.client.SensorManager.Accelerometer.IsSupported)
            {
                await this.client.SensorManager.Accelerometer.StartReadingsAsync();
                this.client.SensorManager.Accelerometer.ReadingChanged += this.OnAccelerometerReadingChanged;
            }
            // ジャイロセンサーの検知開始
            if (this.client.SensorManager.Gyroscope.IsSupported)
            {
                await this.client.SensorManager.Gyroscope.StartReadingsAsync();
                this.client.SensorManager.Gyroscope.ReadingChanged += this.OnGyroscopeReadingChanged;
            }
            // 心拍数の検知開始
            if (this.client.SensorManager.HeartRate.IsSupported)
            {
                await this.client.SensorManager.HeartRate.StartReadingsAsync();
                this.client.SensorManager.HeartRate.ReadingChanged += this.OnHeartRateReadingChanged;
            }
            // 歩数の検知開始
            if (this.client.SensorManager.Pedometer.IsSupported)
            {
                await this.client.SensorManager.Pedometer.StartReadingsAsync();
                this.client.SensorManager.Pedometer.ReadingChanged += this.OnPedometerReadingChanged;
            }
        }
        else
        {
            // 加速度センサーの検知終了
            if (this.client.SensorManager.Accelerometer.IsSupported)
            {
                await this.client.SensorManager.Accelerometer.StopReadingsAsync();
                this.client.SensorManager.Accelerometer.ReadingChanged -= this.OnAccelerometerReadingChanged;
                this.AccelerationX = 0d;
                this.AccelerationY = 0d;
                this.AccelerationZ = 0d;
            }
            // ジャイロセンサーの検知終了
            if (this.client.SensorManager.Gyroscope.IsSupported)
            {
                await this.client.SensorManager.Gyroscope.StopReadingsAsync();
                this.client.SensorManager.Gyroscope.ReadingChanged -= this.OnGyroscopeReadingChanged;
                this.AngularVelocityX = 0d;
                this.AngularVelocityY = 0d;
                this.AngularVelocityZ = 0d;
                this.GyroAccelerationX = 0d;
                this.GyroAccelerationY = 0d;
                this.GyroAccelerationZ = 0d;
            }
            // 心拍数の検知終了
            if (this.client.SensorManager.HeartRate.IsSupported)
            {
                await this.client.SensorManager.HeartRate.StopReadingsAsync();
                this.client.SensorManager.HeartRate.ReadingChanged -= this.OnHeartRateReadingChanged;
                this.HeartRate = 0;
                this.HeartRateQuality = HeartRateQuality.Acquiring;
            }
            // 歩数の検知終了
            if (this.client.SensorManager.Pedometer.IsSupported)
            {
                await this.client.SensorManager.Pedometer.StopReadingsAsync();
                this.client.SensorManager.Pedometer.ReadingChanged -= this.OnPedometerReadingChanged;
                this.TotalSteps = 0L;
            }
        }
    }

    ~ 中略 ~

    /// <summary>
    /// 歩数変更イベントハンドラ
    /// </summary>
    /// <param name="sender">イベント発行者</param>
    /// <param name="e">イベント引数</param>
    private void OnPedometerReadingChanged(object sender, BandSensorReadingEventArgs<IBandPedometerReading> e)
    {
        if (e == null)
        {
            return;
        }
        this.TotalSteps = e.SensorReading.TotalSteps;
    }
}

監視対象が増えてきましたが今までとやることはほぼ変わってません

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:cv="clr-namespace:XamarinBandSample.Converters;assembly=XamarinBandSample"
             xmlns:t="clr-namespace:XamarinBandSample.Triggers;assembly=XamarinBandSample"
             xmlns:prismmvvm="clr-namespace:Prism.Mvvm;assembly=XamarinBandSample"
             prismmvvm:ViewModelLocator.AutoWireViewModel="true"
             x:Class="XamarinBandSample.Views.TopPage">

    ~ 中略 ~

    <!-- Sensor Info Pain-->
    <ScrollView IsVisible="{Binding ShowSensors}"
                Orientation="Vertical">
      <Grid Padding="10"
            RowSpacing="10"
            ColumnSpacing="10"
            BindingContext="{Binding SensorReading}">
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto"/>
          <RowDefinition Height="Auto"/>
          <RowDefinition Height="Auto"/>
          <RowDefinition Height="Auto"/>
          <RowDefinition Height="Auto"/>
          <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="100"/>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

    ~ 中略 ~

        <StackLayout Orientation="Horizontal"
                     Grid.Column="0"
                     Grid.ColumnSpan="2"
                     Grid.Row="4"
                     Spacing="5">

          <Label Text="Pedometer:"
                 FontSize="Medium"/>
          <StackLayout Orientation="Vertical"
                       Padding="10,0,0,0"
                       Spacing="10">
            <Label Text="{Binding TotalSteps, StringFormat='steps={0}'}"
                   FontSize="Small"/>
          </StackLayout>

        </StackLayout>

      </Grid>
    </ScrollView>
  </Grid>

</ContentPage>

表示領域を追加してお試し実行

f:id:matatabi_ux:20150425203055p:plain

合計歩数なので結構な数字・・・アプリ側で時間ごとに管理しないと使いづらい数値かもしれないですね