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); } }
/// <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; }
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; }
private void Button1Click(object sender, RoutedEventArgs e) { var addr = BluetoothAddress.Parse("d0:37:61:c4:cb:25"); var serviceClass = BluetoothService.SerialPort; var ep = new BluetoothEndPoint(addr, serviceClass); _bluetoothClient = new BluetoothClient(); _bluetoothClient.Connect(ep); // Stream peerStream = cli.GetStream(); BtProtocol.OutStream = _bluetoothClient.GetStream(); MetaWatchService.inputOutputStream = BtProtocol.OutStream; BtProtocol.SendRtcNow(); BtProtocol.GetDeviceType(); BtProtocol.OutStream.Flush(); _readThread = new Thread(() => { while (true) { BtProtocol.OutStream.ReadTimeout = 2000000; var startByte = BtProtocol.OutStream.ReadByte(); if (startByte != 1) continue; var msgLen = BtProtocol.OutStream.ReadByte(); if (msgLen < 6) { MessageBox.Show("Ошибка приёма"); continue; } var msgType = BtProtocol.OutStream.ReadByte(); var msgOptions = BtProtocol.OutStream.ReadByte(); var msgDataLen = msgLen - 6; var data = new byte[msgDataLen]; BtProtocol.OutStream.Read(data, 0, msgDataLen); //CRC BtProtocol.OutStream.ReadByte(); BtProtocol.OutStream.ReadByte(); switch (msgType) { case (int)BtMessage.Message.GetDeviceTypeResponse: switch (data[0]) { case 2: Dispatcher.Invoke(new Action(delegate { sbiConnect.Content = "Подключено!"; }), System.Windows.Threading.DispatcherPriority.Normal); //MessageBox.Show("Цифровые!"); break; } break; case (int)BtMessage.Message.ButtonEventMsg: if ((data[0] & 0x1) == 0x1) MessageBox.Show("A!"); if ((data[0] & 0x2) == 0x2) MessageBox.Show("B!"); if ((data[0] & 0x4) == 0x4) MessageBox.Show("C!"); if ((data[0] & 0x8) == 0x8) MessageBox.Show("D!"); if ((data[0] & 0x20) == 0x20) MessageBox.Show("E!"); if ((data[0] & 0x40) == 0x40) MessageBox.Show("F!"); if ((data[0] & 0x80) == 0x80) MessageBox.Show("S!"); break; case (int)BtMessage.Message.ReadBatteryVoltageResponse: var powerGood = data[0]; var batteryCharging = data[1]; var voltage = (data[3] << 8) | data[2]; var voltageAverage = (data[5] << 8) | data[4]; MessageBox.Show(string.Format("volt:{0} avg:{1} powerGood:{2} batteryCharging: {3}", voltage / 1000f, voltageAverage / 1000f, powerGood, batteryCharging)); break; } } }); _readThread.Start(); // var buf = new byte[2]; // var readLen = peerStream.Read(buf, 0, buf.Length); // if (readLen == 2) // { // MessageBox.Show(buf[1].ToString()); // } // peerStream.Write/Read ... // //e.g. /*var buf = new byte[1000]; var readLen = peerStream.Read(buf, 0, buf.Length); if (readLen == 0) { Console.WriteLine("Connection is closed"); } else { Console.WriteLine("Recevied {0} bytes", readLen); }*/ }
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; } } catch (Exception ex) { logging.AddToLog(address + " - " + obj.Name + " failed with Connect attempt. exception: " + ex.Message, false); } if (found) { osae.ObjectStateSet(obj.Name, "ON"); logging.AddToLog("Status Updated in osae", false); } else { osae.ObjectStateSet(obj.Name, "OFF"); logging.AddToLog("Status Updated in osae", false); } } } catch (Exception ex) { logging.AddToLog("Error searching for devices: " + ex.Message, true); } }
private async void MainWindow_Activated(object sender, EventArgs e) { BluetoothDevicePicker picker = new BluetoothDevicePicker(); //picker.ClassOfDevices.Add(new ClassOfDevice(DeviceClass.SmartPhone, 0)); var device = await picker.PickSingleDeviceAsync(); InTheHand.Net.Sockets.BluetoothClient client = new InTheHand.Net.Sockets.BluetoothClient(); System.Diagnostics.Debug.WriteLine("Unknown"); foreach (BluetoothDeviceInfo bdi in client.DiscoverDevices()) { System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress); } System.Diagnostics.Debug.WriteLine("Paired"); foreach (BluetoothDeviceInfo bdi in client.PairedDevices) { System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress); } //System.Diagnostics.Debug.WriteLine(client.RemoteMachineName); client.Connect(device.DeviceAddress, BluetoothService.SerialPort); var stream = client.GetStream(); stream.Write(System.Text.Encoding.ASCII.GetBytes("Hello World\r\n\r\n"), 0, 15); stream.Close(); }
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); } }
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); } }
private async void button2_Click(object sender, EventArgs e) { BluetoothDevicePicker picker = new BluetoothDevicePicker(); var device = await picker.PickSingleDeviceAsync(); listBox1.Items.Clear(); listBox2.Items.Clear(); client = new InTheHand.Net.Sockets.BluetoothClient(); client.Connect(device.DeviceAddress, new Guid("fa87c0d0-afac-11de-8a39-0800200c9a66")); stream = client.GetStream(); label3.Text = "Status: Connected " + device.DeviceName; //var AvilableDevices = client.DiscoverDevices(); //foreach (var item in AvilableDevices) //{ // listBox1.Items.Add(item.DeviceName); //} //var PairDevices = client.PairedDevices; //foreach (var item in PairDevices) //{ // listBox2.Items.Add(item.DeviceName); //} btnConnect.Enabled = !client.Connected; btnDisconnect.Enabled = client.Connected; btnSend.Enabled = client.Connected; }
/// <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; } }
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(); }
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 ); } ); }
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); } }
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(); }
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()); } }
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; }
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; } }
// 连接电脑端蓝牙 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); stream = client.GetStream(); stream.Write(System.Text.Encoding.ASCII.GetBytes("student" + LOCALBLUETOOTHNAME), 0, 7 + LOCALBLUETOOTHNAME.Length); } catch { return false; } StateOfRunning(); stream = client.GetStream(); // 标记stream已经接受对象实例化 SIGN_STREAMSETUP = true; // 启动接收图片的进程 receiving = true; // sendfileThread = new System.Threading.Thread(SendFileLoop); return true; } return false; } }
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 { this.Status = "Too big file!"; MessageBox.Show("Too big file!"); } } } catch (Exception ex) { Logger.LogEvent(true, "MainViewModel.SendZip 207 Exception = {0} , \nStack = {1}", ex.Message, ex.StackTrace); lastEx = ex; } finally { //if (bluetoothClient != null) //{ // //bluetoothStream.Flush(); // //bluetoothStream.Close(); // bluetoothClient.Close(); // bluetoothClient.Dispose(); //} } } Logger.LogEvent(true, "MainViewModel.SendZip 208"); this.StopTimer(aTimer); //if (bluetoothStream != null) //{ // bluetoothStream.Flush(); // bluetoothStream.Close(); //} if (bluetoothClient != null) { Logger.LogEvent(true, "MainViewModel.SendZip 209"); bluetoothClient.Close(); bluetoothClient.Dispose(); bluetoothClient = null; } Logger.LogEvent(true, "MainViewModel.SendZip 210"); } }).ContinueWith(taskState => { Logger.LogEvent(true, "MainViewModel.SendZip 211"); this.IsScanning = false; if (success) { this.Status = string.Format("File \"{0}\" has been transferred to {1}!", Path.GetFileNameWithoutExtension(this.lastZipPath) + ".lmu", this.selectedDevice.Name); this.ClearAfterSendOrCancel(); } else if (!this.wasCanceled) { this.Status = "Form transfering failed."; Logger.LogEvent(true, "MainViewModel.SendZip 212 lastEx: {0}", lastEx == null ? "IsNULL" : "Not NULL"); if (lastEx != null) { if (lastEx is SocketException) { var socketEx = (SocketException)lastEx; BluetoothRadio.PrimaryRadio.Mode = RadioMode.PowerOff; if (socketEx.SocketErrorCode == SocketError.AddressNotAvailable || socketEx.SocketErrorCode == SocketError.TimedOut) { MessageBox.Show("Selected bluetooth device is not available. Please press \"App Update\" button on an appropriate device before sending forms.", "Destination device is not reachable.", MessageBoxButton.OK, MessageBoxImage.Warning); } else if (socketEx.SocketErrorCode == SocketError.InvalidArgument || socketEx.SocketErrorCode == SocketError.Shutdown) { MessageBox.Show("Try one of next solutions:\n- Try to restart the application\n- Unpair devices in settings (for both devices) and pair them again.\n", "Bluetooth connection problem.", MessageBoxButton.OK, MessageBoxImage.Error); } else// if (lastEx.Message.Contains("invalid argument was supplied")) // (lastEx as SocketException).SocketErrorCode == SocketError.Shutdown { MessageBox.Show("Try one of next solutions:\n- Try to restart the application;\n- Unpair devices in settings (for both devices) and pair them again;\n- Go to Start > Type services.msc > Services Local > Then scroll down the list till you see 'Bluetooth Support Service' > Right click on it and then Stop the process and then start it up again;\n- Update bluetooth drivers;", "Bluetooth connection problem.", MessageBoxButton.OK, MessageBoxImage.Error); } } Logger.LogEvent(true, "MainViewModel.SendZip 213"); this.AddExceptionToLog(lastEx); } this.SelectedDeviceIndex = -1; } Logger.LogEvent(true, "MainViewModel.SendZip 214"); }, TaskScheduler.FromCurrentSynchronizationContext()); Logger.LogEvent(true, "MainViewModel.SendZip 215"); }
public void SerialOpen(String portName, BaudRates baud) { if (portName.StartsWith("COM")){ BasicPortSettings portSettings = new BasicPortSettings(); portSettings.BaudRate = baud; mPort = new Port(portName+":", portSettings); mPort.RThreshold = 1; mPort.SThreshold = 1; // send 1 byte at a time mPort.InputLen = 0; mPort.Open(); mPort.DataReceived +=new Port.CommEvent(mPort_DataReceived); }else{ try{ BluetoothAddress address = BluetoothAddress.Parse(portName); bluetoothClient = new BluetoothClient(); bluetoothClient.SetPin(address, "0000"); BluetoothEndPoint btep = new BluetoothEndPoint(address, BluetoothService.SerialPort, 1); bluetoothClient.Connect(btep); stream = bluetoothClient.GetStream(); if (stream == null){ bluetoothClient.Close(); bluetoothClient = null; }else{ if (stream.CanTimeout){ stream.WriteTimeout = 2; stream.ReadTimeout = 2; } } }catch(System.IO.IOException){ bluetoothClient = null; } } }
public void MakeConnection() { BluetoothClient thisRadio = GetRadio(); if (thisRadio == null) { SetError("Bluetooth radio not found"); return; } BluetoothDeviceInfo pulseOx = GetPulseOx(thisRadio); if (pulseOx == null) { SetError("Pulse oximeter not found"); return; } noninEndpoint = new BluetoothEndPoint(pulseOx.DeviceAddress, BluetoothService.SerialPort); /* Listen mode */ if (ATREnabled) { BluetoothListener btListen = new BluetoothListener(BluetoothService.SerialPort); btListen.Start(); noninClient = btListen.AcceptBluetoothClient(); } /* Connect mode */ else { noninClient = new BluetoothClient(); try { noninClient.Connect(noninEndpoint); } catch (SocketException ex) { SetError("Couldn't connect to pulse oximeter", ex); } } if (noninClient.Connected) { connectionBegin = DateTime.Now; } GetMostRecentReading(); }
/// <summary> /// 连接函数 /// </summary> /// <returns></连接失败返回false> 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); stream = client.GetStream(); stream.Write(System.Text.Encoding.ASCII.GetBytes("teacher"), 0, 7); } catch { return false; } StateOfRunning(); stream = client.GetStream(); // 标记stream已经接受对象实例化 SIGN_STREAMSETUP = true; // 启动接收图片的线程 receiving = true; ReceiveThread = new System.Threading.Thread(ReceiveLoop); ReceiveThread.Start(); // 启动信息发送线程 sendDataThread = new System.Threading.Thread(SendDataLoop); closeSendData(); sendDataThread.Start(); sendfileThread = new System.Threading.Thread(SendFileLoop); return true; } return false; } }
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; } }
void bgCominucate_DoWork(object sender, DoWorkEventArgs e) { using (var bluetoothClient = new BluetoothClient()) { try { var ep = new BluetoothEndPoint(((Device)e.Argument).DeviceInfo, MyConsts.MyServiceUuid); // connecting bluetoothClient.Connect(ep); Stream peerStream = bluetoothClient.GetStream(); StreamReader sr = new StreamReader(peerStream); int line; // Read and display lines from the file until the end of // the file is reached. while (true)//(line = sr.ReadLine()) != null) { line = sr.Read(); if (line != -1) { stream.WriteAsync(BitConverter.GetBytes(((Device)e.Argument).PlayerID), 0, 4); stream.WriteAsync(BitConverter.GetBytes(line), 0, 4); } } } 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 } } }
private void sendMessage(int NumRetries, byte[] Buffer, int BufferLen) { BluetoothClient client = null; int CurrentTries = 0; for ( ; ((client == null) && (CurrentTries < NumRetries)); ) { try { client = new BluetoothClient(); client.Connect(new BluetoothEndPoint(((BluetoothDeviceInfo)(cboDevices.SelectedItem)).DeviceAddress, ServiceName)); } catch (SocketException se) { if ((CurrentTries >= NumRetries)) { throw se; } client = null; } CurrentTries = (CurrentTries + 1); } if ((client == null)) { // timeout occurred MsgBox("Error establishing contact"); return; } System.IO.Stream stream = null; try { stream = client.GetStream(); stream.Write(Buffer, 0, BufferLen); } catch (Exception e) { MsgBox("Error sending"); } finally { if (!(stream == null)) { stream.Close(); } if (!(client == null)) { client.Close(); } } }
public void Open(String url) { try{ var parsed_url = ParseUrl(url); Logger.trace("BluetoothStream", "Open " + parsed_url[URL_ADDR] + " serviceid " + parsed_url[URL_SVC] + " pin " + parsed_url[URL_PIN]); try{ BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; }catch(Exception e){ Logger.error("BluetoothStream", "set_Mode", e); } BluetoothAddress address = BluetoothAddress.Parse(parsed_url[URL_ADDR]); bluetoothClient = new BluetoothClient(); try{ if (parsed_url[URL_PIN] != null) { bluetoothClient.SetPin(address, parsed_url[URL_PIN]); } }catch(Exception){ Logger.error("BluetoothStream", "SetPin"); } #if xxBLUETOOTH_USE_PAIRREQUEST // advice from some user - but was useless. other user reported "unable to connecte because of this" if (parsed_url[URL_PIN] != null) try{ for(var i = 0; i < 3; i++){ var res = BluetoothSecurity.PairRequest(address, parsed_url[URL_PIN]); if (res) break; Logger.error("BluetoothStream", "PairRequest failed, retry "+i); } }catch(Exception){ Logger.error("BluetoothStream", "PairRequest"); } #endif BluetoothEndPoint btep; // force serviceid for some popular china BT adapters if (parsed_url[URL_SVC] == null && try_with_service) { parsed_url[URL_SVC] = "1"; } if (parsed_url[URL_SVC] != null) btep = new BluetoothEndPoint(address, BluetoothService.SerialPort, int.Parse(parsed_url[URL_SVC])); else btep = new BluetoothEndPoint(address, BluetoothService.SerialPort); bluetoothClient.Connect(btep); stream = bluetoothClient.GetStream(); if (stream == null){ bluetoothClient.Close(); bluetoothClient = null; }else{ if (stream.CanTimeout){ stream.WriteTimeout = 2; stream.ReadTimeout = 2; } } }catch(Exception e){ if (bluetoothClient != null) { bluetoothClient.Close(); bluetoothClient = null; } if (!try_with_service){ try_with_service = true; Open(url); return; } throw; } }
/// <summary> /// Connect to device /// </summary> private void ConnectToDevice() { try { // bgWorkerProcessData.ReportProgress(0, "Creating endboint"); BluetoothEndPoint endPoint = new BluetoothEndPoint(deviceAddress, serviceClass); // bgWorkerProcessData.ReportProgress(0, "Creating bt client"); using (BluetoothClient btClient = new BluetoothClient()) { bgWorkerProcessData.ReportProgress(0, "Connecting..."); btClient.Connect(endPoint); bgWorkerProcessData.ReportProgress(0, "Connected"); // If connected using (Stream peerStream = btClient.GetStream()) { // Read and parse data from device. ReadData(peerStream); } } } catch (Exception ex) { // try to connect again in 2 second. bgWorkerProcessData.ReportProgress(0, ex.Message); Thread.Sleep(2000); } }
/// <summary> /// Connect to Arduino. (PC as Master) /// </summary> /// <param name="client">Ref class BluetoothClient</param> /// <param name="macAdress">Mac Address from Single Handler</param> /// <returns></returns> private static bool ConnectArduino(ref BluetoothClient client, string macAdress) { try { client = new BluetoothClient(); client.Connect(new BluetoothEndPoint(BluetoothAddress.Parse(macAdress), BluetoothService.SerialPort)); return true; } catch (Exception) { MessageBox.Show(@"Error. Connection is failed!"); return false; } }
protected override void OpenConnection() { btEndpoint = new BluetoothEndPoint(addr, g); btClient = new BluetoothClient(); btClient.Connect(btEndpoint); peerStream = btClient.GetStream(); }
/// <summary> /// Constructor, tries to connect 3x to NXT then fails /// </summary> /// <param name="nxtName">NXT brick name, case sensitive</param> /// <param name="connectionTries">Max failed try to connect</param> public NXTBluetooth(string nxtName, int connectionTries = 3) { _maxTries = connectionTries; try { _btc = new BluetoothClient(); // instantiate bluetooth connection debugMessage(@"Bluetooth is discovering devices"); _bdi = _btc.DiscoverDevices(); // get all bluetooth devices #if DEBUG debugMessage(@"Bluetooth devices:"); foreach (BluetoothDeviceInfo info in _bdi) { Console.WriteLine(info.DeviceName); } #endif // linq to match our NXT name var nxt = from n in this._bdi where n.DeviceName == nxtName select n; if (nxt != null && nxt.Count<BluetoothDeviceInfo>() > 0) { // get the NXT device info _nxt = (BluetoothDeviceInfo)nxt.First<BluetoothDeviceInfo>(); } else { // no NXT of that name exists throw new Exception("Cannot find NXT name from Bluetooth device list"); } debugMessage(@"Bluetooth Initialized, NXT found"); } catch (Exception) { throw; } _client = null; int tries = 1; do { debugMessage(string.Format(@"Connecting to NXT... on {0} try...", tries)); try { // now if we have found our NXT _client = new BluetoothClient(); // we will connect to the NXT using the device info we got earlier _client.Connect(_nxt.DeviceAddress, _SERVICENAME); } catch (SocketException se) { if ((tries >= this._maxTries)) { // gave up trying to connect throw se; } debugMessage(string.Format(@"Error establishing contact, retrying {0} time", tries)); _client = null; } // if we cant connect, we can try and try, default is 3 times tries = tries + 1; } while (_client == null & tries <= this._maxTries); // after these, if client is not null then we are connected! we can use _client now if ((_client == null)) { //timeout occurred debugMessage(@"Error establishing contact, fail"); throw new Exception(@"Cannot connect to NXT... Terminating..."); } debugMessage(@"Connected to NXT..."); }
private void Baglan() { int deneme = 0; sunucu = null; // Uzak makina ile baðlantý kurmaya çalýþýyoruz... do { try { sunucu = new BluetoothClient(); sunucu.Connect(new BluetoothEndPoint(sunucuAdresi, servisAdi)); } catch (SocketException ex) { if (deneme >= Sabitler.MAX_DENEME_SAYISI) { Console.WriteLine(ex.ToString()); } } deneme += 1; } while (sunucu == null && deneme < Sabitler.MAX_DENEME_SAYISI); if (sunucu.Connected == false) { HataGoster(); return; } if (sunucuStream == null) { try { sunucuStream = sunucu.GetStream(); } catch (Exception) { HataGoster(); return; } } anaPencere.ArastirmaBilgisi(sunucuAdi + " aygýtý ile baðlantý kuruldu."); anaPencere.MesajBilgisi(sunucuAdi + " aygýtý ile baðlantý kuruldu."); anaPencere.BaglanButonu(); baglantiKuruldu = true; // Sunucu ile baðlantý kuruldu... }
/// <summary> /// Send Members profile to another bluetooth device /// </summary> /// <param name="address">The address object for the remote Member</param> /// <param name="gotTheirProfile">1 if this Member has the remote Members profile</param> private void SendBluetoothProfile(BluetoothAddress address, int gotTheirProfile) { try { // Create a BluetoothClient object BluetoothClient btSend = new BluetoothClient(); // Connect to the remote member with the serviceGUID for service identification btSend.Connect(new BluetoothEndPoint(address, serviceGUID)); // get the stream from the connetion System.IO.Stream s = btSend.GetStream(); // serialise the this Members profile into a string string header = ""; header += this.MajorVersion+","; header += this.MinorVersion+","; header += Member.Age+","; header += ((int)Member.Gender).ToString()+","; header += Member.SeekAge+","; header += ((int)Member.SeekGender).ToString()+","; header += MainForm.member.MemberID+","; header += this.MACAddress+","; header += gotTheirProfile.ToString(); // convert the header string into a byte array for transmission byte[] bs = System.Text.Encoding.Unicode.GetBytes(header); // write the byte array to the steam object s.Write(bs, 0, bs.Length); // Flush the buffer and transmit the profile s.Flush(); // close the BluetoothClient connection btSend.Close(); } catch(Exception ex) { throw ex; } }
public override void send_file(String devicename, String bluid, int not) { try { _stopwatch.Start(); _bluetooth_client = new BluetoothClient(); BluetoothDeviceInfo[] devinfos = _bluetooth_client.DiscoverDevices(); foreach (var device in devinfos) { if (device.DeviceName == devicename) { _bluetooth_address = device.DeviceAddress; break; } } _bluetooth_guid = Guid.Parse(bluid); _bluetooth_client.Connect(_bluetooth_address, _bluetooth_guid); _netstream = _bluetooth_client.GetStream(); byte[] dataToSend = File.ReadAllBytes(this.filepath); _netstream.Write(dataToSend, 0, dataToSend.Length); _netstream.Flush(); _netstream.Dispose(); _netstream.Close(); _bluetooth_client.Dispose(); _bluetooth_client.Close(); _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath); this.callback.on_file_received(_message, this.results); this.main_view.text_to_logs(_message); _stopwatch.Stop(); } catch (Exception e) { append_error_tolog(e, _stopwatch.Elapsed, devicename); } }
public void connectBluetoothDevice(BluetoothClient bc, BluetoothAddress addr, Guid serviceClass) { try { var ep = new BluetoothEndPoint(addr, serviceClass); bc.Connect(ep); } 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.Message; msg = reason + msg; msg += "Attempting to reconnect ...."; log.dispatchLogMessage(msg); //MessageBox.Show(msg); } var mssg = "Bluetooh connection established with a PROTAG device "; log.dispatchLogMessage(mssg); }