Unable to connect Bluetooth device using c# - c#

I'm using 32 feet library to develop Bluetooth communication WPF app, and able to pair the device but not working to connect it and ended up with an exception like below.
Note: I've tried to connect the devices like my mobile and my PC, but both are giving the same errors as explained below.
I've seen somewhere about this issue and they mentioned like, this issue may be because of 32 feet library is not compatible with the Bluetooth device that I've in my PC.
But actually, I've tested this in some other PC's which are running with Windows 7 OS - 64 bit and getting the same error message.
Anyone help me out. Thank you.
Error Message: The requested address is not valid in its context ECD09F51114A:0000110100001000800000805f9b34fb
My code sample:
Guid uId = new Guid("0000110E-0000-1000-8000-00805f9b34fb");
bool receiverStarted = false;
private List<BluetoothDeviceInfo> deviceList;
private List<string> deviceNames;
private BluetoothDeviceInfo deviceInfo;
private string myPin = "1234";
private BluetoothClient sender;
private void BtnScan_Click(object sender, RoutedEventArgs e)
{
ScanAvailableDevices();
}
private void ScanAvailableDevices()
{
lstAvailableDevices.ItemsSource = null;
lstAvailableDevices.Items.Clear();
deviceList.Clear();
deviceNames.Clear();
Thread senderThread = new Thread(new ThreadStart(Scan));
senderThread.Start();
}
private void Scan()
{
UpdateStatus("Starting scan...");
sender = new BluetoothClient();
availableDevices = sender.DiscoverDevicesInRange();
UpdateStatus("Scan completed.");
UpdateStatus(availableDevices.Length.ToString() + " device(s) discovered");
foreach(BluetoothDeviceInfo device in availableDevices)
{
deviceList.Add(device);
deviceNames.Add(device.DeviceName);
}
UpdateAvailableDevices();
}
private void UpdateAvailableDevices()
{
Func<int> devicesDelegate = delegate ()
{
lstAvailableDevices.ItemsSource = deviceNames;
return 0;
};
Dispatcher.BeginInvoke((Action)(() =>
{
devicesDelegate.Invoke();
}));
}
private void PairDevice()
{
deviceInfo = deviceList[lstAvailableDevices.SelectedIndex];
if (CanPair())
{
UpdateStatus("Device paired..");
UpdateStatus("Starting to connect the device");
Thread senderThread = new Thread(new ThreadStart(SenderConnectThread));
senderThread.Start();
}
}
private bool CanPair()
{
if(!deviceInfo.Authenticated)
{
if(!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress,myPin))
{
return false;
}
}
return true;
}
private void LstAvailableDevices_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
deviceInfo = deviceList[lstAvailableDevices.SelectedIndex];
UpdateStatus(deviceInfo.DeviceName + " was selected, attempting connect");
if (CanPair())
{
UpdateStatus("Device paired..");
UpdateStatus("Starting connect thread");
Thread senderThread = new Thread(new ThreadStart(ClientConnectThread));
senderThread.Start();
}
else
{
UpdateStatus("Pair failed");
}
}
private void ClientConnectThread()
{
BluetoothClient sender = new BluetoothClient();
BluetoothAddress address = deviceInfo.DeviceAddress;
//sender.SetPin(deviceInfo.DeviceAddress, myPin);
var endPoint = new BluetoothEndPoint(address, uId);
sender.Connect(endPoint);
//Another way that I've tried
BluetoothClient client = new BluetoothClient();
UpdateStatus("Attempting connect");
//client.Connect(deviceInfo.DeviceAddress, uId);
client.BeginConnect(deviceInfo.DeviceAddress, uId, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient senderE = (BluetoothClient)result.AsyncState;
senderE.EndConnect(result);
Stream stream = senderE.GetStream();
while (true)
{
while (!ready) ;
byte[] message = Encoding.ASCII.GetBytes(txtSenderMessage.Text);
stream.Write(message, 0, message.Length);
}
}

There are libraries in UWP where you can easily make a connection between your desktop and other devices , you can easily handle the Bluetooth Adapter.

There are multiple downloads for 32 feet
Try these
Downloading
https://github.com/inthehand/32feet
Downloads are available here on the Downloads tab. Packages are also available at NuGet:-
InTheHand.Devices.Bluetooth - Modern (v4.x) - Preview NuGet version
32feet.NET - Legacy (v3.x) NuGet version
32feet.NET.Phone - Windows Phone NuGet version
InTheHand.Devices.Enumeration (Windows 8 / Windows Phone Device Pickers) NuGet version

Folks, I'm able to pair and connect it using the same application running in different PC and acting it as a server. Earlier I've tried this without having the same application running in the target PC and thus it's giving the error that I mentioned above.
Thanks guys for your time and support.

Related

Publish UWP Project

Hello I was trying to make two programs(server and client) on one machine. I did it with WPF and then I tried to do it with UWP, but I didn't succeed. The problem is that the listener in the server is waiting for a connection, but it never comes. This only happens when I try to do the connection from two separate projects.
If I do it in one project everything works fine. I saw somewhere that it is not possible to run the server and client form one machine with UWP, but the information was not so good explained.
So my question is, is it possible to make two separate projects with UWP for server and client on one computer and if not how can I test the programs(Do I need another computer to test it or there is some other way to do it).
And can someone tell me if there is a possible way to publish my project like the option from Console Applications, so that I can send my client to another computer maybe and try then. All I could find on the internet is how to publish your Apps to the Microsoft Store.
Server
public sealed partial class MainPage : Page
{
string port = "11000";
string hostv4 = "127.0.0.1";
StreamSocketListener server;
public MainPage()
{
InitializeComponent();
StartServer();
}
private async void StartServer()
{
HostName name = new HostName(hostv4);
server = new StreamSocketListener();
server.ConnectionReceived += this.Receive;
await server.BindEndpointAsync(name, port);
Chat.Content += ("server is listening...\n");//chat is a ScrollViewer where I show the received messsges
}
private async void Receive(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
string receivedMsg;
using (var sr = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
{
receivedMsg = await sr.ReadLineAsync();
}
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("server received the request: \"{0}\"\n", receivedMsg)));
}
}
Client
public sealed partial class MainPage : Page
{
string port = "11000";
string hostv4 = "127.0.0.1";
StreamSocket client;
public MainPage()
{
this.InitializeComponent();
Connect();
}
private async void Connect()
{
client = new StreamSocket();
HostName name = new HostName(hostv4);
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("client trying to connect...\n")));
await client.ConnectAsync(name, port);
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("client connected\n")));
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string request = Input.Text; //Input is the name of my TextBox
using (Stream outputStream = client.OutputStream.AsStreamForWrite())
{
using (var sw = new StreamWriter(outputStream))
{
await sw.WriteLineAsync(request);
await sw.FlushAsync();
}
}
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("client sent request: {0}\n", request)));
}
I also have enabled Internet(Client & Server) and Private Networks(Client & Server) from the Capabilities

C# TCPListener keep listening after application shutdown only for the first time

I have an issue with my application,
I have a TCPListener which listen let's say on port 14000
After the application is being closed I can see on the CMD that the listener is still listening.
At the second run of the application as expected I cant start the listener on the same port (14000) because it is already taken, I am changing the application port to 15000 on the second running, work wonderful and the listener is being CLOSED after the application is being shut down,
I assume that on the first run, the first listener on port 14000 stays open after the app is dead, on the second run the application closed/open the listener on port 15000 very well, why is this happen? I thought maybe it is about the port 14000 I've switched the orders of the opening ports (first opened 15000) and saw that the 15000 stays open and the 14000 (on the second run) closed and open correctly, Why at the first run the listener not being closed??
The code to my server:
class Server : IDisposable
{
private const int TIMER_PERIOD = 60 * 1000; // ms
private string servePort;
private string serverIP;
byte[] DataReceived = new byte[1024];
Action<string> MssageReceiveCallback;
private bool isListening = false;
static Timer serverTimer = null;
private TcpListener _Server;
private Dictionary<int, TcpClient> clientsList = new Dictionary<int, TcpClient>();
private bool serverListening = true;
private static int ClientInstance = 0;
public Server(string _serverIP, string _serverPORT, Action<string> messageReceiveCallback)
{
serverIP = _serverIP;
servePort = _serverPORT;
MssageReceiveCallback = messageReceiveCallback;
// InitilizeServer();
}
private void InitilizeServer()
{
_Server = new TcpListener(IPAddress.Parse(serverIP), int.Parse(servePort));
// if (serverTimer == null)
// serverTimer = new Timer(new TimerCallback(OnTimerCallback), null, TIMER_PERIOD, TIMER_PERIOD);
Task.Run(() =>
{
try
{
_Server.Start();
while (_Server != null)
{
TcpClient tcpClient;
try
{
tcpClient = _Server.AcceptTcpClient();
}
catch
{
continue;
}
Task.Run(() =>
{
ClientInstance++;
int currentinstance = ClientInstance;
clientsList.Add(currentinstance, tcpClient);
try
{
while (tcpClient.Connected && serverListening)
{
if (tcpClient.GetStream().DataAvailable)
{
int actualBufferlength = tcpClient.GetStream().Read(DataReceived, 0, DataReceived.Length);
byte[] data = new byte[actualBufferlength];
Buffer.BlockCopy(DataReceived, 0, data, 0, actualBufferlength);
string asciiMessage = Encoding.ASCII.GetString(data);
MssageReceiveCallback(asciiMessage);
}
else
{
Thread.Sleep(5);
}
}
}
catch (Exception ex)
{
}
finally
{
clientsList[currentinstance].Close();
clientsList.Remove(currentinstance);
}
});
}
}
catch (Exception ex)
{
}
});
}
public void StartServer()
{
InitilizeServer();
isListening = true;
}
public void SendMessage(string msg)
{
byte[] data = ASCIIEncoding.ASCII.GetBytes(msg);
foreach (TcpClient client in clientsList.Values)
{
client.GetStream().Write(data, 0, data.Length);
}
}
public void Dispose()
{
serverListening = false;
foreach (var item in clientsList.Values)
{
if (item.Connected)
item.Close();
}
_Server.Server.Close();
}
}
UPDATE:
I've check in TCPView to see which application the listener bind to and found this:
It looks like the listener available for un exist process
The biggest problem here, I think (I've pointed out other problems in the comments) is that TCP shutdown requires network communications and by default prevents socket reuse for a period of time.
The function you need to get to is Socket.SetSocketOption, specifically the ReuseAddress option. You should be able to get at it via the Server property on the TcpListener. Pay attention that it needs to be done before you actually start the listener listening.
You could try putting:
_Server.Server =null;
After close.

Unity UDPClient not receiving broadcast on android build. Editor works. Targeting phone IP works

I'm using a very standard UDP client code. It works fine in Unity Editor. But when build to android phone, I got no response. The sender is a well tested windows program (I also tried other udp senders from online) and I'm only building a receiver client. The sender is in UDP broadcast mode and is sending to 255.255.255.255:60888. It works fine In Unity but when build on the phone, it prints nothing. However toggling the sender to direct ip of the phone, it works fine and prints out the data. I have tried putting the receive EndPoint with IPAddress.Broadcast/Any/255.255.255.255/192.168.1.255.
They all work in editor but none works in android. Tried other ports too and same. I have read something about multicast lock from android and tried, not working.
Some suggested HTC is not receiving broadcast (hardware specific). However the phone (not HTC) has a built-in video player that can be triggered buy a udp broadcast. My sender can send through and pull up the player. I think that is a native app and using java Datagram Socket. I wonder if this is a Unity bug or firmware bug.
Unity version tried: 5.6.3, 2017.2.1, 2017.4.2.
Code is below:
public class UDPClient : MonoBehaviour {
Thread receiveThread;
int remotePort = 60888;
int clientPort = 60666;
UdpClient _udpClient;
// Use this for initialization
void Start ()
{
if (Application.isEditor)
{
Application.runInBackground = true;
}
_udpClient = new UdpClient(clientPort);
_udpClient.Client.ReceiveBufferSize = 1024;
receiveThread = new Thread(new ThreadStart(ReceiveTask));
receiveThread.Start();
}
void ReceiveTask()
{
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Broadcast, 0);
while (true)
{
try
{
byte[] data = _udpClient.Receive(ref remoteEP);
if (data != null && data.Length > 0)
{
Debug.Log("received: " + remoteEP.ToString() + " length: " + data.Length + " data: " + data[1].ToString());
}
else {
Thread.Sleep(10);
}
}
catch (System.Exception ex)
{
throw (ex);
}
}
}
void CleanUp()
{
Debug.Log("cleanning Thread");
if (receiveThread != null)
{
receiveThread.Abort();
}
receiveThread = null;
_udpClient.Close();
_udpClient = null;
}
void OnApplicationQuit()
{
CleanUp();
}
}

Arduino and C# Serial Port "Crash"

I am trying to create a communication between an Arduino Leonardo and C#.
Just now, the Arduino's software sends a simple message (in loop) on the serial port:
void setup() {
Serial.begin(9600);
analogReference(INTERNAL);
}
void loop() {
Serial.println("test");
delay(500);
}
C# try only to read these messages and print them on the shell:
public class Program
{
private SerialPort mySerialPort;
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine("PORTS: " + String.Join(" ", p.getSerialPortsList())+ ", enter to start.");
Console.Read();
p.SerialRead("COM6");
}
public String[] getSerialPortsList()
{
string[] ports = SerialPort.GetPortNames();
return ports;
}
public void SerialRead(String com)
{
mySerialPort = new SerialPort(com, 9600, Parity.None, 8, StopBits.One);
Console.Read();
Console.WriteLine("Incoming Data:");
SerialRead sr = new SerialRead();
Thread rs = new Thread(sr.StartRead);
sr.SetMySerialPort(mySerialPort);
rs.Start();
while (!rs.IsAlive);
Console.Read();
sr.SetSuspendThread(true);
rs.Join();
}
}
public class SerialRead
{
private Boolean suspendThread = false;
SerialPort mySerialPort;
public void StartRead()
{
mySerialPort.Open();
Thread.Sleep(500);
int i = 0;
while (!suspendThread)
{
i++;
Console.WriteLine(i + ": " + mySerialPort.ReadLine());
Thread.Sleep(500);
}
}
public void SetMySerialPort(SerialPort mysp){ mySerialPort = mysp; }
public void SetSuspendThread(Boolean a){ suspendThread = a; }
}
The output of this C# software depends. If I use the serial monitor on the Arduino IDE, then I receive the string's stream correctly (one each 500ms).
Otherwise, the C# software freezes. Sometimes, I receive a couple of strings as we can see this figure; but almost all time, the software does not give any string, as we can see here. After that the software freezes (thus, if I press enter the shell does not response).
Can you suggest a solution in order to get a fluent flow of string, and -as a consequence- read each message sent by Arduino on the serial port?
I am using Window 10 x64 as OS and the COM6 (it is an USB 2.0).
I found the solution and I share it in order to help people with the same problem.
C# does not activate as default the RTS and the DTR serial port.
Thus, adding
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
after the serial port declaration, everything works fine.
This is a really good example:
Serial Port Polling and Data handling
The Serial Port got an event called DataRecived, so you dont have to sleep your thread.
Something like this:
serialPort.DataReceived +=SerialPortDataReceived;
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine(serialPort.ReadLine());
}

TCPIP connection in c# and data sending/receiving in another threads

I have a problem with my TCPIP connection Form programm.
I have a code, where I'm trying to send and receive some data from server.
The main problem of my app is how to reconcile some threads:
myListenThread - to listening data from server
myReadStreamThread - to read data from server
System.Threading.Thread - main thread eg. to write data to server
captureThread - to do another things like capturing images from camera
Part of my code:
private void buttonConnect_Click(object sender, EventArgs e)
{
try
{
Connect();
Connected = true;
this.myListenThread = new Thread(new ThreadStart(Listen));
this.myListenThread.Start();
}
catch
{
MessageBox.Show("Invalid host! Try again.");
}
}
private void Listen()
{
this.myReadStreamThread = new Thread(new ThreadStart(ReadStream));
this.myReadStreamThread.Start();
while (Connected)
{
if (!myReadClient.Connected)
{
Connect();
}
}
}
private void Connect()
{
IPAddress IP = IPAddress.Parse(textboxIP.Text);
int PORT = Convert.ToInt32(textboxPORT.Text);
this.myReadClient = new TcpClient();
this.myReadClient.Connect(IP, PORT);//SOMETIMES HERE'S AN ERROR
this.myStream = this.myReadClient.GetStream();
Properties.Settings.Default.IP = Convert.ToString(IP);
Properties.Settings.Default.PORT = Convert.ToString(PORT);
Properties.Settings.Default.Save();
}
private void ReadStream()
{
while (true)
{
try
{
this.myReadBuffer = new byte[this.myReadClient.ReceiveBufferSize];
this.myBufferSize = myStream.Read(myReadBuffer, 0, this.myReadClient.ReceiveBufferSize);
if (myBufferSize != 0)
{
this.myString = Encoding.ASCII.GetString(myReadBuffer);
//myDelegate myDel;
//myDel = new myDelegate(Print);
//richtextboxRead.Invoke(myDel);
}
}
catch
{
break;
}
}
}
All is working correct when I'm connecting to server, but when I want to send some string the problem appears because of threads.
I decided to send string, by clicking Button3 and waiting until I receive string "1" from server using while loop:
private void button3_Click(object sender, EventArgs e)
{
this.captureThread = new Thread(new ThreadStart(() => this.newGame()));
this.captureThread.Start();
}
private bool newGame()
{
string command = "12345abc";
if (Connected)
{
WriteStream(command);
}
while (myBufferSize == 0 && myString !="1") { }
Thread.Sleep(2000);
...//doing other things
}
private void WriteStream(string command)
{
Connect();
this.myWriteBuffer = Encoding.ASCII.GetBytes(command);
this.myStream.Write(this.myWriteBuffer, 0, command.Length);
}
And the problem with connection and data send/receive problem appears, when it should write my string "command" - it doesn't react. MyBufferSize is always 0 and myString is always null. Sometimes an Error about connection appears when I click Button3 (assigned in code). I think it is because in captureThread I can't see any data from another threads. How to solve it?

Categories