Skip to content
This repository was archived by the owner on May 15, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Samples/Samples/Samples.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<ItemGroup>
<ProjectReference Include="..\..\Xamarin.Essentials\Xamarin.Essentials.csproj" />
</ItemGroup>

<Import Project="$(MSBuildThisFileDirectory)..\..\CodeStyles.targets" />

</Project>
35 changes: 35 additions & 0 deletions Samples/Samples/View/AllSensorsPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,41 @@
<Button Grid.Row="5" Grid.Column="1" Text="Stop" Command="{Binding StopCommand}"
IsEnabled="{Binding IsActive}" />
</Grid>

<Label Text="Orientation Sensor" FontAttributes="Bold" Margin="0,6,0,0" />
<Grid>
<Grid.BindingContext>
<viewmodels:OrientationSensorViewModel />
</Grid.BindingContext>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<Label Grid.Row="0" Grid.ColumnSpan="2" Text="{Binding X, StringFormat='X: {0:N}'}" />
<Label Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding Y, StringFormat='Y: {0:N}'}" />
<Label Grid.Row="2" Grid.ColumnSpan="2" Text="{Binding Z, StringFormat='Z: {0:N}'}" />
<Label Grid.Row="3" Grid.ColumnSpan="2" Text="{Binding W, StringFormat='W: {0:N}'}" />

<Picker Grid.Row="4" Grid.ColumnSpan="2" HorizontalOptions="FillAndExpand"
ItemsSource="{Binding Speeds}"
SelectedIndex="{Binding Speed, Mode=TwoWay}"
IsEnabled="{Binding IsActive, Converter={StaticResource NegativeConverter}}" />

<Button Grid.Row="5" Grid.Column="0" Text="Start" Command="{Binding StartCommand}"
IsEnabled="{Binding IsActive, Converter={StaticResource NegativeConverter}}" />

<Button Grid.Row="5" Grid.Column="1" Text="Stop" Command="{Binding StopCommand}"
IsEnabled="{Binding IsActive}" />
</Grid>
</StackLayout>
</ScrollView>
</StackLayout>
Expand Down
50 changes: 50 additions & 0 deletions Samples/Samples/View/OrientationSensorPage.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8" ?>
<views:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:views="clr-namespace:Samples.View"
xmlns:viewmodels="clr-namespace:Samples.ViewModel"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Samples.View.OrientationSensorPage"
Title="Orientation Sensor">
<views:BasePage.BindingContext>
<viewmodels:OrientationSensorViewModel />
</views:BasePage.BindingContext>

<StackLayout>
<Label Text="Retrieve orientation of the device in 3D space." FontAttributes="Bold" Margin="12" />

<ScrollView>
<Grid Padding="12,0,12,12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<Label Grid.Row="0" Grid.ColumnSpan="2" Text="{Binding X, StringFormat='X: {0:N}'}" />
<Label Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding Y, StringFormat='Y: {0:N}'}" />
<Label Grid.Row="2" Grid.ColumnSpan="2" Text="{Binding Z, StringFormat='Z: {0:N}'}" />
<Label Grid.Row="3" Grid.ColumnSpan="2" Text="{Binding W, StringFormat='W: {0:N}'}" />

<Picker Grid.Row="4" Grid.ColumnSpan="2" HorizontalOptions="FillAndExpand"
ItemsSource="{Binding Speeds}"
SelectedIndex="{Binding Speed, Mode=TwoWay}"
IsEnabled="{Binding IsActive, Converter={StaticResource NegativeConverter}}" />

<Button Grid.Row="5" Grid.Column="0" Text="Start" Command="{Binding StartCommand}"
IsEnabled="{Binding IsActive, Converter={StaticResource NegativeConverter}}" />

<Button Grid.Row="5" Grid.Column="1" Text="Stop" Command="{Binding StopCommand}"
IsEnabled="{Binding IsActive}" />
</Grid>
</ScrollView>
</StackLayout>

</views:BasePage>
10 changes: 10 additions & 0 deletions Samples/Samples/View/OrientationSensorPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace Samples.View
{
public partial class OrientationSensorPage : BasePage
{
public OrientationSensorPage()
{
InitializeComponent();
}
}
}
10 changes: 8 additions & 2 deletions Samples/Samples/ViewModel/HomeViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ public HomeViewModel()
"📏",
"All Sensors",
typeof(AllSensorsPage),
"Have a look at the accelerometer, compass, gyroscope and magnetometer.",
new[] { "accelerometer", "compass", "gyroscope", "magnetometer", "sensors", "hardware", "device" }),
"Have a look at the accelerometer, compass, gyroscope, magnetometer, and orientation sensors.",
new[] { "accelerometer", "compass", "gyroscope", "magnetometer", "orientation", "sensors", "hardware", "device" }),
new SampleItem(
"📦",
"App Info",
Expand Down Expand Up @@ -120,6 +120,12 @@ public HomeViewModel()
typeof(MagnetometerPage),
"Detect device's orientation relative to Earth's magnetic field.",
new[] { "compass", "magnetometer", "sensors", "hardware", "device" }),
new SampleItem(
"📏",
"Orientation Sensor",
typeof(OrientationSensorPage),
"Retrieve orientation of the device in 3D space.",
new[] { "orientation", "sensors", "hardware", "device" }),
new SampleItem(
"📞",
"Phone Dialer",
Expand Down
130 changes: 130 additions & 0 deletions Samples/Samples/ViewModel/OrientationSensorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.Windows.Input;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace Samples.ViewModel
{
class OrientationSensorViewModel : BaseViewModel
{
double x;
double y;
double z;
double w;
bool isActive;
int speed = 2;

public OrientationSensorViewModel()
{
StartCommand = new Command(OnStart);
StopCommand = new Command(OnStop);
}

public ICommand StartCommand { get; }

public ICommand StopCommand { get; }

public double X
{
get => x;
set => SetProperty(ref x, value);
}

public double Y
{
get => y;
set => SetProperty(ref y, value);
}

public double Z
{
get => z;
set => SetProperty(ref z, value);
}

public double W
{
get => w;
set => SetProperty(ref w, value);
}

public bool IsActive
{
get => isActive;
set => SetProperty(ref isActive, value);
}

public List<string> Speeds { get; } =
new List<string>
{
"Fastest",
"Game",
"Normal",
"User Interface"
};

public int Speed
{
get => speed;
set => SetProperty(ref speed, value);
}

public override void OnAppearing()
{
OrientationSensor.ReadingChanged += OnReadingChanged;
base.OnAppearing();
}

public override void OnDisappearing()
{
OnStop();
OrientationSensor.ReadingChanged -= OnReadingChanged;

base.OnDisappearing();
}

async void OnStart()
{
try
{
OrientationSensor.Start((SensorSpeed)Speed);
IsActive = true;
}
catch (Exception ex)
{
await DisplayAlertAsync($"Unable to start orientation sensor: {ex.Message}");
}
}

void OnStop()
{
IsActive = false;
Accelerometer.Stop();
}

void OnReadingChanged(OrientationSensorChangedEventArgs e)
{
var data = e.Reading;
switch ((SensorSpeed)Speed)
{
case SensorSpeed.Fastest:
case SensorSpeed.Game:
Platform.BeginInvokeOnMainThread(() =>
{
X = data.Orientation.X;
Y = data.Orientation.Y;
Z = data.Orientation.Z;
W = data.Orientation.W;
});
break;
default:
X = data.Orientation.X;
Y = data.Orientation.Y;
Z = data.Orientation.Z;
W = data.Orientation.W;
break;
}
}
}
}
65 changes: 65 additions & 0 deletions Xamarin.Essentials/OrientationSensor/OrientationSensor.android.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using Android.Hardware;
using Android.Runtime;

namespace Xamarin.Essentials
{
public static partial class OrientationSensor
{
internal static bool IsSupported =>
Platform.SensorManager?.GetDefaultSensor(SensorType.RotationVector) != null;

static OrientationSensorListener listener;
static Sensor orientationSensor;

internal static void PlatformStart(SensorSpeed sensorSpeed)
{
var delay = SensorDelay.Normal;
switch (sensorSpeed)
{
case SensorSpeed.Normal:
delay = SensorDelay.Normal;
break;
case SensorSpeed.Fastest:
delay = SensorDelay.Fastest;
break;
case SensorSpeed.Game:
delay = SensorDelay.Game;
break;
case SensorSpeed.Ui:
delay = SensorDelay.Ui;
break;
}

listener = new OrientationSensorListener();
orientationSensor = Platform.SensorManager.GetDefaultSensor(SensorType.RotationVector);
Platform.SensorManager.RegisterListener(listener, orientationSensor, delay);
}

internal static void PlatformStop()
{
if (listener == null || orientationSensor == null)
return;

Platform.SensorManager.UnregisterListener(listener, orientationSensor);
listener.Dispose();
listener = null;
}
}

class OrientationSensorListener : Java.Lang.Object, ISensorEventListener
{
internal OrientationSensorListener()
{
}

void ISensorEventListener.OnAccuracyChanged(Sensor sensor, [GeneratedEnum] SensorStatus accuracy)
{
}

void ISensorEventListener.OnSensorChanged(SensorEvent e)
{
var data = new OrientationSensorData(e.Values[0], e.Values[1], e.Values[2], e.Values[3]);
OrientationSensor.OnChanged(data);
}
}
}
53 changes: 53 additions & 0 deletions Xamarin.Essentials/OrientationSensor/OrientationSensor.ios.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using CoreMotion;
using Foundation;

namespace Xamarin.Essentials
{
public static partial class OrientationSensor
{
// Timing intervales to match android sensor speeds in seconds
// https://stackoverflow.com/questions/10044158/android-sensors
internal const double FastestInterval = .02;
internal const double GameInterval = .04;
internal const double UiInterval = .08;
internal const double NormalInterval = .225;

internal static bool IsSupported =>
Platform.MotionManager?.DeviceMotionAvailable ?? false;

internal static void PlatformStart(SensorSpeed sensorSpeed)
{
var manager = Platform.MotionManager;
switch (sensorSpeed)
{
case SensorSpeed.Fastest:
manager.DeviceMotionUpdateInterval = FastestInterval;
break;
case SensorSpeed.Game:
manager.DeviceMotionUpdateInterval = GameInterval;
break;
case SensorSpeed.Normal:
manager.DeviceMotionUpdateInterval = NormalInterval;
break;
case SensorSpeed.Ui:
manager.DeviceMotionUpdateInterval = UiInterval;
break;
}

manager.StartDeviceMotionUpdates(Platform.GetCurrentQueue(), DataUpdated);
}

static void DataUpdated(CMDeviceMotion data, NSError error)
{
if (data == null)
return;

var field = data.Attitude.Quaternion;
var rotationData = new OrientationSensorData(field.x, field.y, field.z, field.w);
OnChanged(rotationData);
}

internal static void PlatformStop() =>
Platform.MotionManager?.StopDeviceMotionUpdates();
}
}
Loading