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

しっぽを追いかけて

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

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

Xamarin.Forms で Micorosft Band の紫外線レベル値を取得する

Android C# Windows ランタイムアプリ Xamarin XAML ウェアラブル

今回は Xamarin.Forms で紫外線量のレベルを取得してみます

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

github.com

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

いつものようにまずはデータのいれものを作ります

/// <summary>
/// iOS 用紫外線データ
/// </summary>
public class NativeBandUltravioletLightReading : IBandUltravioletLightReading
{
    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="data">センサーデータ</param>
    public NativeBandUltravioletLightReading(Native.Sensors.BandSensorUVData data)
    {
        this.Timestamp = DateTime.Now;
        this.ExposureLevel = UltravioletExposureLevel.None;
        if (data.UVIndexLevel == Native.Sensors.UVIndexLevel.High)
        {
            this.ExposureLevel = UltravioletExposureLevel.High;
        }
        if (data.UVIndexLevel == Native.Sensors.UVIndexLevel.Medium)
        {
            this.ExposureLevel = UltravioletExposureLevel.Medium;
        }
        if (data.UVIndexLevel == Native.Sensors.UVIndexLevel.Low)
        {
            this.ExposureLevel = UltravioletExposureLevel.Low;
        }
    }

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

    /// <summary>
    /// 紫外線レベル
    /// </summary>
    public UltravioletExposureLevel ExposureLevel { get; private set; }
}

iOSAndroid でほぼ同じです・・・列挙型の受け渡しが少し面倒;

次にセンサー制御クラス

/// <summary>
/// iOS 用紫外線センサー
/// </summary>
public class NativeBandUltravioletLightSensor : NativeBandSensorBase<IBandUltravioletLightReading>
{
    /// <summary>
    /// 紫外線センサー
    /// </summary>
    private Native.Sensors.UVSensor sensor = null;

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

    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="manager">Band センサー管理クラス</param>
    public NativeBandUltravioletLightSensor(Native.Sensors.IBandSensorManager manager)
        : base(manager)
    {
        this.sensor = Native.Sensors.BandSensorManagerExtensions.CreateUVSensor(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.BandSensorUVData> e)
    {
        if (this.ReadingChanged == null)
        {
            return;
        }
        this.ReadingChanged.Invoke(
            this, new BandSensorReadingEventArgs<IBandUltravioletLightReading>(new NativeBandUltravioletLightReading(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 NativeBandUltravioletLightSensor : NativeBandSensorBase<IBandUltravioletLightReading>
{
    /// <summary>
    /// 紫外線センサー
    /// </summary>
    private Native.Sensors.UVSensor sensor = null;

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

    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="manager">Band センサー管理クラス</param>
    public NativeBandUltravioletLightSensor(Native.Sensors.IBandSensorManager manager)
        : base(manager)
    {
        this.sensor = Native.Sensors.BandSensorManagerExtensions.CreateUVSensor(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.IBandUVEvent> e)
    {
        if (this.ReadingChanged == null)
        {
            return;
        }
        this.ReadingChanged.Invoke(
            this, new BandSensorReadingEventArgs<IBandUltravioletLightReading>(new NativeBandUltravioletLightReading(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 ・・・T4 にした方がよかったですかね

ViewModel も改修

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

    #region UVSensor

    /// <summary>
    /// 紫外線レベル
    /// </summary>
    private UltravioletExposureLevel exposureLevel = 0;

    /// <summary>
    /// 紫外線レベル
    /// </summary>
    public UltravioletExposureLevel ExposureLevel
    {
        get { return this.exposureLevel; }
        set { this.SetProperty<UltravioletExposureLevel>(ref this.exposureLevel, value); }
    }

    #endregion //UVSensor

    ~ 中略 ~

    /// <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;
            }
            // 移動距離の検知開始
            if (this.client.SensorManager.Distance.IsSupported)
            {
                await this.client.SensorManager.Distance.StartReadingsAsync();
                this.client.SensorManager.Distance.ReadingChanged += this.OnDistanceReadingChanged;
            }
            // 肌温度の検知開始
            if (this.client.SensorManager.SkinTemperature.IsSupported)
            {
                await this.client.SensorManager.SkinTemperature.StartReadingsAsync();
                this.client.SensorManager.SkinTemperature.ReadingChanged += this.OnSkinTemperatureReadingChanged;
            }
            // 紫外線レベルの検知開始
            if (this.client.SensorManager.Ultraviolet.IsSupported)
            {
                await this.client.SensorManager.Ultraviolet.StartReadingsAsync();
                this.client.SensorManager.Ultraviolet.ReadingChanged += this.OnUltravioletReadingChanged;
            }
        }
        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;
            }
            // 移動距離の検知終了
            if (this.client.SensorManager.Distance.IsSupported)
            {
                await this.client.SensorManager.Distance.StopReadingsAsync();
                this.client.SensorManager.Distance.ReadingChanged -= this.OnDistanceReadingChanged;
                this.CurrentMotion = MotionType.Unknown;
                this.Pace = 0d;
                this.Speed = 0d;
                this.TotalDistance = 0L;
            }
            // 肌温度の検知開始
            if (this.client.SensorManager.SkinTemperature.IsSupported)
            {
                await this.client.SensorManager.SkinTemperature.StopReadingsAsync();
                this.client.SensorManager.SkinTemperature.ReadingChanged -= this.OnSkinTemperatureReadingChanged;
                this.SkinTemperature = 0d;
            }
            // 紫外線レベルの検知終了
            if (this.client.SensorManager.Ultraviolet.IsSupported)
            {
                await this.client.SensorManager.Ultraviolet.StopReadingsAsync();
                this.client.SensorManager.Ultraviolet.ReadingChanged -= this.OnUltravioletReadingChanged;
                this.ExposureLevel = UltravioletExposureLevel.None;
            }
        }
    }

    ~ 中略 ~

    /// <summary>
    /// 紫外線レベル変更イベントハンドラ
    /// </summary>
    /// <param name="sender">イベント発行者</param>
    /// <param name="e">イベント引数</param>
    private void OnUltravioletReadingChanged(object sender, BandSensorReadingEventArgs<IBandUltravioletLightReading> e)
    {
        if (e == null)
        {
            return;
        }
        this.ExposureLevel = e.SensorReading.ExposureLevel;
    }
}

最後に XAML

<?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="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="7"
                     Spacing="5">

          <Label Text="UV Level:"
                 FontSize="Medium"/>
          <StackLayout Orientation="Vertical"
                       Padding="10,0,0,0"
                       Spacing="10">
            <Label Text="{Binding ExposureLevel, StringFormat='level={0}'}"
                   FontSize="Small"/>
          </StackLayout>

        </StackLayout>

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

</ContentPage>

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

f:id:matatabi_ux:20150426074949p:plain

室内なので紫外線ゼロ・・・とれてますよね?!