Working with MIDI in Windows Store App (Win 8.1) - c#

My goal is to receive MIDI messages in Windows Store Apps.
Microsoft has delivered an API called Microsoft.WindowsPreview.MidiRT (as a nuget package).
I managed to get a midi port, but MessageReceived event is not arised, although I'm pressing keys on my MIDI keyboard, and other MIDI programs show me that PC receives these messages.
Here is my code:
public sealed partial class MainPage : Page
{
private MidiInPort port;
public MainPage()
{
this.InitializeComponent();
DeviceWatcher watcher = DeviceInformation.CreateWatcher();
watcher.Updated += watcher_Updated;
watcher.Start();
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
port.Dispose();
}
async void watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
DeviceInformationCollection deviceCollection = await DeviceInformation.FindAllAsync(MidiInPort.GetDeviceSelector());
foreach (var item in deviceCollection)
{
Debug.WriteLine(item.Name);
if (port == null)
{
port = await MidiInPort.FromIdAsync(item.Id);
port.MessageReceived += port_MessageReceived;
}
}
}
void port_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
{
Debug.WriteLine(args.Message.Type);
}
}
Any ideas?

Possibly-related: Your device watcher code is not following the normal pattern. Here is what you need to do:
DeviceWatcher midiWatcher;
void MonitorMidiChanges()
{
if (midiWatcher != null)
return;
var selector = MidiInPort.GetDeviceSelector();
midiWatcher = DeviceInformation.CreateWatcher(selector);
midiWatcher.Added += (s, a) => Debug.WriteLine("Midi Port named '{0}' with Id {1} was added", a.Name, a.Id);
midiWatcher.Updated += (s, a) => Debug.WriteLine("Midi Port with Id {1} was updated", a.Id);
midiWatcher.Removed += (s, a) => Debug.WriteLine("Midi Port with Id {1} was removed", a.Id);
midiWatcher.EnumerationCompleted += (s, a) => Debug.WriteLine("Initial enumeration complete; watching for changes...");
midiWatcher.Start();
}

I managed to make it work. I've changed the platfrom to x64, and now it works (I used to build it for x86). There is still a problem though (and it is even bigger): I want to integrate this with Unity3d, but Unity3d doesn't allow to build x64 windows apps, on the other hand x86 MIDI build doesn't work on x64 machines.
Added:
Although this API depends on your architecture, a new Windows 10 api reportedly does not, so it should be simpler, if you target Win10.

Related

EventHandler to get HDMI connectivity in windows application

I am looking for event handler to get the information when HDMI is connected or disconnected using c#/WPF like how myNetworkAvailabilityChangeHandler is used to detect when internet gots disconnected or connected.
There is no direct answer to this but you can use the SystemEvents to achieve this.
Code in C# :
main()
{
SystemEvents.DisplaySettingsChanged += new
EventHandler(SystemEvents_DisplaySettingsChanged);
}
private void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
int HDMI_Monitors = 0;
ManagementClass mClass = new ManagementClass(#"\\localhost\ROOT\WMI:WmiMonitorConnectionParams");
foreach (ManagementObject mObject in mClass.GetInstances())
{
var ss = mObject["VideoOutputTechnology"];
if(ss.ToString().StartsWith("5"))
{
int HDMIport = Convert.ToInt32(ss);
if (HDMIport == 5)
{
HDMI_Monitors += 1;
}
}
}
}
You can use the model class to keep on updating the HDMI status.
So every time your HDMI will connect or disconnect SystemEvents_DisplaySettingsChanged will trigger and then it will check the HDMI connection.

Xamarin.Forms - Android/iOS : Push notification not working if app is killed

I have used https://github.com/CrossGeeks/PushNotificationPlugin for push notifications in my xamarin.forms application.
The major issue I am facing currently is Notifications not arriving in device once the app is closed. Here is how the push notifications working:
it works if app is in foreground or background,
if kill app and then send notification it not works
if you again open app and it's again either in background or foreground notifications not works
So it works only first time when app is installed in device and it's in
either Foreground or background.
Anyone know how to handle this issue?
I have initialised plugin in both Android and iOS also setup all required things.
Version of packages I have used:
Xamarin.Forms - 4.7.0.968
Plugin.PushNotification - 1.3.0
1 Code in App.xaml.cs OnStartMethod
CrossPushNotification.Current.OnTokenRefresh += (s, p) =>
{
if (Device.RuntimePlatform == Device.Android)
{
DeviceToken = p.Token;
}
};
CrossPushNotification.Current.OnNotificationReceived += async (s, p) =>
{
//Logic to handle arrived notification
};
CrossPushNotification.Current.OnNotificationOpened += async (s, p) =>
{
//Notification tap handler code here
};
CrossPushNotification.Current.OnNotificationDeleted += (s, p) =>
{
Debug.WriteLine("Dismissed");
};
2 Android Main Application class
[Application]
public class MainApplication : Application
{
public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
//Set the default notification channel for your app when running Android Oreo
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
//Change for your default notification channel id here
PushNotificationManager.DefaultNotificationChannelId = "DefaultChannel";
//Change for your default notification channel name here
PushNotificationManager.DefaultNotificationChannelName = "General";
}
//If debug you should reset the token each time.
#if DEBUG
PushNotificationManager.Initialize(this, true);
#else
PushNotificationManager.Initialize(this, false);
#endif
//PushNotificationManager.IconResource = Resource.Drawable.icon;
//Handle notification when app is closed here
CrossPushNotification.Current.OnNotificationReceived += (s, p) =>
{
};
}
}
3 Android: MainActivity class
protected async override void OnCreate(Bundle savedInstanceState)
{
LoadApplication(new App());
PushNotificationManager.ProcessIntent(this, Intent);
}

Xamarin Forms Bluetooth LE not showing nearby discoverable devices

I am making an app that utilizes bluetooth function such as scanning devices etc. I checked the scan flag and returns true but not showing the discoverable device that I am testing.
I am using Samsung J7 Pro as my app test device and Samsung J7 as the device I want to see in the list of discovered devices.
J7 already set as discoverable and with bluetooth ON.
I based my codes in Monkey.BluetoothLE
Here is what I have:
Declarations
ObservableCollection<BluetoothViewModel> vm = new ObservableCollection<BluetoothViewModel>();
Android.Bluetooth.BluetoothManager _blManager;
Android.Bluetooth.BluetoothManager _blManager;
Robotics.Mobile.Core.Bluetooth.LE.Adapter _bleAdapter;
Functions
public BluetoothPage()
{
InitializeComponent();
lvInfo.ItemsSource = vm;
var appContext = Android.App.Application.Context;
_blManager = (Android.Bluetooth.BluetoothManager)appContext.GetSystemService("bluetooth");
_blAdapter = _blManager.Adapter;
_bleAdapter = new Robotics.Mobile.Core.Bluetooth.LE.Adapter();
_bleAdapter.DeviceDiscovered += _bleAdapter_DeviceDiscovered;
_bleAdapter.ScanTimeoutElapsed += _bleAdapter_ScanTimeoutElapsed;
}
private void btnScanStopBluetooth_Click(object sender, EventArgs e)
{
if (!_bleAdapter.IsScanning)
{
if (!_blAdapter.IsEnabled)
{
_blAdapter.Enable();
DisplayInformation("Turning on bluetooth...");
while (!_blAdapter.IsEnabled)
{
//do nothing until enabled
}
}
vm.Clear();
btnScan.Text = "Stop Scan";
_bleAdapter.StartScanningForDevices();
}
else
{
btnScan.Text = "Start Scan";
_bleAdapter.StopScanningForDevices();
}
}
private void _bleAdapter_DeviceDiscovered(object sender, Robotics.Mobile.Core.Bluetooth.LE.DeviceDiscoveredEventArgs e)
{
count++;
vm.Add(new BluetoothViewModel
{
Name = e.Device.Name,
ID = e.Device.ID.ToString(),
RSSI = e.Device.Rssi.ToString()
});
}
private void _bleAdapter_ScanTimeoutElapsed(object sender, EventArgs e)
{
DisplayInformation("Scan Timeout");
_bleAdapter.StopScanningForDevices();
btnScan.Text = "Start Scan";
}
private void DisplayInformation(string line)
{
lblStatus.Text = line;
}
A listview is bound to "vm" that will display the discovered device.
It does not show anything, and count is always zero but I checked the scan flag using _bleAdapter.IsScanning, it returns true.
EDIT:
I tried other open-source sample programs for Bluetooth such as
xamarin-bluetooth-le (BLE Explorer)
Bluetooth-Xamarin.Forms (DemoBluetooth)
None of them seem to list the device. When I use my built-in bluetooth app under settings, it lists the device. What am I missing here?
Have you granted permission for bluetooth and location?
You have to grant permission in the Manifest/or Settings and depending on the sdk (23+) also asking the user for extra permission.
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/permissions?tabs=windows

Detect changes in Wifi

I need to detect when wifi is turned on/off. For that purpose I'm using Connectivity by James Montemagno, but the problem is that I don't get an ConnectivityChanged event if the Phone have access to mobile network and I turn on/off the wifi.
Here is the mapping of the event:
CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
{
WiFiConnected = CrossConnectivity.Current.ConnectionTypes.Contains(ConnectionType.WiFi);
};
So can I detect Connectivity Changed on Wifi? I would like to do it in Xamarin Forms code so I won't have to implement a solution for each platform.
Here What Your Looking For
CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
{
if (args.IsConnected.ToString().Equals("False"))
{
if (CrossConnectivity.Current.ConnectionTypes.Contains(ConnectionType.WiFi))
{
// WE LOST AN CONNECTION BUT WIFI IS STILL ON
}
}
else
{
if (CrossConnectivity.Current.ConnectionTypes.Contains(ConnectionType.WiFi))
{
// WIFI WAS TURN ON AND WE HAVE A CONNECTION
}
else
{
// WE HAVE A CONNECTION BUT NOT WIFI
}
}
};
I dont know if there is a xamarin forms solution but you can do it plateform specific. In android with BroadcastReceiver.. for other plateforms i have no idea..

What Triggers the ValueUpdated property in BLE C# code

I am building a Xamarin.Formscross platform mobile app, which uses Monkey.Robotics for its Bluetoth Low Energy functionality. I am connecting to an mbed based implimentation of a custom GATT service.
In the Xamarin C#, What triggers the Characteristic ValueUpdated event in Monkey.Robotics?
This is a standard example my C# is based on:
if (characteristic.CanUpdate) {
characteristic.ValueUpdated += (s, e) => {
Debug.WriteLine("characteristic.ValueUpdated");
Device.BeginInvokeOnMainThread( () => {
UpdateDisplay(characteristic);
});
IsBusy = false; // only spin until the first result is received
};
IsBusy = true;
characteristic.StartUpdates();
}
This has been working, but since I changed to my own custom GATT service which I am connecting to, the ValueUpdated event is never triggered. What is this event and how is it triggered? Is this a property read from the Characteristic, as set up by the mbed device, or is it something which the mobile end works out?
Thanks
this is from the Android implementation
this._gattCallback.CharacteristicValueUpdated += (object sender, CharacteristicReadEventArgs e) => {
// it may be other characteristics, so we need to test
if(e.Characteristic.ID == this.ID) {
// update our underlying characteristic (this one will have a value)
//TODO: is this necessary? probably the underlying reference is the same.
//this._nativeCharacteristic = e.Characteristic;
this.ValueUpdated (this, e);
}
};

Categories

Resources