I am developing code in C# to communicate with a custom Bluetooth device. The code I use to connect to the device essentially looks like this:
BluetoothDeviceInfo device_info = new BluetoothDeviceInfo(BluetoothAddress.Parse(address_str));
try
{
BluetoothClient connection = new BluetoothClient();
connection.Connect(device_info.DeviceAddress, BluetoothService.SerialPort);
if (connection.Connected)
{
...
}
else
{
...
}
}
catch (Exception e)
{
...
}
The problem is that the Connect call often times out after about 5s. Sometimes it succeeds after about 3s and I have reason to believe that a connection could be established successfully if I allowed more time. However, I have nowhere set this timeout of 5s. I just call the Connect method and it times out at some point.
Is there a way to configure this timeout somewhere in 32feet?
Related
First, I have extensively read through Autoconnect to MS Wireless display on Windows 10 and tried basically every solution. (I did technically get the AutoHotKey solution working, and in fact did that before even researching. But, I feel like that's kind of unprofessional and surely there is some API that can connect to this thing.) After going through all of this, I just started reading through the different namespaces. Finally, I found Windows.Devices.WiFiDirect. This gave me the most progress I've been able to get, which is, it begins to connect and says so on screen, then an exception stating that the device is unreachable occurs. Very infuriating.
Can anyone explain exactly what is happening here? It seems like this should be the proper way to connect my screen to this device, but it is just not working. Code below, it's pretty short and straightforward.
Edit:
Based on Roy Li's suggestion, I attempted to use a different overload of the socket.ConnectAsync method. This actually did have an effect but I am still receiving an exception, although a different one. The method now attempts to connect for longer but still fails out, this time with a "connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond" exception. Could this mean there is some sort of secret handshake that Window's OS is using when connecting to this device? If so, this might be a dead end. The code has been updated below.
static async Task Main()
{
string id = null;
string prefix = "MicrosoftDisplayAdapter";
WiFiDirectDevice device;
StreamSocket socket = new StreamSocket();
try
{
DeviceInformationCollection devInfoCollection = await DeviceInformation.FindAllAsync(WiFiDirectDevice.GetDeviceSelector());
foreach (DeviceInformation devInfo in devInfoCollection)
{
if (devInfo.Name.StartsWith(prefix))
{
id = devInfo.Id;
}
}
device = await WiFiDirectDevice.FromIdAsync(id);
var endpointPairCollection = device.GetConnectionEndpointPairs();
await socket.ConnectAsync(endpointPairCollection[0].RemoteHostName, "50001"); //This line begins connecting to the display but ultimately fails
}
catch (Exception e)
{
//device unreachable exception
}
}
I finally found something along the lines of what I need. I came across https://social.msdn.microsoft.com/Forums/en-US/7608d127-d864-436a-802e-472fd55cc02c/use-projectionmanager-from-net-framework?forum=csharpgeneral, which gave me a way to cast/project to the Microsoft Display Adapter. As the link states, I do get a "Catastrophic Error" but it does make the connection and keep it, anyway. What my code ended up looking like is below:
static async Task Main()
{
string prefix = "MicrosoftDisplayAdapter";
DeviceInformation displayAdapter = null;
try
{
//Get projection devices
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(ProjectionManager.GetDeviceSelector());
foreach (DeviceInformation device in devices)
{
if (device.Name.StartsWith(prefix))
{
displayAdapter = device;
}
}
//Start projection. This throws an error but works without issue.
await ProjectionManager.StartProjectingAsync(0, 0, displayAdapter);
}
catch (Exception e)
{
//Ignore this error
if (e.Message.StartsWith("Catastrophic"))
{
//Change display to use secondary only
Process proc = new Process();
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = #"C:\Windows\Sysnative\DisplaySwitch.exe";
proc.StartInfo.Arguments = "/external";
proc.Start();
proc.WaitForExit();
}
else
{
Console.WriteLine(e);
}
}
}
Hey, I have a Problem with the Windows 10 UWP API.
I'm developing a Windows 10 UWP App and need to connect to a Chromecast. I'm using SharpCaster for this. But when I open a connection to a Chromecast and close it again later on, it is not possible to connect to a Chromecast again. The socket to the Chromecast opens again, but when trying to write to it, I get the following exception:
A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
This even happens when I turn the Chromecast off while disconnected. I disconnect the Chromecast with this Method:
public void Disconnect()
{
_running = false;
_socket.InputStream.Dispose();
_socket.OutputStream.Dispose();
_socket.Dispose();
}
The method is not found in the Library, I have written it myself. Setting _running to false stops all the loops for pinging, etc...
The socket is created with this code:
_socket = new StreamSocket().ConfigureForChromecast();
await _socket.ConnectAsync(new HostName(uri.Host), ChromecastPort, SocketProtectionLevel.Tls10);
The extension ConfigureForChromecast() looks like this:
public static StreamSocket ConfigureForChromecast(this StreamSocket socket)
{
//Chromecast is not using trusted certificate so ignoring errors caused by that
socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
socket.Control.OutboundBufferSizeInBytes = 2048;
socket.Control.KeepAlive = true;
socket.Control.QualityOfService = SocketQualityOfService.LowLatency;
return socket;
}
Finally, the messages are written to the socket with
internal async Task Write(byte[] bytes)
{
try
{
var buffer = CryptographicBuffer.CreateFromByteArray(bytes);
await _socket.OutputStream.WriteAsync(buffer);
}
catch (Exception e)
{
Debugger.Break();
}
}
And that is the point where the exception occurs. When connecting the first time, it works perfectly, but to connect a second time, I have to restart the whole app. Any ideas why?
I am using a driver which is in following link for c#
https://github.com/datastax/csharp-driver
It seems really good. But problem is time issue. I am waiting to connect or execute somequery longer than 1 minute. I tried cassandraemon,it connected in 1-2 seconds. But It dont like this library much and want to use another one.
So here is my connection code.. where is my mistake?
try
{
cluster = Cluster.Builder()
// .AddContactPoints(nodes)
.AddContactPoint("xx.xx.xx.xx")
.Build();
session = cluster.Connect();
}
catch (Exception e)
{
return false;
}
return true;
I have written Windows service, which perform Modbus WriteMultipleRegisters function call over TCP using NModbus library to 3-party devices every 10 minutes (ticks of System.Threading.Timer).
Occasionally this connection hang up open usually during network problems. As the device accepts only one Modbus connection at time and others are refused, connection during all next ticks fail with SocketException - ConnectionRefused.
But the device automatically closes connections which don't respond after short time. Something must keep connection open at my side even for two days. What's more when my Service is restarted, everything is fine again. So there is definitely some forgotten open connection. But I didn't manage to reproduce this bug in dev, so I don't where/when.. connection hang up. I only know that next connection is refused.
I do the modbus function call with this part of code:
using (TcpClient client = new TcpClient(device.ip, 502))
{
using (Modbus.Device.ModbusIpMaster master = Modbus.Device.ModbusIpMaster.CreateIp(client))
{
master.WriteMultipleRegisters(500, new ushort[] { 0xFF80 });
}
}
device.ip is string containing IP address of device - it's correct, confirmed from SocketException details.
As I'm using using statement dispose is called on both objects.
I have looked trough NModbus source code and everything is disposed correctly.
Any idea how its possible that with this code connection is not closed?
I agree with nemec. If you review the documentation for TcpClient.Dispose if does not specifically mention closing the connection. It frees managed and unmanaged resources by default, but it may not correctly tear down the connection.
Try changing your code to:
using (TcpClient client = new TcpClient(device.ip, 502))
{
try
{
using (Modbus.Device.ModbusIpMaster master = Modbus.Device.ModbusIpMaster.CreateIp(client))
{
master.WriteMultipleRegisters(500, new ushort[] { 0xFF80 });
}
}
catch(Exception e)
{
// Log exception
}
finally
{
client.Close();
}
}
That way you are doing a clean close before dispose and it should clean up even if the Modbus protocol throws some kind of exception.
did you play with TcpClient.LingerState Property
defualt setting could cause problems with resetting winsock
check it out
http://msdn.microsoft.com/pl-pl/library/system.net.sockets.tcpclient.lingerstate%28v=vs.110%29.aspx
This is not an answer, but a comment with code. We have this same issue on some of our installed computers, but not all of them. The issue itself is also very intermittent, sometimes going months without happening. I am hoping someone can find an answer. Here is our brute force destroy / reconnect code that does not work:
try
{
try
{
try
{
// Close the stream
var stream = _tcpClient.GetStream();
if (stream != null)
stream.Close();
}
catch { }
try
{
// Close the socket
if (_tcpClient.Client != null)
_tcpClient.Client.Close();
}
catch { }
// Close the client
_tcpClient.Close();
_tcpClient = null;
}
catch { }
if (_device != null)
{
_device.Dispose();
_device = null;
}
}
catch { }
System.Threading.Thread.Sleep(1000);
I have a WCF windows service which exposes an API to a windows form application.
API connection to client:
var serviceType = typeof(Mail2SmsServerApi);
var uri = new Uri("http://localhost:8000/");
host = new ServiceHost(serviceType, new[] { uri });
var behaviour = new ServiceMetadataBehavior() { HttpGetEnabled = true };
host.Description.Behaviors.Add(behaviour);
host.AddServiceEndpoint(serviceType, new BasicHttpBinding(), "Hello");
host.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), "mex");
host.Open();
My ServiceContract:
[ServiceContract]
public class Mail2SmsServerApi
{
[OperationContract]
public string Imei()
{
try
{
GSMHandler gsm = new GSMHandler();
return gsm.GetImei();
}
catch (Exception ex)
{
LogText.Error("API GetImei(), exception: " + ex.ToString());
return null;
}
}
}
My GSMHandler class and method:
public bool OpenConnection()
{
modem = new GsmPhone(_comport, _baudrate, _timeout);
if (!comm.IsConnected())
{
try
{
modem.Open();
return true;
}
catch (Exception ex)
{
LogText.Debug("OpenConnection(), exception" + ex.ToString());
return false;
}
}
else
{
try
{
modem.Close();
modem.Open();
return true;
}
catch (Exception ex)
{
LogText.Debug("OpenConnection(), exception" + ex.ToString());
return false;
}
}
}
public string GetImei()
{
string imei = "";
try
{
imei = modem.RequestSerialNumber();
LogText.Debug("IMEI:" + _IMEI);
return imei;
}
catch (Exception ex)
{
LogText.Error("Error caught in GetImei(), exception: " + ex.ToString());
return imei;
}
}
When the OnStart method in my service are called, I'm opening a connection to the modem with :
gsm = new GSMHandler();
gsm.OpenConnection();
When OnStop are called, I'm stopping it with:
gsm = new GSMHandler();
gsm.OpenConnection();
My idea was that, with this design the service would handle the communication and the client and service could interact with the modem without getting a com port not open or com port busy problem. This is obviously wrong, since I'm not able to return values from the modem this way. It has to be a design failure from my side.
What I'm trying to achieve is that a client can talk to the modem through the service, and that not both of them make a direct connection to the modem. But that the service can handle the opening and closing of connection to modem, and pass commands in to the modem from the client...
So my question is, what's the appropriate way to design such a scenario? I'm not asking for the code, just how It's usual to design it...
I'm appreciating all answers :) Thanks in advance!
I think you might have much more success if you performed the interaction with the modem as a single unit of work.
For example, design your service such that the caller calls a single method to send a text message, providing all of the necessary detail in the interface call.
The service method then performs all of the tasks necessary to open the modem, send the text message, and close the modem, in a single unit of work.
This design will allow you to ensure that the modem is always opened and closed correctly and completely within the unit of work instead of waiting for additional commands through the service that may never arrive.
Also, this design will allow you to eventually correctly support multiple modems, which your current design will not. You could have a modem pool and when a new request arrives, you could obtain an available modem from the pool, perform the unit of work, then return the modem to the pool on completion, even in a failure situation.