2025-07-04 07:54:44 +02:00

96 lines
2.7 KiB
C#

using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace NotVPR_SideProjecktForVpr_FreeTime
{
public class BluetoothServer
{
private BluetoothListener _listener;
private BluetoothClient _client;
private NetworkStream _stream;
private Thread _receiveThread;
public event Action<string> MessageReceived;
public event Action ClientConnected;
public event Action<string> ErrorOccurred;
public bool IsRunning { get; private set; }
public void Init()
{
if (!BluetoothRadio.IsSupported)
throw new NotSupportedException("Bluetooth adapter not found.");
_listener = new BluetoothListener(BluetoothService.SerialPort);
_listener.Start();
Console.WriteLine("Waiting for Bluetooth client connection...");
_client = _listener.AcceptBluetoothClient();
_stream = _client.GetStream();
IsRunning = true;
Console.WriteLine("Client connected.");
ClientConnected?.Invoke();
_receiveThread = new Thread(ReceiveLoop);
_receiveThread.Start();
}
private void ReceiveLoop()
{
byte[] buffer = new byte[1024];
try
{
while (IsRunning && _stream.CanRead)
{
int bytesRead = _stream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
string msg = Encoding.UTF8.GetString(buffer, 0, bytesRead);
MessageReceived?.Invoke(msg);
}
}
}
catch (Exception ex)
{
ErrorOccurred?.Invoke($"Receive error: {ex.Message}");
}
}
public void SendMessage(string message)
{
if (_stream == null || !_stream.CanWrite)
{
ErrorOccurred?.Invoke("Stream not writable.");
return;
}
try
{
byte[] data = Encoding.UTF8.GetBytes(message + "\n");
_stream.Write(data, 0, data.Length);
_stream.Flush();
}
catch (Exception ex)
{
ErrorOccurred?.Invoke($"Send error: {ex.Message}");
}
}
public void Stop()
{
IsRunning = false;
_stream?.Close();
_client?.Close();
_listener?.Stop();
Console.WriteLine("Server stopped.");
}
}
}