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 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); } }
void findDevices() { List <Device> devices = new List <Device>(); // po ponownym uruchomieniu if (comboBoxAvailableDevices.Items.Count > 0) { for (int i = 0; i < comboBoxAvailableDevices.Items.Count; i++) { comboBoxAvailableDevices.Items.RemoveAt(i); } } InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient(); InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices(); int count = array.Length; for (int i = 0; i < count; i++) { Device device = new Device(array[i]); devices.Add(device); comboBoxAvailableDevices.Items.Add(device); } if (count > 0) { comboBoxAvailableDevices.SelectedIndex = 0; buttonPair.Enabled = buttonSearch.Enabled = buttonSend.Enabled = true; ShowDeviceOnScreen(); } }
public void findBluetoothTolist() { BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; BluetoothClient bluetoothClient = new BluetoothClient(); BluetoothDeviceInfo[] bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10); ArrayList deviceCollection = new ArrayList(); foreach (BluetoothDeviceInfo device_info in bluetoothDeviceInfo) { string device_name = device_info.DeviceName; string device_address = device_info.DeviceAddress.ToString(); BluetoothDeviceManager manager = new BluetoothDeviceManager(device_name,device_address); deviceCollection.Add(manager); } System.Management.ManagementObjectSearcher Searcher = new System.Management.ManagementObjectSearcher("Select * from WIN32_SerialPort"); foreach (System.Management.ManagementObject Port in Searcher.Get()) { string PNPDeviceID = Port.GetPropertyValue("PNPDeviceID").ToString(); string DeviceID = Port.GetPropertyValue("DeviceID").ToString(); for (int i = 0; i < deviceCollection.Count; i++) { BluetoothDeviceManager manager = (BluetoothDeviceManager)deviceCollection[i]; string device_address = manager.getDeviceAddress(); int index = PNPDeviceID.IndexOf(device_address); if (index > 0) { manager.addCOM(DeviceID); bluetoothList.Add(manager); } } } }
public static List<string> GetNearbyRemoteAddresses(TimeSpan timeout) { List<string> result = new List<string>(); try { BluetoothClient cli = new BluetoothClient(); if (timeout != TimeSpan.Zero) cli.InquiryLength = timeout; BluetoothDeviceInfo[] devs = cli.DiscoverDevices(); foreach (BluetoothDeviceInfo dev in devs) { if (dev.DeviceName.ToLower().Contains("bd remote control")) { if (RemoteBtState(null, dev) == RemoteBtStates.Awake) { string candidate = FormatBtAddress(null, dev.DeviceAddress, "N"); if (!result.Contains(candidate)) result.Add(candidate); } } } } catch { DebugLog.write("BTUtils.GetNearbyRemoteAddresses Failed"); } return result; }
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 string[] GetAvailableSpheroNames() { Reset(); _client = new BluetoothClient(); _peers = _client.DiscoverDevices(); var spheros = _peers.Where(x => x.DeviceName.StartsWith("Sphero")).Select(x => x.DeviceName).ToArray(); return spheros; }
void bg_DoWork(object sender, DoWorkEventArgs e) { /* * Loop over the list of all detected bluetooth devices and display them for selecion * by the user . */ ObservableCollection <Device> devices = new ObservableCollection <Device>(); // Check if a Bluetooth radio is available on the system that is compatible with the 32Feet library. // If not then exit. log.dispatchLogMessage("Bluetooth_Devices: Attempting to find a Bluetooth radio "); bool d = BluetoothRadio.IsSupported; if (!d) { var msg = "No compatible Bluetooth radio found on system . Aboring application"; log.dispatchLogMessage(msg); System.Windows.Forms.MessageBox.Show(msg); Environment.Exit(1); } log.dispatchLogMessage("Success! Compatibe Bluetooth radio found on system "); BluetoothRadio br = BluetoothRadio.PrimaryRadio; var messg = "Details of the Bluetooth radio : "; log.dispatchLogMessage(messg); // Manfucaturer messg = "Manufacturer : " + br.Manufacturer.ToString(); log.dispatchLogMessage(messg); // System Name messg = "Name : " + br.Name.ToString(); log.dispatchLogMessage(messg); //Software Manufacturer messg = "Software Manufacturer :" + br.SoftwareManufacturer.ToString(); log.dispatchLogMessage(messg); log.dispatchLogMessage("Bluetooth Radio initiated"); log.dispatchLogMessage("***"); // This must be put in a try block InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient(); InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices(); log.dispatchLogMessage("Bluetooth_Devices: Bluetooth Devices found in vicinity"); int count = array.Length; Device device; for (int i = 0; i < count; i++) { device = new Device(array[i]); devices.Add(device); //UnsecuredDevices.Add(device); } _unsecuredDevices = devices; e.Result = _unsecuredDevices; }
private void Initialize() { client = new BluetoothClient(); devices = client.DiscoverDevices(10, true, true, false); deviceList.Items.Clear(); foreach (BluetoothDeviceInfo device in devices) { deviceList.Items.Add(device.DeviceName); } }
void bg_DoWork(object sender, DoWorkEventArgs e) { InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient(); InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices(); int count = array.Length; for (int i = 0; i < count; i++) { Device device = new Device(array[i]); detectedDevices.Add(device); } }
public static IList<Pebble> DetectPebbles() { var client = new BluetoothClient(); // A list of all BT devices that are paired, in range, and named "Pebble *" var bluetoothDevices = client.DiscoverDevices( 20, true, false, false ). Where( bdi => bdi.DeviceName.StartsWith( "Pebble " ) ).ToList(); return ( from device in bluetoothDevices select (Pebble)new PebbleNet45( new PebbleBluetoothConnection( device ), device.DeviceName.Substring( 7 ) ) ).ToList(); }
private void bg_DoWork(object sender, DoWorkEventArgs e) { List<Device> devices = new List<Device>(); InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient(); InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices(); int count = array.Length; for (int i = 0; i < count; i++) { Device device = new Device(array[i]); devices.Add(device); } e.Result = devices; }
static void Main(string[] args) { //Runs Method InitDeviceList(); //Drops known user table sqlClient.Drop("tblknown"); //Creates known user table sqlClient.Create("tblknown", "id int NOT NULL AUTO_INCREMENT, name varchar(255),counting int NOT NULL ,address int,PRIMARY KEY (id)"); BluetoothClient bc = new BluetoothClient(); BluetoothDeviceInfo[] devices = bc.DiscoverDevices(); string a = "dadasd"; int number = 0; if (devices.Length == 0) { Console.WriteLine("Empty set"); } else for (int i = 0; i < devices.Length; i++) { a = number + ") " + devices[i].DeviceName + "/" + "Address: " + devices[i].DeviceAddress + "\r\n"; for (int j = 0; j < userDevices.Count; j++) { if (devices[i].DeviceAddress.ToString() == userDevices[j].Address) { //convert list items to string string username = (userDevices[j].UserName.ToString().ToUpper()); string address = (userDevices[j].Address.ToString().ToUpper()); //adds '' to string,so sql can accept as a char string knownuser = "******" + username.Replace(",", "','") + "'"; string knownaddress = "'" + address.Replace(",", "','") + "'"; // listBox1.Items.Add(userDevices[j].UserName); sqlClient.Insert("tblknown", "name", knownuser); sqlClient.Update("tblknown", "counting =counting+1", "id=1"); } } number++; Console.WriteLine(a); } Console.ReadLine(); }
//private static BlueToothWorker _worker = new BlueToothWorker(); public static string[] GetDevicesinRange() { var result = new List<string>(); var cli = new InTheHand.Net.Sockets.BluetoothClient(); //cli.BeginDiscoverDevices(10, true, true, false, false, DeviceDiscovered, null); var peers = cli.DiscoverDevices(); foreach (var device in peers) { result.Add(device.DeviceName); } return result.ToArray(); }
public bool? deviceIsRuning() { bool? result = null; try { BluetoothClient searcher = new BluetoothClient(); searcher.DiscoverDevices(); return true; } catch (Exception ex) { result = false; } return result; }
private void button1_Click(object sender, EventArgs e) { this.listBox1.Items.Clear(); this.label2.Text = "Searching... please wait"; this.label2.Update(); try { BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable; BluetoothClient btc = new BluetoothClient(); devices = btc.DiscoverDevices(60, false, true, true); for (int i = 0; (i < devices.Length); i++) { //if the device is a wocket if (((devices[i].DeviceName.IndexOf("Wocket") >= 0) || (devices[i].DeviceName.IndexOf("WKT") >= 0) || (devices[i].DeviceName.IndexOf("FireFly") >= 0) || (devices[i].DeviceName.IndexOf("0006660") >= 0) && (wocketCount < 100))) { string hex = ""; hex = devices[i].DeviceAddress.ToString(); #region Commented // if (this.WocketsList_Box.Items.IndexOf(hex) < 0) //{ // this.WocketsList_Box.Items.Add(devices[i].DeviceName + " (" + hex + ")"); //macaddresses.Add(hex); //} #endregion Commented this.listBox1.Items.Add(hex); bluetoothlist.Add(hex, devices[i]); wocketCount++; } } btc.Dispose(); btc.Close(); } catch { MessageBox.Show("Cannot connect: please check your Bluetooth radio is plugged in and active"); Environment.Exit(0); } }
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { List <String> devicesNames = new List <String>(); BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient(); BluetoothDeviceInfo[] array = bc.DiscoverDevices(10); int count = array.Length; for (int i = 0; i < count; i++) { //Device device = new Device(array[i]); devices.Add(array[i]); devicesNames.Add(array[i].DeviceName); } e.Result = devicesNames; }
private async void DoFind(Action<IList<IAvailableSphero>> onSuccess, Action<Exception> onError) { try { // what?! var client = new BluetoothClient(); var peers = client.DiscoverDevices(); var spheroPeers = peers .Where(x => x.DeviceName.StartsWith("Sphero")) .Select(x => new AvailableSphero(x)) .ToArray(); onSuccess(spheroPeers); } catch (Exception exception) { onError(exception); } }
private void btnDeviceDiscovery_Click(object sender, EventArgs e) { if (!BluetoothRadio.IsSupported) { MessageBox.Show("Adapter not found"); } else { InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient(); InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices(); for (int i = 0; i < array.Length; i++) { this.address_array[i] = array[i].DeviceAddress; this.lsDevices.Items.Add(array[i].DeviceName); } } }
/// <summary> /// Gets the devices. /// </summary> /// <returns>The list of the devices.</returns> public async Task<IList<Device>> GetDevices() { // for not block the UI it will run in a different threat var task = Task.Run(() => { var devices = new List<Device>(); using (var bluetoothClient = new BluetoothClient()) { var array = bluetoothClient.DiscoverDevices(); var count = array.Length; for (var i = 0; i < count; i++) { devices.Add(new Device(array[i])); } } return devices; }); return await task; }
/// <summary> /// Detect all Pebble bluetooth connections that have been paired with this system. /// </summary> /// <returns></returns> public static List<Flint.Core.Pebble> DetectPebbles() { var client = new BluetoothClient(); // A list of all BT devices that are paired, in range, and named "Pebble *" var bluetoothDevices = client.DiscoverDevices(20, true, false, false). Where(bdi => bdi.DeviceName.StartsWith("Pebble ")); // A list of all available serial ports with some metadata including the PnP device ID, // which in turn contains a BT device address we can search for. var portListCollection = (new ManagementObjectSearcher("SELECT * FROM Win32_SerialPort")).Get(); var portList = new ManagementBaseObject[portListCollection.Count]; portListCollection.CopyTo(portList, 0); return (from device in bluetoothDevices from port in portList where ((string)port["PNPDeviceID"]).Contains(device.DeviceAddress.ToString()) select new Flint.Core.Pebble(new PebbleBluetoothConnection((string)port["DeviceID"]), device.DeviceName.Substring(7))).ToList(); }
public void Run() { var client = new BluetoothClient(); Console.WriteLine("This device's name is {0}", BluetoothRadio.PrimaryRadio.Name); var peers = client.DiscoverDevices(); if (peers == null || peers.Length == 0) { Console.WriteLine("No devices found"); return; } foreach (var device in peers) { device.Refresh(); int i = 0; while (device.DeviceName.Contains(":") && ++i <= 15) device.Refresh(); Console.WriteLine("Device name: {0}", device.DeviceName); } }
public void InitDevice() { Ready = false; var cli = new BluetoothClient(); SendMessage("Поиск устройств..."); BluetoothDeviceInfo[] devices = cli.DiscoverDevices(); if (devices.Any()) { SendMessage(string.Format("Найдено {0} bluetooth устройств:", devices.Length)); foreach (var foundDevice in devices) SendMessage(foundDevice.DeviceName); device = devices.FirstOrDefault(x => x.DeviceName == DeviceName); if (device != null) { SendMessage("Устройство-метка есть в списке"); deviceGiud = device.InstalledServices.First(); Ready = true; } } else SendMessage("Bluetooth устройств не обнаружено."); }
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; } }
/// <summary> Detect all Pebbles that have been paired with this system. /// Takes a little while because apparently listing all available serial /// ports does. /// </summary> /// <returns></returns> public static List<Pebble> DetectPebbles() { var client = new BluetoothClient(); // A list of all BT devices that are paired, in range, and named "Pebble *" var btlist = client.DiscoverDevices(20, true, false, false). Where((bdi) => bdi.DeviceName.StartsWith("Pebble ")); // A list of all available serial ports with some metadata including the PnP device ID, // which in turn contains a BT device address we can search for. var _portlist = (new ManagementObjectSearcher("SELECT * FROM Win32_SerialPort")).Get(); var portlist = new ManagementObject[_portlist.Count]; _portlist.CopyTo(portlist, 0); var peblist = new List<Pebble>(); // Match bluetooth devices and serial ports, then create Pebbles out of them. // Seems like a LINQ join should do this much more cleanly. foreach (BluetoothDeviceInfo bdi in btlist) { foreach (ManagementObject port in portlist) { if ((port["PNPDeviceID"] as String).Contains(bdi.DeviceAddress.ToString())) { peblist.Add(new Pebble(port["DeviceID"] as String, bdi.DeviceName.Substring(7))); } } } return peblist; }
/// <summary> /// Initiates wockets discovery and updates the registry /// </summary> private static void Discover() { try { Registry.LocalMachine.DeleteSubKeyTree(Core.REGISTRY_DISCOVERED_SENSORS_PATH); NetworkStacks._BluetoothStack.Initialize(); BluetoothClient btc = new BluetoothClient(); BluetoothDeviceInfo[] devices = btc.DiscoverDevices(); int wocketCount = 0; for (int i = 0; (i < devices.Length); i++) { //if the device is a wocket if (((devices[i].DeviceName.IndexOf("WKT") >= 0) || (devices[i].DeviceName.IndexOf("Wocket") >= 0) || (devices[i].DeviceName.IndexOf("FireFly") >= 0)) && (wocketCount < 100)) { string hex = ""; hex = devices[i].DeviceAddress.ToString(); RegistryKey rk = Registry.LocalMachine.CreateSubKey(Core.REGISTRY_DISCOVERED_SENSORS_PATH + "\\" + wocketCount.ToString("00")); rk.SetValue("Name", devices[i].DeviceName, RegistryValueKind.String); rk.SetValue("MacAddress", hex, RegistryValueKind.String); rk.Close(); wocketCount++; } } //Send to the appropriate application a response foreach (string guid in applicationPaths.Values) Send(KernelResponse.DISCOVERED, guid); } catch (Exception e) { Logger.Error("Booter.cs: "+ e.ToString()); } }
/// <summary> /// Threaded loop discovers new devices in range and sends this Members profile /// if they have not yet received it. /// </summary> public void DiscoverLoop() { // on exit, run is set to false to terminate all threads while(run) { // create a new bluetooth client object BluetoothClient bt = new BluetoothClient(); // return a maximum of 10 devices bTDevices = bt.DiscoverDevices(10); //close the bluetooth client object bt.Close(); // loop through all the devices found for(int i=0;i<BTDevices.Length;i++) { // check again if the application is exiting and terminate threads // this makes the application end much faster if (!run) { // stop the listener btListener.Stop(); // exit the loop break; } try { // the device isnt looing at itself if (BTDevices[i].DeviceAddress.ToString() != this.MACAddress) { // if the device name is not in the match list if (!MainForm.member.MatchExists(BTDevices[i].DeviceAddress.ToString())) { //Send profile and request that a profile not be returned by using "0" parameter SendBluetoothProfile(bTDevices[i].DeviceAddress, 0); } } } catch(Exception e) { //throw e; // an exception will be thrown if the remote device doesnt reply in time // this is quite a frequent occurance due to the nature of mobile bluetooth } } } }
void DiscoverBT() { try{ BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; BluetoothClient bluetoothClient = new BluetoothClient(); UpdateBTStatus(HOBD.t("Scanning Bluetooth..")); bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10, true, false, true); foreach (var di in bluetoothDeviceInfo){ Logger.info("ConfigurationPage", "BT name="+di.DeviceName+", addr="+di.DeviceAddress.ToString()); } }catch(Exception e){ UpdateBTStatus(HOBD.t("Bluetooth scan failed")); Logger.error("ConfigurationPage", "", e); } UpdateBTStatus(HOBD.t("Scan Again")); CreateItems(); discoverBThread = null; }
//Search private void button_search_Click(object sender, EventArgs e) { try { this.label_status.Text = "Please wait... searching for wockets"; this.Refresh(); this.button_search.Enabled = false; this.dataGridView1.Rows.Clear(); this.macaddresses.Clear(); bluetoothlist.Clear(); int wocketCount = 0; if (BluetoothRadio.PrimaryRadio.Mode != RadioMode.Connectable) { BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable; } BluetoothClient btc = new BluetoothClient(); label_status.Text = "Searching for wockets..."; Application.DoEvents(); devices = btc.DiscoverDevices(60, true, true, true); for (int i = 0; (i < devices.Length); i++) { //if the device is a wocket if (((devices[i].DeviceName.IndexOf("Wocket") >= 0) || (devices[i].DeviceName.IndexOf("WKT") >= 0) || (devices[i].DeviceName.IndexOf("FireFly") >= 0) || (devices[i].DeviceName.IndexOf("00:06:66") >= 0) && (wocketCount < 100))) { string hex = ""; hex = devices[i].DeviceAddress.ToString(); System.Threading.Thread.Sleep(1000); if (this.macaddresses.IndexOf(hex) < 0) { int row = this.dataGridView1.Rows.Add(); this.dataGridView1.Rows[row].Cells[0].Value = devices[i].DeviceName; this.dataGridView1.Rows[row].Cells[1].Value = hex; this.dataGridView1.Rows[row].Cells[2].Value = "Not tested"; this.dataGridView1.Rows[row].Cells[3].Value = "Not tested"; macaddresses.Add(hex); bluetoothlist.Add(devices[i]); System.Threading.Thread.Sleep(1000); } wocketCount++; } } btc.Dispose(); btc.Close(); if (this.dataGridView1.Rows.Count > 0) { this.button_test.Enabled = true; this.button_settings.Enabled = true; } label_status.Text = "Waiting for wocket..."; } catch { label_status.Text = "BT module not responding."; } this.button_search.Enabled = true; }
void doBluetoothWork() { int attempts = 0; int maxTries = 1; while (attempts < maxTries) { attempts++; List <Device> devices = new List <Device>(); // Check if a Bluetooth radio is available on the system that is compatible with the 32Feet library. // If not then exit. log.dispatchLogMessage("Bluetooth Devices: Attempting to find a Bluetooth radio "); bool d = BluetoothRadio.IsSupported; if (!d) { var msg = "No compatible Bluetooth radio found on system . Aboring application"; log.dispatchLogMessage(msg); System.Windows.Forms.MessageBox.Show(msg); Environment.Exit(1); } log.dispatchLogMessage("Success! Compatibe Bluetooth radio found on system "); BluetoothRadio br = BluetoothRadio.PrimaryRadio; var messg = "Details of the Bluetooth radio : "; log.dispatchLogMessage(messg); // Manfucaturer messg = "Manufacturer : " + br.Manufacturer.ToString(); log.dispatchLogMessage(messg); // System Name messg = "Name : " + br.Name.ToString(); log.dispatchLogMessage(messg); //Software Manufacturer messg = "Software Manufacturer :" + br.SoftwareManufacturer.ToString(); log.dispatchLogMessage(messg); log.dispatchLogMessage("Bluetooth Radio initiated"); log.dispatchLogMessage("***"); // This must be put in a try block InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient(); InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices(); log.dispatchLogMessage("Bluetooth Devices found in vicinity"); int count = array.Length; BluetoothDeviceInfo dev; for (int i = 0; i < count; i++) { Device device = new Device(array[i]); if (device.DeviceName == "SAMSUNG GT-I8350") { log.dispatchLogMessage("Found a PROTAG device to connect to "); dev = array[i]; var addr = device.DeviceAddress; if (addr == null) { return; } Guid serviceClass = BluetoothService.SerialPort; // Make a connection to the bluetooth device and continously check for pairing // Lets make 3 consecutive checks to ensure that the connection still exists . // Make a connection to the specified Bluetooth device try { connectBluetoothDevice(bc, addr, serviceClass); try { int sigStrgt = dev.Rssi; var mssg = "Signal strength of the connection is" + sigStrgt; log.dispatchLogMessage(mssg); } catch (Exception e) { /* * Rssi query may fail on certain platforms . Check http://inthehand.com/library/html/P_InTheHand_Net_Sockets_BluetoothDeviceInfo_Rssi.htm * for platfrom details . Handle failure gracefully. */ var mssg = e.Message; mssg += "Signal strength cannot be determined"; log.dispatchLogMessage(mssg); } checkconnection(dev, serviceClass, bc); } catch (Exception ex) { // handle exception var msg = "Bluetooth connection failed: " + ex.Message; log.dispatchLogMessage(msg); log.dispatchLogMessage("Re-initiating connection"); msg = "Attempt " + attempts; log.dispatchLogMessage(msg); Thread.Sleep(10); } } devices.Add(device); } if (attempts >= maxTries) { } //e.Result = devices; } var mesg = "Bluetooth pairing is broken . Please check ! "; log.dispatchLogMessage(mesg); LockWorkStation(); }
private BluetoothDeviceInfo GetPulseOx(BluetoothClient thisRadio) { BluetoothDeviceInfo[] devices = thisRadio.DiscoverDevices(); BluetoothDeviceInfo pulseOx = devices.Where(di => di.DeviceName.StartsWith("Nonin_Medical")).FirstOrDefault(); return pulseOx; }
// This finds and updates the available bluetooth devices private void UpdateThread() { BluetoothClient cli; while(true) { // This is allowed to fail when there are no bluetooth devices connected try { cli = new BluetoothClient(); } catch(ThreadInterruptedException) { return; } catch(Exception e) { General.WriteLogLine(e.GetType().Name + " while updating bluetooth manager: " + e.Message + "\r\n" + e.StackTrace); return; } List<ObexBluetoothDevice> newdevices = null; try { cli.Client.ReceiveTimeout = 1000; cli.Client.SendTimeout = 1000; BluetoothDeviceInfo[] peers = cli.DiscoverDevices(ObexTransferDisplayPanel.NUM_DEVICE_BUTTONS, true, true, true); string p = "Found " + peers.Length + " peers: "; int index = 0; newdevices = new List<ObexBluetoothDevice>(); foreach(BluetoothDeviceInfo bdi in peers) { // Make sure the information on this device is accurate! string addrname = bdi.DeviceName.Replace(":", ""); if(addrname == bdi.DeviceAddress.ToString()) { bdi.Refresh(); bdi.Update(); } p += bdi.DeviceName + " "; // Make info struct newdevices.Add(new ObexBluetoothDevice(bdi)); } General.WriteLogLine(p); } catch(ThreadInterruptedException) { return; } #if !DEBUG catch(NotImplementedException e) { // Ignore this, it's probably due to outdated code in the Bluetooth classes made by 'In The Hand' //General.WriteLogLine(e.GetType().Name + " while updating bluetooth devices: " + e.Message); } #endif catch(Exception e) { General.Fail(e, "while updating bluetooth devices"); } // Make the new devices array on success if(newdevices != null) { lock(this) { devicesinfo = newdevices.ToArray(); } } try { Queue<ObexTransferObject> dotransfers = new Queue<ObexTransferObject>(); lock(transferobjects) { while(transferobjects.Count > 0) dotransfers.Enqueue(transferobjects.Dequeue()); } while(dotransfers.Count > 0) { ObexTransferObject obj = dotransfers.Peek(); Transfer(obj); dotransfers.Dequeue(); } } catch(ThreadInterruptedException) { return; } #if !DEBUG catch(NotImplementedException e) { // Ignore this, it's probably due to outdated code in the Bluetooth classes made by 'In The Hand' //General.WriteLogLine(e.GetType().Name + " while updating bluetooth devices: " + e.Message); } #endif catch(Exception e) { General.Fail(e, "while transferring bluetooth data"); } try { Thread.Sleep(300); } catch(ThreadInterruptedException) { return; } } }
void doBluetoothWork(String deviceName) { // Check if a Bluetooth radio is available on the system that is compatible with the 32Feet library. // If not then exit. log.dispatchLogMessage("Mainservices : Attempting to find a Bluetooth radio "); bool d = BluetoothRadio.IsSupported; if (!d) { var msg = "No compatible Bluetooth radio found on system . Aboring application"; log.dispatchLogMessage(msg); System.Windows.Forms.MessageBox.Show(msg); Environment.Exit(1); } log.dispatchLogMessage("Mainservices : Success! Compatibe Bluetooth radio found on system "); BluetoothRadio br = BluetoothRadio.PrimaryRadio; var messg = "Mainservices : Details of the Bluetooth radio : "; log.dispatchLogMessage(messg); // Manfucaturer messg = "Mainservices : Manufacturer : " + br.Manufacturer.ToString(); log.dispatchLogMessage(messg); // System Name messg = "Mainservices : Name : " + br.Name.ToString(); log.dispatchLogMessage(messg); //Software Manufacturer messg = "Mainservices : Software Manufacturer :" + br.SoftwareManufacturer.ToString(); log.dispatchLogMessage(messg); log.dispatchLogMessage("Mainservices : Bluetooth Radio initiated"); log.dispatchLogMessage("***"); // This must be put in a try block InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient(); InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices(); log.dispatchLogMessage("Mainservices : Bluetooth Devices found in vicinity"); int count = array.Length; BluetoothDeviceInfo dev; for (int i = 0; i < count; i++) { Device device = new Device(array[i]); if (device.DeviceName == deviceName) { /* * Here the maxTries refers to the number of times we will make an attempt to "connect" to the device . Later * the maxTries refer to the number of times we will make an attemp to "checkconnection" that was established earlier. */ int attempts = 0; int maxTries = 3; while (attempts < maxTries) { log.dispatchLogMessage("Mainservices : Found a Bluetooth device to connect to "); log.dispatchLogMessage("Mainservices : Attempting connection to : " + deviceName); dev = array[i]; var addr = device.DeviceAddress; if (addr == null) { return; } Guid serviceClass = BluetoothService.SerialPort; // Make a connection to the bluetooth device and continously check for pairing // // Make a connection to the specified Bluetooth device try { connectBluetoothDevice(bc, addr, serviceClass); /* * Here we fetch the RSSI values of the strength of the signal established betweem the system * and bluetooth device . Currently we just log it . Maybe later we make more better use of it. */ try { int sigStrgt = dev.Rssi; var mssg = "Mainservices : Signal strength of the connection is" + sigStrgt; log.dispatchLogMessage(mssg); } catch (Exception e) { /* * Rssi query may fail on certain platforms . Check http://inthehand.com/library/html/P_InTheHand_Net_Sockets_BluetoothDeviceInfo_Rssi.htm * for platfrom details . Handle failure gracefully. */ var mssg = e.Message; mssg += "Mainservices : Signal strength cannot be determined"; log.dispatchLogMessage(mssg); } checkconnection(dev, serviceClass, bc); /* * If you fall out from checkconnection you probably mean that the connection no longer exits . * So increment attempts. */ attempts++; } catch (Exception ex) { // handle exception attempts++; var msg = "Mainservices : Bluetooth connection failed: " + ex.Message; log.dispatchLogMessage(msg); log.dispatchLogMessage("Mainservices : Re-initiating connection"); msg = "Mainservices : Attempt " + attempts; log.dispatchLogMessage(msg); } } } } }
private void Discovering() { if (!BluetoothRadio.IsSupported) { //synth.Speak ("No Bluetooth Adapter found!!!"); } else { if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff) BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; try { BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; bluetoothClient = new BluetoothClient(); Cursor.Current = Cursors.WaitCursor; bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10); Cursor.Current = Cursors.Default; } catch (Exception ex) { // synth.Speak ("Error: Bluetooth device isn't active (" + ex.Message + ")."); MessageBox.Show(ex.Message); } } }
private void btButton_Click(object sender, System.EventArgs e) { BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; BluetoothClient bluetoothClient = new BluetoothClient(); Cursor.Current = Cursors.WaitCursor; bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10, true, true, true); foreach(BluetoothDeviceInfo di in bluetoothDeviceInfo){ this.portComboBox.Items.Add( di.DeviceName ); } //comboBox1.DataSource = bluetoothDeviceInfo; //comboBox1.DisplayMember = "DeviceName"; //comboBox1.ValueMember = "DeviceAddress"; this.portComboBox.Focus(); Cursor.Current = Cursors.Default; }
/// <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..."); }
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); } }