private async void RfcommScanner_Added(object sender, Bluetooth.IBluetoothDevice e) { if (e.Address == BluetoothUtils.AddressStringToInt64("DC:53:60:DD:AE:63")) { //var serviceResult = await e.GetRfcommServicesAsync(); await e.RfcommConnectAsync(); //var serviceResult = await e.GetRfcommServicesForIdAsync(Constants.ServiceId); var serviceResult = await e.GetRfcommServicesAsync(); IRfcommDeviceService service = null; if (serviceResult.Error == BluetoothError.Success && serviceResult.Services.Count > 0) { foreach (var ser in serviceResult.Services) { if (ser.ServiceId == Constants.ServiceId) { service = ser; break; } } } if (service == null) { return; } var connection = new RfcommRXConnection(service, ConnectionGroup); OnConnectionReceived?.Invoke(this, connection); } }
// Setup function public void Setup() { _ledState = false; BluetoothInfo(); // Create Bluetooth transport object _bluetoothTransport = new BluetoothTransport { //CurrentBluetoothDeviceInfo = BluetoothUtils.DeviceByAdress("98-D3-31-B0-FB-B5") CurrentBluetoothDeviceInfo = BluetoothUtils.DeviceByAdress("20:13:07:26:10:08") }; // Create Serial Port transport object // Note that for some boards (e.g. Sparkfun Pro Micro) DtrEnable may need to be true. _serialTransport = new SerialTransport { CurrentSerialSettings = { PortName = "COM16", BaudRate = 9600, DtrEnable = false } // object initializer }; // Initialize the command messenger with the Serial Port transport layer _cmdMessenger = new CmdMessenger(_bluetoothTransport) { BoardType = BoardType.Bit16 // Set if it is communicating with a 16- or 32-bit Arduino board }; // Tell CmdMessenger if it is communicating with a 16 or 32 bit Arduino board // Attach the callbacks to the Command Messenger AttachCommandCallBacks(); // Start listening _cmdMessenger.Connect(); }
private async void GattServiceListView_ItemSelected(object sender, SelectedItemChangedEventArgs e) { if (GattServiceListView.SelectedItem == null) { return; } Page servicePage = new GattServicePage(e.SelectedItem as GattServiceModel); if ((e.SelectedItem as GattServiceModel).GattServerService.Uuid == BluetoothUtils.ShortValueUuid(0x3432)) { servicePage = new TestGattServicePage(e.SelectedItem as GattServiceModel, TestGattServiceWrapper); } else if ((e.SelectedItem as GattServiceModel).GattServerService.Uuid == BatteryServiceWrapper.BATTERY_SERVICE_UUID) { servicePage = new BatteryServicePage(BatteryServiceWrapper); } else if ((e.SelectedItem as GattServiceModel).GattServerService.Uuid == TcpTranspondServiceWrapper.Uuid) { servicePage = new TcpTranspondServicePage(TcpTranspondServiceWrapper); } GattServiceListView.SelectedItem = null; await Navigation.PushAsync(servicePage); }
public RXConnPage() { ReceiveMessageList = new ObservableCollection <string>(); InitializeComponent(); ReceiveListView.ItemsSource = ReceiveMessageList; IManagerManager managerManager = DependencyService.Get <IManagerManager>(); BluetoothManager = managerManager.BluetoothManager; RXConnectionManager = managerManager.RXConnectionManager; LocalConnectionGroup localConnectionGroup = new LocalConnectionGroup(RXConnectionManager); RXConnectionManager.AddConnectionGroup(localConnectionGroup); RfcommRXConnectionGroup rfcommConnectionGroup = new RfcommRXConnectionGroup(BluetoothManager, RXConnectionManager); RXConnectionManager.AddConnectionGroup(rfcommConnectionGroup); RXConnectionManager.OnReceived += RXConnectionManager_OnReceived; Dictionary <string, byte[]> pairs = new Dictionary <string, byte[]>(); pairs.Add("DeviceName", Encoding.UTF8.GetBytes("MY MACHINE")); pairs.Add("DeviceId", Guid.NewGuid().ToByteArray()); pairs.Add("Rfcomm.N", Encoding.UTF8.GetBytes("XEON-J-LAPTOP-1")); pairs.Add("Rfcomm.A", BitConverter.GetBytes(BluetoothUtils.AddressStringToInt64("DC:53:60:DD:AE:63"))); (localConnectionGroup.Scanner as LocalConnectionScanner).AddConnection(pairs); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { return(BluetoothUtils.AddressInt64ToString((ulong)value)); } catch (Exception) { return("Unknown Address"); } }
private void ChooseBluetoothDevice_Return(object sender, ReturnEventArgs <object> e) => Task.Run(() => { var svc = e.Result as RfcommDeviceService; if (svc == null) { return; } var addr = BluetoothUtils.RequestAddContact(svc, App.Instance.Address); App.AddContactData = new { Address = addr.Value, Name = $"Bluetooth device '{svc.ConnectionHostName.DisplayName}'" }; Dispatcher.Invoke(addr == null ? new Action(() => MessageBox.Show(Application.Current.MainWindow, $"'{svc.ConnectionHostName.DisplayName}' rejected your contact request.")) : new Action(() => NavigationService.Navigate(new Uri("/Views/AddContact.xaml", UriKind.Relative)))); });
public static BluetoothDeviceWrapper GetFromAddress(this IEnumerable <BluetoothDeviceWrapper> bluetoothDevices, string macAddress) { foreach (var device in bluetoothDevices) { if (BluetoothUtils.AddressStringToInt64(macAddress) == device.Address) { return(device); } } return(null); }
public object ConvertBack(object value, Type targetType, object parameter, string language) { try { return(BluetoothUtils.AddressStringToInt64(targetType.ToString())); } catch (Exception) { return(0ul); } }
public SvrNativeInterface() { InitAndroidInterface(); AppUtils = new AppUtils(this); ApkUtils = new ApkUtils(this); BatteryUtils = new BatteryUtils(this); WifiUtils = new WifiUtils(this); VolumeUtils = new VolumeUtils(this); BrightnessUtils = new BrightnessUtils(this); DateTimeUtils = new DateTimeUtils(this); WFDUtils = new WFDUtils(this); FotaUtils = new FotaUtils(this); BluetoothUtils = new BluetoothUtils(this); DeviceUtils = new DeviceUtils(this); }
internal RXBluetoothDevice GetBluetoothDeviceFromDeviceInformation(DeviceInformation deviceInformation) { ulong address = BluetoothUtils.AddressStringToInt64(RXBluetoothUtils.GetAddressStringFromDeviceId(deviceInformation.Id)); foreach (var device in _BluetoothDeviceList) { if (device.Address == address) { return(device); } } RXBluetoothDevice rxBluetoothDevice = new RXBluetoothDevice(this, deviceInformation); _BluetoothDeviceList.Add(rxBluetoothDevice); return(rxBluetoothDevice); }
private async void GattScanner_OnReceived(object sender, BluetoothManager.BluetoothDevice e) { System.Diagnostics.Debug.WriteLine("(Name: " + e.Name + " Address: " + BluetoothUtils.AddressInt64ToString(e.Address) + ")"); if (e.Name.Contains("xj")) { System.Diagnostics.Debug.WriteLine("Got you"); BluetoothManager.Instance.GattScanner.StopScan(); } else { return; } var gattClient = await e.ConnectToGattServerAsync(); if (gattClient != null) { System.Diagnostics.Debug.WriteLine("Connected"); int serviceCount = 0; IGattClientService[] services = null; while (serviceCount == 0) { System.Diagnostics.Debug.WriteLine("No Service"); services = await gattClient.DiscoverAllPrimaryServiceAsync(); serviceCount = services.Length; } foreach (var service in services) { System.Diagnostics.Debug.WriteLine("SERVICE:" + service.Uuid); var characteristics = await service.DiscoverAllCharacteristicsAsync(); foreach (var characteristic in characteristics) { System.Diagnostics.Debug.WriteLine("CHARACTERISTIC:" + characteristic.Uuid); byte[] value = (await characteristic.ReadCharacteristicValueAsync()).Value; if (value == null) { System.Diagnostics.Debug.WriteLine("CHARACTERISTIC VALUE: NULL"); } else { System.Diagnostics.Debug.WriteLine("CHARACTERISTIC VALUE: " + Encoding.ASCII.GetString(value)); } } } } }
private static void BluetoothInfo() { // Show adress of local primary bluetooth device Console.WriteLine("Adress of local primary bluetooth device:"); BluetoothUtils.PrintLocalAddress(); Console.WriteLine(""); //Show all paired bluetooth devices Console.WriteLine("All paired bluetooth devices:"); BluetoothUtils.PrintPairedDevices(); Console.WriteLine(""); // Show Virtual serial ports associated with Bluetooth devices Console.WriteLine("Virtual serial ports associated with Bluetooth devices:"); BluetoothUtils.PrintSerialPorts(); Console.WriteLine(""); }
async Task devicesUpdateProcess() { while (process) { var dev = BluetoothUtils.EnumerateDevices(); Dispatcher.Invoke(() => { var c = list.SelectedItem; list.ItemsSource = dev; if (c != null && dev.Contains(c)) { list.SelectedIndex = dev.FirstIndexOf(c); } }); await Task.Delay(2000); } }
public TestGattServiceWrapper(IBluetoothManager bluetoothManager, Int32 shortUuid) { Name = "No Name M**********r"; GattRequestViewModels = new ObservableCollection <GattRequestViewModel>(); BluetoothManager = bluetoothManager; TestCharacteristicWrapper = new TestCharacteristicWrapper(bluetoothManager); IGattServiceBuilder builder = bluetoothManager.NewGattServiceBuilder(); GattServerService = builder.SetUuid(BluetoothUtils.ShortValueUuid(shortUuid)) .AddCharacteristics(TestCharacteristicWrapper.GattServerCharacteristic) .Build(); TestCharacteristicWrapper.GattServerCharacteristic.OnWrite += _OnCharacteristicWrite; TestCharacteristicWrapper.GattServerCharacteristic.OnRead += _OnCharacteristicRead; value = BitConverter.GetBytes(232); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); var l = new LinearLayout(BaseContext) { Orientation = Orientation.Vertical }; foreach (var d in BluetoothUtils.EnumerateDevices()) { var b = new Button(BaseContext) { Text = $"{d.Name} ({d.Address})" }; b.Click += (sender, e) => Task.Run(() => BluetoothUtils.RequestAddContact(d, Common.Instance.Address)); l.AddView(b); } SetContentView(l); }
internal RXBluetoothDevice RemoveBluetoothDeviceFromDeviceInformationUpdate(DeviceInformationUpdate deviceInformationUpdate) { ulong address = BluetoothUtils.AddressStringToInt64(RXBluetoothUtils.GetAddressStringFromDeviceId(deviceInformationUpdate.Id)); RXBluetoothDevice deviceReadyToDelete = null; foreach (var device in _BluetoothDeviceList) { if (device.Address == address) { deviceReadyToDelete = device; break; } } if (deviceReadyToDelete != null) { _BluetoothDeviceList.Remove(deviceReadyToDelete); } return(deviceReadyToDelete); }
// Show Bluetooth information private static void ShowBluetoothInfo() { // Show adress of local primary bluetooth device Console.WriteLine("Adress of the connected (primary) bluetooth device:"); BluetoothUtils.PrintLocalAddress(); Console.WriteLine(""); //Show all paired bluetooth devices Console.WriteLine("All paired bluetooth devices:"); BluetoothUtils.PrintPairedDevices(); Console.WriteLine(""); //Show all bluetooth devices, paired and unpaired. // Note that this takes a lot of time! Console.WriteLine("All Bluetooth devices, paired and unpaired:"); BluetoothUtils.PrintAllDevices(); Console.WriteLine(""); // Show Virtual serial ports associated with Bluetooth devices // Note that CmdMessenger does not need these and will bypass them Console.WriteLine("Virtual serial ports associated with Bluetooth devices:"); BluetoothUtils.PrintSerialPorts(); Console.WriteLine(""); }
// Setup function public void Setup() { // Let's show all bluetooth devices ShowBluetoothInfo(); // Now let us set Bluetooth transport _transport = new BluetoothTransport() { // If you know your bluetooth device and you have already paired // you can directly connect to you Bluetooth Device by adress adress. // Under windows you can find the adresss at: // Control Panel >> All Control Panel Items >> Devices and Printers // Right-click on device >> properties >> Unique id CurrentBluetoothDeviceInfo = BluetoothUtils.DeviceByAdress("20:13:07:26:10:08") }; // Initialize the command messenger with the Serial Port transport layer // Set if it is communicating with a 16- or 32-bit Arduino board _cmdMessenger = new CmdMessenger(_transport) { PrintLfCr = false // Do not print newLine at end of command, to reduce data being sent }; // The Connection manager is capable or storing connection settings, in order to reconnect more quickly // the next time the application is run. You can determine yourself where and how to store the settings // by supplying a class, that implements ISerialConnectionStorer. For convenience, CmdMessenger provides // simple binary file storage functionality var bluetoothConnectionStorer = new BluetoothConnectionStorer("BluetoothConnectionManagerSettings.cfg"); // It is easier to let the BluetoothConnectionManager connection for you. // It will: // - Auto discover Bluetooth devices // - If not yet paired, try to pair using the default Bluetooth passwords // - See if the device responds with the correct CommunicationIdentifier _connectionManager = new BluetoothConnectionManager( _transport as BluetoothTransport, _cmdMessenger, (int)Command.Identify, CommunicationIdentifier, bluetoothConnectionStorer) { // Enable watchdog functionality. WatchdogEnabled = true, // You can add PIN codes for specific devices DevicePins = { { "01:02:03:04:05:06", "6666" }, { "01:02:03:04:05:07", "7777" }, }, // You can also add PIN code to try on all unpaired devices // (the following PINs are tried by default: 0000, 1111, 1234 ) GeneralPins = { "8888", } }; // Show all connection progress on command line _connectionManager.Progress += (sender, eventArgs) => { if (eventArgs.Level <= 3) { Console.WriteLine(eventArgs.Description); } }; // If connection found, tell the arduino to turn the (internal) led on _connectionManager.ConnectionFound += (sender, eventArgs) => { // Create command var command = new SendCommand((int)Command.TurnLedOn); // Send command _cmdMessenger.SendCommand(command); }; // Finally - activate connection manager _connectionManager.StartConnectionManager(); }
public async Task <ConnectionBuildResult> StartAsync() { if (BluetoothManager.LEScanner.Status == LE.BluetoothLEScannerState.Started) { BluetoothManager.LEScanner.Stop(); } await RemoteDevice.GattClient.ConnectToServerAsync(); var serviceResult = await RemoteDevice.GattClient.DiscoverAllPrimaryServiceAsync(); if (serviceResult.ProtocolError != LE.Gatt.GattErrorCode.Success) { throw new Exception("无法获得LE服务器的Service"); } Dictionary <Guid, IGattClientService> allFoundGattServiceDict = new Dictionary <Guid, IGattClientService>(); foreach (var foundService in serviceResult.Services) { allFoundGattServiceDict.Add(foundService.Uuid, foundService); } List <IGattClientService> gattServiceList = new List <IGattClientService>(); foreach (var profileGattServiceGuid in RealUsingConnectionProfile.RequiredCharacteristicGuids.Keys) { if (!allFoundGattServiceDict.ContainsKey(profileGattServiceGuid)) { throw new Exception("Server中可能没有要求的Service"); } else { gattServiceList.Add(allFoundGattServiceDict[profileGattServiceGuid]); } } Dictionary <IGattClientService, Dictionary <Guid, IGattClientCharacteristic> > serviceCharacteristicDict = new Dictionary <IGattClientService, Dictionary <Guid, IGattClientCharacteristic> >(); foreach (var gattService in gattServiceList) { var characteristics = await gattService.DiscoverAllCharacteristicsAsync(); if (characteristics.ProtocolError != LE.Gatt.GattErrorCode.Success) { throw new Exception("获取Characteristic失败"); } Dictionary <Guid, IGattClientCharacteristic> allFoundGattCharacteristicDict = new Dictionary <Guid, IGattClientCharacteristic>(); foreach (var chara in characteristics.Characteristics) { allFoundGattCharacteristicDict.Add(chara.Uuid, chara); } Dictionary <Guid, IGattClientCharacteristic> characteristicsDict = new Dictionary <Guid, IGattClientCharacteristic>(); var inProfileCharacteristicGuidList = from characteristicProfile in RealUsingConnectionProfile.RequiredCharacteristicGuids[gattService.Uuid] select characteristicProfile.Guid; foreach (var profileCharacteristicGuid in inProfileCharacteristicGuidList) { if (!allFoundGattCharacteristicDict.ContainsKey(profileCharacteristicGuid)) { throw new Exception("Service中没有要求的Characteristic"); } else { characteristicsDict.Add(profileCharacteristicGuid, allFoundGattCharacteristicDict[profileCharacteristicGuid]); } } serviceCharacteristicDict.Add(gattService, characteristicsDict); foreach (var charateristicProfile in RealUsingConnectionProfile.RequiredCharacteristicGuids[gattService.Uuid]) { if (charateristicProfile.Notified) { var result = await characteristicsDict[charateristicProfile.Guid].GattCharacteristicConfiguration.SetValueAsync(true, false); if (result.ProtocolError != LE.Gatt.GattErrorCode.Success) { throw new Exception("无法打开Notify"); } } } } System.Diagnostics.Debug.WriteLine("LE连接过程完成"); var noRfcommResult = new ConnectionBuildResult(serviceCharacteristicDict); var readRfcommAddressResult = await noRfcommResult[Constants.RfcommServerServiceGuid, Constants.RfcommServerAddressCharacteristicGuid].ReadCharacteristicValueAsync(); if (readRfcommAddressResult.ProtocolError != LE.Gatt.GattErrorCode.Success) { throw new Exception("无法读取Rfcomm的MacAddress"); } var rfcommMacAddress = BitConverter.ToUInt64(readRfcommAddressResult.Value, 0); var readRfcommNameResult = await noRfcommResult[Constants.RfcommServerServiceGuid, Constants.RfcommServerNameCharacteristicGuid].ReadCharacteristicValueAsync(); if (readRfcommAddressResult.ProtocolError != LE.Gatt.GattErrorCode.Success) { throw new Exception("无法读取Rfcomm的Name"); } var rfcommName = Encoding.UTF8.GetString(readRfcommNameResult.Value); _WantedDeviceName = rfcommName; System.Diagnostics.Debug.WriteLine("对方的Rfcomm地址是:" + BluetoothUtils.AddressInt64ToString(rfcommMacAddress) + " Name:" + rfcommName); var rfcommScanner = BluetoothManager.RfcommScanner; rfcommScanner.Added += RfcommScanner_Added; rfcommScanner.Stopped += RfcommScanner_Stopped; _WaitingForRfcommScanResultThread = Thread.CurrentThread; rfcommScanner.Start(); try { Thread.Sleep(Timeout.Infinite); } catch (ThreadInterruptedException) { rfcommScanner.Added -= RfcommScanner_Added; rfcommScanner.Stopped -= RfcommScanner_Stopped; if (_TargetFoundDevice == null) { throw new Exception("没有找到Rfcomm设备"); } } Dictionary <Guid, IRfcommDeviceService> inProfileAndFoundRfcommServices = new Dictionary <Guid, IRfcommDeviceService>(); foreach (var inProfileRfcommServiceId in RealUsingConnectionProfile.RequiredServiceGuids) { await _TargetFoundDevice.RfcommConnectAsync(); var rfcommServiceResult = await _TargetFoundDevice.GetRfcommServicesForIdAsync(inProfileRfcommServiceId); if (rfcommServiceResult.Error != BluetoothError.Success || rfcommServiceResult.Services.Count == 0) { throw new Exception("没有找到Rfcomm Service"); } else { await rfcommServiceResult.Services[0].ConnectAsync(); inProfileAndFoundRfcommServices.Add(inProfileRfcommServiceId, rfcommServiceResult.Services[0]); } } var finalResult = noRfcommResult; finalResult.RfcommServiceLookup = inProfileAndFoundRfcommServices; return(finalResult); }
public BluetoothListener(BluetoothUtils oTG) : base("com.ssnwt.vr.androidmanager.bluetooth.BluetoothUtils$BluetoothListener") { oTGContent = oTG; }
public object Convert(object value, Type targetType, object parameter, string language) { UInt64 macAddress = (UInt64)value; return(BluetoothUtils.AddressInt64ToString(macAddress)); }
public CommandMessengerTest() { // Set up board & transport mode var teensy31 = new systemSettings() { Description = @"Teensy 3.1", MinReceiveSpeed = 2000000, // Bits per second MinSendSpeed = 1250000, // Bits per second MinDirectSendSpeed = 45000, // Bits per second BoardType = BoardType.Bit32, // 32-bit architecture, needed from binary value conversion sendBufferMaxLength = 512, // Maximum send buffer size, optimally buffer size is similar to embedded controller Transport = new SerialTransport { CurrentSerialSettings = new SerialSettings() { PortName = "COM15", // Can be different! BaudRate = 115200, // Bits per second DataBits = 8, // Data bits Parity = Parity.None, // Bit parity DtrEnable = false, // Some boards need to send this to enabled }, } }; var arduinoNano = new systemSettings() { Description = @"Arduino Nano /w AT mega328", MinReceiveSpeed = 82000, // Bits per second MinSendSpeed = 85000, // Bits per second MinDirectSendSpeed = 52000, // Bits per second BoardType = BoardType.Bit16, // 16-bit architecture, needed from binary value conversion sendBufferMaxLength = 60, // Maximum send buffer size, optimally buffer size is similar to embedded controller Transport = new SerialTransport { CurrentSerialSettings = new SerialSettings() { PortName = "COM16", // Can be different! BaudRate = 115200, // Bits per second DataBits = 8, // Data bits Parity = Parity.None, // Bit parity DtrEnable = false, // Some boards need to send this to enabled }, } }; var arduinoNanoBluetooth = new systemSettings() { Description = @"Arduino Nano /w AT mega328 - Bluetooth", MinReceiveSpeed = 6500, // Bits per second MinSendSpeed = 7400, // Bits per second MinDirectSendSpeed = 8000, // Bits per second BoardType = BoardType.Bit16, // 16-bit architecture, needed from binary value conversion sendBufferMaxLength = 60, // Maximum send buffer size, optimally buffer size is similar to embedded controller Transport = new BluetoothTransport() { CurrentBluetoothDeviceInfo = BluetoothUtils.DeviceByAdress("20:13:07:26:10:08"), LazyReconnect = true, // Only reconnect if really necessary } }; var arduinoLeonardoOrProMicro = new systemSettings() { Description = @"Arduino Leonardo or Sparkfun ProMicro /w AT mega32u4", MinReceiveSpeed = 82000, // Bits per second MinSendSpeed = 90000, // Bits per second MinDirectSendSpeed = 52000, // Bits per second BoardType = BoardType.Bit16, // 16-bit architecture, needed from binary value conversion sendBufferMaxLength = 60, // Maximum send buffer size, optimally buffer size is similar to embedded controller Transport = new SerialTransport { CurrentSerialSettings = new SerialSettings() { PortName = "COM13", // Can be different! BaudRate = 115200, // Bits per second DataBits = 8, // Data bits Parity = Parity.None, // Bit parity DtrEnable = true, // Some boards need to send this to enabled }, } }; // Set up Command enumerators var command = DefineCommands(); // Initialize tests, CHANGE "DEVICE" VARIABLE TO YOUR DEVICE! var device = teensy31; InitializeTests(device, command); // Open log file for testing Common.OpenTestLogFile(@"TestLogFile.txt"); // Run tests RunTests(); Common.CloseTestLogFile(); }