本文整理汇总了C#中InTheHand.Net.Sockets.BluetoothClient.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# BluetoothClient.Connect方法的具体用法?C# BluetoothClient.Connect怎么用?C# BluetoothClient.Connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类InTheHand.Net.Sockets.BluetoothClient
的用法示例。
在下文中一共展示了BluetoothClient.Connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MakeConnection
public static void MakeConnection(BluetoothAddress btAddress)
{
var serviceClass = BluetoothService.SerialPort;
if (_cli != null)
{
_cli.Close();
}
_cli = new BluetoothClient();
var bluetoothDeviceInfos = _cli.DiscoverDevices();
var deviceInfos = bluetoothDeviceInfos.ToList();
BluetoothDeviceInfo device = null;
foreach (var bluetoothDeviceInfo in deviceInfos)
{
var scannedDeviceAddress = bluetoothDeviceInfo.DeviceAddress;
if (scannedDeviceAddress == btAddress)
{
device = bluetoothDeviceInfo;
}
}
if (device == null)
{
return;
}
var ep = new BluetoothEndPoint(device.DeviceAddress, serviceClass);
try
{
if (!device.Connected)
{
_cli.Connect(ep);
}
}
catch(System.Net.Sockets.SocketException e)
{
_cli.Close();
_isConnected = false;
return;
}
_isConnected = true;
}
示例2: BluetoothConnect
private void BluetoothConnect(BluetoothAddress addr)
{
BluetoothClient btClient = new BluetoothClient();
try
{
btClient.Connect(addr, OurServiceClassId);
var peer = btClient.GetStream();
SetConnection(peer, true, btClient.RemoteEndPoint);
ThreadPool.QueueUserWorkItem(ReadMessagesToEnd_Runner, peer);
}
catch (SocketException ex)
{
// Try to give a explanation reason by checking what error-code.
// http://32feet.codeplex.com/wikipage?title=Errors
// Note the error codes used on MSFT+WM are not the same as on
// MSFT+Win32 so don't expect much there, we try to use the
// same error codes on the other platforms where possible.
// e.g. Widcomm doesn't match well, Bluetopia does.
// http://32feet.codeplex.com/wikipage?title=Feature%20support%20table
string reason;
switch (ex.ErrorCode)
{
case 10048: // SocketError.AddressAlreadyInUse
// RFCOMM only allow _one_ connection to a remote service from each device.
reason = "There is an existing connection to the remote Chat2 Service";
break;
case 10049: // SocketError.AddressNotAvailable
reason = "Chat2 Service not running on remote device";
break;
case 10064: // SocketError.HostDown
reason = "Chat2 Service not using RFCOMM (huh!!!)";
break;
case 10013: // SocketError.AccessDenied:
reason = "Authentication required";
break;
case 10060: // SocketError.TimedOut:
reason = "Timed-out";
break;
default:
reason = null;
break;
}
reason += " (" + ex.ErrorCode.ToString() + ") -- ";
//
var msg = "Bluetooth connection failed: " + ex;
msg = reason + msg;
AddMessage(MessageSource.Error, msg);
System.Windows.MessageBox.Show(msg);
}
catch (Exception ex)
{
var msg = "Bluetooth connection failed: " + ex;
AddMessage(MessageSource.Error, msg);
System.Windows.MessageBox.Show(msg);
}
}
示例3: search
private void search()
{
try
{
Guid uuid = BluetoothService.L2CapProtocol;
BluetoothDeviceInfo bdi;
BluetoothAddress ba;
byte tmp;
bool found = false;
int discarded;
bc = new BluetoothClient();
bc.InquiryLength = new TimeSpan(0, 0, 0, Int32.Parse(osae.GetObjectPropertyValue(pName, "Discover Length").Value), 0);
nearosaeDevices = bc.DiscoverDevices(10, false, false, true);
for (int j = 0; j < nearosaeDevices.Length; j++)
{
string addr = nearosaeDevices[j].DeviceAddress.ToString();
Object obj = osae.GetObjectByAddress(addr);
if (obj == null)
{
if (osae.GetObjectPropertyValue(pName, "Learning Mode").Value == "TRUE")
{
osae.ObjectAdd(nearosaeDevices[j].DeviceName, nearosaeDevices[j].DeviceName, "BLUETOOTH DEVICE", nearosaeDevices[j].DeviceAddress.ToString(), "", true);
osae.ObjectPropertySet(nearosaeDevices[j].DeviceName, "Discover Type", "0");
logging.AddToLog(addr + " - " + nearosaeDevices[j].DeviceName + ": added to OSA", true);
}
}
}
List<OSAEObject> objects = osae.GetObjectsByType("BLUETOOTH DEVICE");
foreach (OSAEObject obj in objects)
{
found = false;
string address = obj.Address;
byte[] byteArray = HexEncoding.GetBytes(address, out discarded);
tmp = byteArray[0];
byteArray[0] = byteArray[5];
byteArray[5] = tmp;
tmp = byteArray[1];
byteArray[1] = byteArray[4];
byteArray[4] = tmp;
tmp = byteArray[2];
byteArray[2] = byteArray[3];
byteArray[3] = tmp;
ba = new BluetoothAddress(byteArray);
bdi = new BluetoothDeviceInfo(ba);
logging.AddToLog("begin search for " + address, false);
for (int j = 0; j < nearosaeDevices.Length; j++)
{
if (nearosaeDevices[j].DeviceAddress.ToString() == address)
{
found = true;
logging.AddToLog(address + " - " + obj.Name + ": found with DiscoverDevices", false);
}
}
if (!found)
{
logging.AddToLog(address + " - " + obj.Name + ": failed with DiscoverDevices", false);
}
try
{
if (!found && (Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 2 || Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 0))
{
logging.AddToLog(address + " - " + obj.Name + ": attempting GetServiceRecords", false);
bdi.GetServiceRecords(uuid);
found = true;
logging.AddToLog(address + " - " + obj.Name + " found with GetServiceRecords", false);
}
}
catch (Exception ex)
{
logging.AddToLog(address + " - " + obj.Name + " failed GetServiceRecords. exception: " + ex.Message, false);
}
try
{
if (!found && (Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 3 || Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 0))
{
logging.AddToLog(address + " - " + obj.Name + ": attempting Connection", false);
//attempt a connect
BluetoothEndPoint ep;
ep = new BluetoothEndPoint(bdi.DeviceAddress, BluetoothService.Handsfree);
//MessageBox.Show("attempt connect: " + pairedDevices[i].DeviceAddress);
bc.Connect(ep);
logging.AddToLog(address + " - " + obj.Name + " found with Connect attempt", false);
bc.Close();
found = true;
}
}
//.........这里部分代码省略.........
示例4: GetImages
public static void GetImages(BluetoothEndPoint endpoint, Color tagColor)
{
InTheHand.Net.Sockets.BluetoothClient btc = new InTheHand.Net.Sockets.BluetoothClient();
btc.Connect(endpoint);
var nws = btc.GetStream();
byte[] emptySize = BitConverter.GetBytes(0); //
if (BitConverter.IsLittleEndian) Array.Reverse(emptySize); // redundant but usefull in case the number changes later..
nws.Write(emptySize, 0, emptySize.Length); // write image size
int imgCount = GetImgSize(nws);
nws = btc.GetStream();
for (int i = 0; i < imgCount; i++)
{
MemoryStream ms = new MemoryStream();
int size = GetImgSize(nws);
if (size == 0) continue;
byte[] buffer = new byte[size];
int read = 0;
while ((read = nws.Read(buffer, 0, buffer.Length)) != 0)
{
ms.Write(buffer, 0, read);
}
SurfaceWindow1.AddImage(System.Drawing.Image.FromStream(ms), tagColor);
}
}
示例5: connectToDeviceWithoutPairing
/// <summary>
/// Attempt to connect to the BluetoothDevice, without trying to pair first.
/// </summary>
/// <param name="device"></param>
/// <returns></returns>
public static async Task<Boolean> connectToDeviceWithoutPairing(BluetoothDevice device) {
BluetoothEndPoint endPoint = new BluetoothEndPoint(device.btDeviceInfo.DeviceAddress, BluetoothService.SerialPort);
BluetoothClient client = new BluetoothClient();
if (!device.Authenticated) {
return false;
}
else {
try {
client.Connect(endPoint);
if (devicesStreams.Keys.Contains(device)) {
devicesStreams.Remove(device);
}
devicesStreams.Add(device, client.GetStream());
if (devicesClients.Keys.Contains(device)) {
devicesClients.Remove(device);
}
devicesClients.Add(device, client);
}
catch (Exception ex) {
//System.Console.Write("Could not connect to device: " + device.DeviceName + " " + device.DeviceAddress);
return false;
}
return true;
}
}
示例6: OpenAsync
public Task OpenAsync()
{
return Task.Run( () =>
{
_tokenSource = new CancellationTokenSource();
_client = new BluetoothClient();
_client.Connect( _deviceInfo.DeviceAddress, BluetoothService.SerialPort );
_networkStream = _client.GetStream();
Task.Factory.StartNew( CheckForData, _tokenSource.Token, TaskCreationOptions.LongRunning,
TaskScheduler.Default );
} );
}
示例7: SendBluetooth
public static void SendBluetooth(BluetoothEndPoint endpoint, BitmapSource bms)
{
InTheHand.Net.Sockets.BluetoothClient btc = new InTheHand.Net.Sockets.BluetoothClient();
btc.Connect(endpoint);
byte[] img = BmSourceToByteArr(bms);
var nws = btc.GetStream();
byte[] imgSize = BitConverter.GetBytes(img.Length);
if (BitConverter.IsLittleEndian) Array.Reverse(imgSize);
nws.Write(imgSize, 0, imgSize.Length); // write image size
nws.Write(img, 0, img.Length); // Write image
nws.Flush();
}
示例8: Send
/// <summary>
/// Sends the data to the Receiver.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="content">The content.</param>
/// <returns>If was sent or not.</returns>
public async Task<bool> Send(Device device, string content)
{
if (device == null)
{
throw new ArgumentNullException("device");
}
if (string.IsNullOrEmpty(content))
{
throw new ArgumentNullException("content");
}
// for not block the UI it will run in a different threat
var task = Task.Run(() =>
{
using (var bluetoothClient = new BluetoothClient())
{
try
{
var ep = new BluetoothEndPoint(device.DeviceInfo.DeviceAddress, _serviceClassId);
// connecting
bluetoothClient.Connect(ep);
// get stream for send the data
var bluetoothStream = bluetoothClient.GetStream();
// if all is ok to send
if (bluetoothClient.Connected && bluetoothStream != null)
{
// write the data in the stream
var buffer = System.Text.Encoding.UTF8.GetBytes(content);
bluetoothStream.Write(buffer, 0, buffer.Length);
bluetoothStream.Flush();
bluetoothStream.Close();
return true;
}
return false;
}
catch
{
// the error will be ignored and the send data will report as not sent
// for understood the type of the error, handle the exception
}
}
return false;
});
return await task;
}
示例9: DoConnect
private async void DoConnect(Action<IConnectedSphero> onSuccess, Action<Exception> onError)
{
try
{
var serviceClass = BluetoothService.SerialPort;
var ep = new BluetoothEndPoint(PeerInformation.DeviceAddress, serviceClass);
var client = new BluetoothClient();
client.Connect(ep);
var stream = client.GetStream();
onSuccess(new ConnectedSphero(PeerInformation, stream));
}
catch (Exception exception)
{
onError(exception);
}
}
示例10: start
public void start(BluetoothDeviceInfo serverToSend)
{
try
{
if (serverToSend.Authenticated)
{
bluetoothClient = new BluetoothClient();
bluetoothClient.Connect(serverToSend.DeviceAddress, UUID);
Console.WriteLine("Conexão Estabelecida!");
Thread thread = new Thread(new ThreadStart(threadClientBluetooth));
thread.Start();
}
else
{
Console.WriteLine("Servidor Não Autenticado!");
}
}
catch (Exception e)
{
Console.WriteLine("Erro: " + e.ToString());
}
}
示例11: Initialize
public override void Initialize()
{
var cli = new BluetoothClient();
BluetoothDeviceInfo[] peers = cli.DiscoverDevices();
BluetoothDeviceInfo device;
if (string.IsNullOrEmpty(_address))
device = peers.FirstOrDefault();
else
{
device = peers.FirstOrDefault((d) => d.DeviceAddress.ToString() == _address);
}
if (device != null)
{
BluetoothAddress addr = device.DeviceAddress;
Guid service = device.InstalledServices.FirstOrDefault();
cli.Connect(addr, service);
var stream = cli.GetStream();
_bwriter = new StreamWriter(stream);
}
Initialized = true;
}
示例12: detector_DoWork
private void detector_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (_bluetoothStream != null)
_bluetoothStream.Close();
_client = new BluetoothClient();
BluetoothDeviceInfo gadgeteerDevice = null;
while (gadgeteerDevice == null)
{
gadgeteerDevice = _client.DiscoverDevices().Where(d => d.DeviceName == "Gadgeteer")
.FirstOrDefault();
UpdateStatus("Still looking...");
}
if (gadgeteerDevice != null)
{
_client.SetPin(gadgeteerDevice.DeviceAddress, "1234");
_client.Connect(gadgeteerDevice.DeviceAddress, BluetoothService.SerialPort);
_bluetoothStream = _client.GetStream();
e.Result = true;
}
else
{
e.Result = false;
}
}
catch (Exception)
{
e.Result = false;
}
}
示例13: SendZip
private void SendZip()
{
Logger.LogEvent(true, "MainViewModel.SendZip 200");
this.wasCanceled = false;
this.IsScanning = true;
this.Status = "Trying to establish connection and transfer file..";
var success = false;
Exception lastEx = null;
if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
{
BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
}
Logger.LogEvent(true, "MainViewModel.SendZip 201");
Task.Factory.StartNew(() =>
{
if (this.selectedDevice != null)
{
var bluetoothClient = new BluetoothClient();
NetworkStream bluetoothStream = null;
this.connectionIntervalFinished = false;
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += this.OnTimedEvent;
// Set the Interval to 20 second.
aTimer.Interval = 20000;
aTimer.Start();
var device = this.realDevices.FirstOrDefault(x => x.DeviceAddress.Sap == this.selectedDevice.DeviceAddressSap);
Logger.LogEvent(true, "MainViewModel.SendZip 201.5 device.DeviceName: {0}", device.DeviceName);
var ep = new BluetoothEndPoint(device.DeviceAddress, _serviceClassId);
Logger.LogEvent(true, "MainViewModel.SendZip 201.75 ep.Address: {0}", ep.Address);
while (!this.connectionIntervalFinished && !success && !this.wasCanceled)
{
try
{
Logger.LogEvent(true, "MainViewModel.SendZip 201.8 connectionIntervalFinished: {0} , \n success: {1} , \n wasCanceled: {2}",
connectionIntervalFinished, success, wasCanceled);
// connecting
bluetoothClient.Connect(ep);
Logger.LogEvent(true, "MainViewModel.SendZip 201.9");
// get stream for send the data
bluetoothStream = bluetoothClient.GetStream();
Logger.LogEvent(true, "MainViewModel.SendZip 201.95");
// if all is ok to send
if (bluetoothClient.Connected && bluetoothStream != null)
{
this.Status = "Connection is established and ready to send.";
// write the data in the stream
var fileInfo = new FileInfo(this.lastZipPath);
Logger.LogEvent(true, "MainViewModel.SendZip 202");
//var buffer = System.Text.Encoding.UTF8.GetBytes();
int fileLength;
if (int.TryParse(fileInfo.Length.ToString(), out fileLength))
{
var sizeBuffer = LastMileHealth.Helpers.Utils.IntToByteArray(fileLength);
//var sizeBuffer = BitConverter.GetBytes(fileLength);
Logger.LogEvent(true, "MainViewModel.SendZip 203 sizeBuffer: {0}", sizeBuffer.Length);
//TODO: CHUNKS! 4096 //BinaryWriter bw = new BinaryWriter(bluetoothStream);
var fileBuffer = System.IO.File.ReadAllBytes(this.lastZipPath);
var buffer = LastMileHealth.Helpers.Utils.Combine(sizeBuffer, fileBuffer);
Logger.LogEvent(true, "MainViewModel.SendZip 204 sizeBuffer: {0}", buffer.Length);
bluetoothStream.Write(buffer, 0, buffer.Length);
//bluetoothStream.Flush();
// TODO: async method StartListen for responce
byte[] receivedIntBytes = new byte[4];
var tst = bluetoothStream.Read(receivedIntBytes, 0, 4);
var receivedInt = LastMileHealth.Helpers.Utils.ByteArrayToInt(receivedIntBytes);
Logger.LogEvent(true, "MainViewModel.SendZip 205 sizeBuffer: {0}", receivedInt);
if (receivedInt == fileLength)
{
success = true;
Logger.LogEvent(true, "MainViewModel.SendZip 206");
}
}
else
//.........这里部分代码省略.........
示例14: OpenConnection
protected override void OpenConnection()
{
btEndpoint = new BluetoothEndPoint(addr, g);
btClient = new BluetoothClient();
btClient.Connect(btEndpoint);
peerStream = btClient.GetStream();
}
示例15: connect
private bool connect()
{
using (SelectBluetoothDeviceDialog bldialog = new SelectBluetoothDeviceDialog())
{
bldialog.ShowRemembered = false;
if (bldialog.ShowDialog() == DialogResult.OK)
{
if (bldialog.SelectedDevice == null)
{
MessageBox.Show("No device selected");
return false;
}
BluetoothDeviceInfo selecteddevice = bldialog.SelectedDevice;
if (!selecteddevice.Authenticated)
{
if (!BluetoothSecurity.PairRequest(selecteddevice.DeviceAddress, "0000"))
{
MessageBox.Show("PairRequest Error");
return false;
}
}
try
{
client = new BluetoothClient();
client.Connect(selecteddevice.DeviceAddress, BluetoothService.SerialPort);
}
catch
{
return false;
}
stream = client.GetStream();
// 标记stream已经接受对象实例化
SIGN_STREAMSETUP = true;
// 启动接收图片的进程
receiving = true;
receiveThread = new System.Threading.Thread(Receiveloop);
receiveThread.Start();
//
sendDataThread = new System.Threading.Thread(SendData);
closeSendData();
sendDataThread.Start();
return true;
}
return false;
}
}