I'm trying to do an UI with C# on Visual Studio (on PC[windows10]) and connect some bluetooth devices.
I'm using Windows.Devices.Radios & Windows.Devices.Bluetooth, but I have some troubles with that. After few steps I try to use the bluetooth when I press a button.
This is the code
private async void btnStart_ClickAsync(object sender, EventArgs e)
{
Repl test = new Repl();
var radio = await Radio.RequestAccessAsync();
if (access != RadioAccessStatus.Allowed)
{
return;
}
BluetoothAdapter adapter = await BluetoothAdapter.GetDefaultAsync();
if (null != adapter)
{
var btRadio = await adapter.GetRadioAsync();
if (bluetoothState)
{
await btRadio.SetStateAsync(RadioState.On);
}
else
{
await btRadio.SetStateAsync(RadioState.Off);
}
}
string connect = $"connect {macRight}\r\n";
//string start = "start\r\n";
await BaseCommands.repl.ParseLine(connect);
}
after the 1st request I'm always in the "return;"
I saw some people saying use x32 or x64 and x86. I already try that but I don't know why it doesn't work for me ...
I also saw some post saying change something in the Manifest, but I don't know where to find it :/
I'm a beginner with C#/.NET so if someone can help me to fix that i will appreciate =)
PS : I have another project which use bluetooth and it work perfectly so I have no ideas to fix my own project ...
Related
I'm developing a c# desktop api with forms where I want to receive ACC data from a BLE server und display them in a chart.
So I'm running in a connection problem and I can't find any solution.
I can find my LE server Device with the watcher.
DevicePairingResult dpr = await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.Encryption);
returns me "AlreadyPaired"
But when I do
device = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress: eventArgs.BluetoothAddress);
mGattService = device.GetGattService(MotionService_GUID);
mCharacteristic = mGattService.GetCharacteristics(ACC_Characteristic_GUID)[0];
and then
var con = device.ConnectionStatus;
I receive "Disconnected" in con.
I am bound with de device on windows( I searched for it in Windows and entered the Code) but I am not connected(based on the Status in the windows info center).
I've read in another Thread in the windows c# developer page that it should not be necessary anymore to pair the device manually.
I'm pretty shure that the rest of my code works because sometimes I can get a connection( pretty confusing for me) and see the right Data in my chart.
Right now I just want to reach a stable connection before changing other part of my code.
Anyone any idea how to solve this?
Thx medTech
Edit:
Here is part of the Code:
Scanning for BLE
private void button1_Click(object sender, EventArgs e)
{
// Create Bluetooth Listener
var watcher = new BluetoothLEAdvertisementWatcher();
watcher.ScanningMode = BluetoothLEScanningMode.Active;
// Register callback for when we see an advertisements
watcher.Received += OnAdvertisementReceivedAsync;
// Wait 5 seconds to make sure the device is really out of range
watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);
// Starting watching for advertisements
watcher.Start();
}
Connect to Server:
private async void OnAdvertisementReceivedAsync(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
// Filter for specific Device
if (eventArgs.Advertisement.LocalName == "MYDEVICE")
{
watcher.Stop();
var MotionService_GUID = new Guid("00002000-0000-1000-8000-00805F9B34FB");
var ACC_Characteristic_GUID = new Guid("00002001-0000-1000-8000-00805F9B34FB");
device = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress: eventArgs.BluetoothAddress);
DevicePairingResult dpr = await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.Encryption);
mGattService = device.GetGattService(MotionService_GUID);
mCharacteristic = mGattService.GetCharacteristics(ACC_Characteristic_GUID)[0];
GattDeviceServicesResult result = await device.GetGattServicesAsync();
GattCommunicationStatus status1 = await ReadFromCharacteristicAsync(mCharacteristic);
var con = device.ConnectionStatus;
while (status1 == GattCommunicationStatus.Success)
{
try
{
status1 = await ReadFromCharacteristicAsync(mCharacteristic);
}
catch
{
Console.WriteLine("ERROR");
status1 = GattCommunicationStatus.Unreachable;
}
}
}
}
Read from Characteristic:
async Task ReadFromCharacteristicAsync(GattCharacteristic mCharacteristic)
{
GattReadResult readResult = await mCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);
if (readResult.Status == GattCommunicationStatus.Success)
{
byte[] data = new byte[readResult.Value.Length];
DataReader.FromBuffer(readResult.Value).ReadBytes(data);
if (chart1.IsHandleCreated)
{
this.Invoke((MethodInvoker)delegate { updateChart(data); });
}
return readResult.Status;
}
return readResult.Status;
}
Terminate Connection
private async Task<bool> ClearBluetoothLEDeviceAsync()
{
mCharacteristic.Service.Dispose();
mGattService.Dispose();
await device.DeviceInformation.Pairing.UnpairAsync();
device?.Dispose();
device = null;
GC.Collect();
return true;
}
SO now when I connect the first time to the Server, I only receive zeros which shows me that the there might be a authentication Error.
After that I always receive this Error:
"System.ArgumentException" in mscorlib.dll with a notification that there is noch executable Code left because all Threads are doing some asynchronous stuff.
This Error gets thrown when I try to read from the Characteristic.
I never coded in c# before so I am not shure if there is an error in my asynchronous part oder the communication part.
Thanks you
Pairing is not the same as connecting!
I really advise using the BLE-advertisementWatcher to select and connect to your device.
The reason is that many BLE-devices don't save their pairing status.
In windows device-watcher once paired, the device stays paired even if it is switched off or out of reach.
Also many times the connection status is kept, unless the device is unpaired and disposed in code or removed in windows settings.
All BLE-devices that I know of start advertising as soon as there is no connection for some time.
This time depends on the device, but most of the time within seconds.
So don't pair but just connect if the device is advertising.
I'm trying to send an email in my xamarin forms project, I have tried both in the iPhone simulator and on an iPhone device. When I push the send email button on the iPhone, nothing happens, not even a debug error. I have also made sure i am logged in with my email on the device.
I have used serviceDependency and followed the setup at this link:
https://developer.xamarin.com/recipes/ios/shared_resources/email/send_an_email/
my interface:
public interface InterfaceEmail
{
void sendEmail();
}
iOS implementation:
[assembly: Xamarin.Forms.Dependency(typeof(SendEmail))]
namespace myProject.iOS
{
public partial class SendEmail : InterfaceEmail
{
MFMailComposeViewController mailController;
public SendEmail() {}
public void sendEmail()
{
if (MFMailComposeViewController.CanSendMail)
{
mailController = new MFMailComposeViewController();
mailController.SetToRecipients (new string[] {"my#email.com"});
mailController.SetSubject ("test mail");
mailController.SetMessageBody ("This is a test", false);
mailController.Finished += (object sender, MFComposeResultEventArgs e) =>
{
Console.WriteLine(e.Result.ToString());
e.Controller.DismissViewController(true, null);
};
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailController, true, null);
}}}}
Implementation in my shared code:
async void Handle_ToolbarButton(object sender, System.EventArgs e)
{
var action = await DisplayActionSheet("What do you want to do?", "Abort", null, "Send email");
if(action == "Send email")
{
DependencyService.Get<InterfaceEmail>().sendEmail();
}
}
Does anyone have an idea on what could be wrong here?
For a better way to send email without even writing platform specific code install this nuget into your solution
xam.plugin.Messaging(https://www.nuget.org/packages/Xam.Plugins.Messaging/)
Then write the code below in PCL
var email = new EmailMessageBuilder()
.To("to.plugins#xamarin.com")
.Subject("Xamarin Messaging Plugin")
.Body("Well hello there from Xam.Messaging.Plugin")
.Build();
You can also add attachments. For more details please go through https://github.com/cjlotz/Xamarin.Plugins/blob/master/Messaging/Details.md
Probably it is related to this bug:
https://bugzilla.xamarin.com/show_bug.cgi?id=58933
Just remove DisplayActionSheet.
Or if you want to use it, then there is a temporary solution in this Xamarin forum topic
Add
await Task.Delay(100);
after DisplayActionSheet
The iPhone simulator will always return false to CanSendMail as it can not send mail. On a physical device, you will need to configure at least on e mail account.
Also:
Typo in:
[assembly: Xamarin.Forms.Dependency(typeof(sendEmail))]
Should be:
[assembly: Xamarin.Forms.Dependency(typeof(SendEmail))]
Typo in:
mailController.Finnished += ~~~~~
Should be:
mailController.Finished += ~~~~~
I recently bought a Lilypad Simblee BLE Board and I'd like to pair it programmatically to my computer (using the 32feet.NET library in C#).
I'm aware the "How to programmatically pair a bluetooth device" has already been asked on StackOverflow (here for example), however for some reason, all my attempts to pair the device programmatically have failed. Indeed, I successfully paired the device with the "Manage Bluetooth devices" window in Windows 10 Settings panel (Settings > Devices > Bluetooth).
Firstly, I don't know the pairing method (either legacy or SSP) to use with my device. Windows never asked me for a PIN or something, so I guess it's SSP, but I'm unsure.
I searched on Google how to do a SSP pairing request with 32feet.NET: I found this.
However, once it discovered my device (the device discovery works properly), the pairing request instantly fails.
My code:
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;
namespace HLK_Client
{
class HLKBoard
{
public event HLKBoardEventHandler HLKBoardConnectionComplete;
public delegate void HLKBoardEventHandler(object sender, HLKBoardEventArgs e);
private BluetoothClient _bluetoothClient;
private BluetoothComponent _bluetoothComponent;
private List<BluetoothDeviceInfo> _inRangeBluetoothDevices;
private BluetoothDeviceInfo _hlkBoardDevice;
private EventHandler<BluetoothWin32AuthenticationEventArgs> _bluetoothAuthenticatorHandler;
private BluetoothWin32Authentication _bluetoothAuthenticator;
public HLKBoard()
{
_bluetoothClient = new BluetoothClient();
_bluetoothComponent = new BluetoothComponent(_bluetoothClient);
_inRangeBluetoothDevices = new List<BluetoothDeviceInfo>();
_bluetoothAuthenticatorHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(_bluetoothAutenticator_handlePairingRequest);
_bluetoothAuthenticator = new BluetoothWin32Authentication(_bluetoothAuthenticatorHandler);
_bluetoothComponent.DiscoverDevicesProgress += _bluetoothComponent_DiscoverDevicesProgress;
_bluetoothComponent.DiscoverDevicesComplete += _bluetoothComponent_DiscoverDevicesComplete;
}
public void ConnectAsync()
{
_inRangeBluetoothDevices.Clear();
_hlkBoardDevice = null;
_bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, false, null);
}
private void PairWithBoard()
{
Console.WriteLine("Pairing...");
bool pairResult = BluetoothSecurity.PairRequest(_hlkBoardDevice.DeviceAddress, null);
if (pairResult)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Fail"); // Instantly fails
}
}
private void _bluetoothComponent_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e)
{
_inRangeBluetoothDevices.AddRange(e.Devices);
}
private void _bluetoothComponent_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e)
{
for (int i = 0; i < _inRangeBluetoothDevices.Count; ++i)
{
if (_inRangeBluetoothDevices[i].DeviceName == "HLK")
{
_hlkBoardDevice = _inRangeBluetoothDevices[i];
PairWithBoard();
return;
}
}
HLKBoardConnectionComplete(this, new HLKBoardEventArgs(false, "Didn't found any \"HLK\" discoverable device"));
}
private void _bluetoothAutenticator_handlePairingRequest(object sender, BluetoothWin32AuthenticationEventArgs e)
{
e.Confirm = true; // Never reach this line
}
}
}
Why does the pairing request fail?
The answer to the question you linked has a plausible suggestion... did you read it?
Also you should look at this question as well.
32feet library is built around legacy pairing, so that you either need to know the pin of the device you are connecting to, or you supply it with a null to get a popup window to enter a pin.
It also says that the windows function used by 32feet is deprecated in newer versions of windows. If that's true, the reason it's failing instantly is because you've passed a null pin in your pairing request and for it to proceed windows needs to show a dialog which no longer exists.
What happens if you try to connect with the pin "0000" or "1234" ?
I'm looking at the source code of WindowsBluetoothSecurity.cs in 32feet.net and I see if a pairing request fails, it logs the error code to Debug.WriteLine, any chance you could post that error code here?
One good work around to this problem might be to import BluetoothAuthenticateDeviceEx and use that manually to complete the pairing request. If you don't want to do this manually, it looks like in the latest version of the 32feet source, there is actually a SSP pairing method that utilises this method but it's not public and it's not used anywhere so you'll need to access it via reflection:
typeof(BluetoothSecurity)
.GetMethod("PairRequest", BindingFlags.Static | BindingFlags.NonPublic)
.Invoke(null, new object[] { _hlkBoardDevice.DeviceAddress, BluetoothAuthenticationRequirements.MITMProtectionNotRequired });
hi there :) il get right to it.
Problem :
when i try to instanciate LiveConnectClient and then try to access the event : GetCompleted
which supose to be in the LiveConnectClient is not showing and on all the examples i been looking at even those on here are using it. this is not the only class this is happening on it is also happening on LiveAuthClient as well no events even the post on the net says there should be.
i tried to reinstall Vs2012 and sdk wp8 and live sdk from scratch but have not solved it
for refrence i using this example to see if i can it to work :
//event triggered when Skydrive sign in status is changed
private void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
//if the user is signed in
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Accessing SkyDrive...";
//get the folders in their skydrive
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(btnSignin_GetCompleted);
client.GetAsync("me/skydrive/files?filter=folders,albums");
}
//otherwise the user isn't signed in
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
i got no luck solving it and running out of ideas. So im hoping one of u boys out there can shed some light on it or lend a hand with dew wise words :)
thanks in advance. and i do apologies if this is to long a post.
regards jens
Indeed, it seems like those events have been removed in the latest versions of the SDK. You don't need them though, thanks to the async/await keywords. First, mark your method as async, then call the GetAsync method with the await keyword. And place afterward the code you would normally put in the GetCompleted event:
private async void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
//if the user is signed in
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Accessing SkyDrive...";
//get the folders in their skydrive
var result = await client.GetAsync("me/skydrive/files?filter=folders,albums");
// Do here what you would normally do in btnSignin_GetCompleted
}
//otherwise the user isn't signed in
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
I have an problem with muting the mic on an windows 7 machine. But all the code i have found dosen't run ore it's not doing anything the runned. Have is it done for an Windows 7 machine using C# code. I just need an on/off solution.
The DDL file works also with Win x64bit. But i thing that i creates an error another place.
mixers.Recording.Lines.GetMixerFirstLineByComponentType(
MIXERLINE_COMPONENTTYPE.SRC_MICROPHONE).Volume = 0;
if (!mediaElement1.CheckAccess()) mediaElement1.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate { mediaElement1.Play(); });
if (MessageBox.Show("Incoming Call from: " + string.Format(e.RemoteParticipant), "Video Chat Call", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
mixers.Recording.Lines.GetMixerFirstLineByComponentType(
MIXERLINE_COMPONENTTYPE.SRC_MICROPHONE).Volume = 1;
if (!mediaElement1.CheckAccess()) mediaElement1.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate { mediaElement1.Stop(); });
_currentConversation.StartVideo();
}'
If error occurs at if (MessageBox.Show("Incoming Call from: " + string.Format(e.RemoteParticipant), "Video Chat Call", MessageBoxButton.YesNo) == MessageBoxResult.Yes) and says {"Arithmetic operation resulted in an overflow."}
http://www.computercabal.com/2010/11/mute-microphone-from-c-on-windows.html -- this gentleman appears to have had a similar problem, and he's provided the source code for a solution.
You can use Audio Switcher Api
https://www.nuget.org/packages/AudioSwitcher.AudioApi.CoreAudio/4.0.0-alpha5
Code is quite simple:
private async void btnMute_ButtonClick(object sender, EventArgs e)
{
var audioController = new CoreAudioController();
var devices = await audioController.GetDevicesAsync(DeviceType.Capture, DeviceState.Active);
var device = devices.FirstOrDefault(x => x.IsDefaultDevice);
if(device != null) {
await device.SetMuteAsync(!device.IsMuted);
}
}
this might help: Windows Mixer Control in C#
Good luck :).
EDIT: It can also mute certain devices if I'm right.