#xamarin #android-bluetooth
#xamarin #android-bluetooth
Вопрос:
у меня проблема с получением данных от модуля Bluetooth HC-05. Отправка данных с мобильного устройства на модуль работает нормально, но я не могу понять, как получать данные из модуля. Я думаю, что возникнет проблема с потоком, который содержит функцию прослушивания. Спасибо за помощь
вот код:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Bluetooth;
using Microcharts;
using Entry = Microcharts.Entry;
using Microcharts.Droid;
using SkiaSharp;
using System.Linq;
using System.Collections.Generic;
namespace BLE
{
[Activity(Label = "BLE", MainLauncher = true)]
public class MainActivity : Activity
{
BluetoothConnection myConnection = new BluetoothConnection();
protected override void OnCreate(Bundle savedInstanceState)
{
var metrics = Resources.DisplayMetrics;
var width = metrics.WidthPixels;
var height = metrics.HeightPixels;
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
Button buttonConnect = FindViewById<Button>(Resource.Id.button1);
Button buttonDisconnect = FindViewById<Button>(Resource.Id.button2);
buttonConnect.LayoutParameters.Width = Convert.ToInt32(width * 0.5);
buttonDisconnect.LayoutParameters.Width = Convert.ToInt32(width * 0.5);
TextView connected = FindViewById<TextView>(Resource.Id.textView1);
BluetoothSocket _socket = null;
System.Threading.Thread listenThread = new System.Threading.Thread(listener);
listenThread.Abort();
buttonConnect.Click = delegate
{
try
{
buttonDisconnect.Enabled = false;
buttonConnect.Enabled = true;
listenThread.Abort();
myConnection.thisDevice.Dispose();
myConnection.thisSocket.OutputStream.WriteByte(187);
myConnection.thisSocket.OutputStream.Close();
myConnection.thisSocket.Close();
myConnection = new BluetoothConnection();
_socket = null;
connected.Text = "Disconnected!";
}
catch { }
listenThread.Start();
myConnection = new BluetoothConnection();
myConnection.thisSocket = null;
_socket = null;
myConnection.getAdapter();
myConnection.thisAdapter.StartDiscovery();
try
{
myConnection.getDevice();
myConnection.thisDevice.SetPairingConfirmation(false);
myConnection.thisDevice.Dispose();
myConnection.thisDevice.SetPairingConfirmation(true);
myConnection.thisDevice.CreateBond();
}
catch (Exception deviceEX)
{
}
myConnection.thisAdapter.CancelDiscovery();
_socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
myConnection.thisSocket = _socket;
try
{
myConnection.thisSocket.Connect();
connected.Text = "Connected!";
buttonDisconnect.Enabled = true;
buttonConnect.Enabled = false;
if (listenThread.IsAlive == false)
{
listenThread.Start();
}
}
catch (Exception CloseEX)
{
}
};
buttonDisconnect.Click = delegate
{
try
{
buttonConnect.Enabled = true;
listenThread.Abort();
myConnection.thisDevice.Dispose();
myConnection.thisSocket.OutputStream.WriteByte(187);
myConnection.thisSocket.OutputStream.Close();
myConnection.thisSocket.Close();
myConnection = new BluetoothConnection();
_socket = null;
connected.Text = "Disconnected!";
}
catch { }
};
void listener()
{
TextView readTextView = FindViewById<TextView>(Resource.Id.textView2);
while (true)
{
try
{
byte[] buffer = new byte[1];
myConnection.thisSocket.InputStream.Read(buffer, 0, 1);
myConnection.thisSocket.InputStream.Close();
String dispString = System.Text.ASCIIEncoding.Default.GetString(buffer);
RunOnUiThread(() =>
{
//readTextView.Text = dispString;
System.Console.WriteLine(dispString);
});
}
catch (Java.IO.IOException)
{
RunOnUiThread(() =>
{
readTextView.Text = string.Empty;
});
break;
}
}
}
}
public class BluetoothConnection
{
public void getAdapter() { this.thisAdapter = BluetoothAdapter.DefaultAdapter; }
public void getDevice() { this.thisDevice = (from bd in this.thisAdapter.BondedDevices where bd.Name == "HC-05" select bd).FirstOrDefault(); }
public BluetoothAdapter thisAdapter { get; set; }
public BluetoothDevice thisDevice { get; set; }
public BluetoothSocket thisSocket { get; set; }
}
}
}
`
Спасибо за помощь
Комментарии:
1. может ли это сработать?
Ответ №1:
Я не понимаю, для чего это используется в buttonConnect.Click
случае
try
{
buttonDisconnect.Enabled = false;
buttonConnect.Enabled = true;
listenThread.Abort();
myConnection.thisDevice.Dispose();
myConnection.thisSocket.OutputStream.WriteByte(187);
myConnection.thisSocket.OutputStream.Close();
myConnection.thisSocket.Close();
myConnection = new BluetoothConnection();
_socket = null;
connected.Text = "Disconnected!";
}
catch { }
и обычно получают данные, подобные этому (простое использование):
System.Threading.Thread listenThread = new System.Threading.Thread(Listener);
buttonConnect.Click = delegate {
myConnection = new BluetoothConnection();
myConnection.getAdapter();
myConnection.getDevice();
_socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
myConnection.thisSocket = _socket;
myConnection.thisSocket.Connect();
listenThread.Start();
}
private void Listener()
{
while (true)
{
try
{
byte[] buffer = new byte[1];
TextView readTextView = FindViewById<TextView>(Resource.Id.textView2);
myConnection.thisSocket.InputStream.Read(buffer, 0, 1);
myConnection.thisSocket.InputStream.Close();
String dispString = System.Text.ASCIIEncoding.Default.GetString(buffer);
RunOnUiThread(() =>
{
readTextView.Text = dispString;
System.Console.WriteLine(dispString);
});
}
catch (Java.IO.IOException)
{
TextView readTextView = FindViewById<TextView>(Resource.Id.textView2);
RunOnUiThread(() =>
{
readTextView.Text = string.Empty;
});
break;
}
}
}
}
public class BluetoothConnection
{
public void getAdapter() { this.thisAdapter = BluetoothAdapter.DefaultAdapter; }
public void getDevice() { this.thisDevice = (from bd in this.thisAdapter.BondedDevices where bd.Name == "hc-05" select bd).FirstOrDefault(); }
public BluetoothAdapter thisAdapter { get; set; }
public BluetoothDevice thisDevice { get; set; }
public BluetoothSocket thisSocket { get; set; }
}