/// <summary> /// The entry point of a background task. /// </summary> /// <param name="taskInstance">The current background task instance.</param> public async void Run(IBackgroundTaskInstance taskInstance) { // Get the deferral to prevent the task from closing prematurely deferral = taskInstance.GetDeferral(); // Setup our onCanceled callback and progress this.taskInstance = taskInstance; this.taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); this.taskInstance.Progress = 0; // Store a setting so that the app knows that the task is running. ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = true; periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1)); try { RfcommConnectionTriggerDetails details = (RfcommConnectionTriggerDetails)taskInstance.TriggerDetails; if (details != null) { socket = details.Socket; remoteDevice = details.RemoteDevice; ApplicationData.Current.LocalSettings.Values["RemoteDeviceName"] = remoteDevice.Name; writer = new DataWriter(socket.OutputStream); reader = new DataReader(socket.InputStream); } else { ApplicationData.Current.LocalSettings.Values["BackgroundTaskStatus"] = "Trigger details returned null"; deferral.Complete(); } var result = await ReceiveDataAsync(); } catch (Exception ex) { reader = null; writer = null; socket = null; deferral.Complete(); Debug.WriteLine("Exception occurred while initializing the connection, hr = " + ex.HResult.ToString("X")); } }
public async void FindDeviceD() { PRing.IsActive = true; //classBluetoothDevices.Clear(); // var BluetoothDeviceSelector = "System.Devices.DevObjectType:=5 AND System.Devices.Aep.ProtocolId:=\"{E0CBF06C-CD8B-4647-BB8A-263B43F0F974}\""; // var deviceInfoCollection = await DeviceInformation.FindAllAsync(BluetoothDeviceSelector); // foreach (var ff in deviceInfoCollection) { // var bluetoothDevice = await BluetoothDevice.FromIdAsync(ff.Id); // await new MessageDialog(ff.Name +"\n"+ bluetoothDevice.Name+"\n"+ bluetoothDevice.HostName.DisplayName).ShowAsync(); } var devices = await DeviceInformation.FindAllAsync(); foreach (var dd in devices) { var device = dd; if (device != null) { try { if (device.Id.Contains("Bluetooth")) { var bluetoothDevice = await BluetoothDevice.FromIdAsync(device.Id); // await new MessageDialog(device.IsEnabled.ToString() + "\n" + bluetoothDevice.ConnectionStatus.ToString() + "\n" + bluetoothDevice.Name + "\n" + bluetoothDevice.DeviceInformation.Pairing.IsPaired.ToString()).ShowAsync(); //if (bluetoothDevice.DeviceInformation.IsEnabled) { // var service = rfcommServices.Services[0]; // await _socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName); classBluetoothDevices.Add(new ClassBluetoothDevice() { namea = dd.Name, bluetoothDeviced = bluetoothDevice, tip = "RFCOMM" }); } } } catch (Exception ex) { } } } // listV.ItemsSource = classBluetoothDevices; string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" }; var services = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false), requestedProperties, DeviceInformationKind.AssociationEndpoint); for (int i = 0; i < services.Count; i++) { //if (services[i].Id.Contains("Bluetooth") && (service.ProtectionLevel== SocketProtectionLevel.BluetoothEncryptionWithAuthentication || service.ProtectionLevel == SocketProtectionLevel.BluetoothEncryptionWithAuthentication || SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication)) if (services[i].Id.Contains("Bluetooth")) { try { //var service = await RfcommDeviceService.FromIdAsync(services[0].Id); BluetoothLEDevice bluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(services[i].Id); // MessageDialog messageDialog = new MessageDialog(services[i].Properties.ElementAt(2).Key + "\t" + services[i].Properties.ElementAt(2).Value.ToString() +"\n"+ service.ToString()); // await messageDialog.ShowAsync(); if (bluetoothLEDevice != null) { string name = "NAME"; if (!String.IsNullOrEmpty(bluetoothLEDevice.Name)) { name = bluetoothLEDevice.Name; } else { if (!String.IsNullOrEmpty(services[i].Name)) { name = services[i].Name; } } classBluetoothDevices.Add(new ClassBluetoothDevice() { namea = name, bluetoothLEDevice = bluetoothLEDevice, tip = "LE" }); } } catch (Exception ex) { MessageDialog messageDialog1 = new MessageDialog(ex.ToString()); await messageDialog1.ShowAsync(); } } } PRing.IsActive = false; }
public bool SendResponse(BluetoothDevice device, int requestId, Android.Bluetooth.GattStatus status, int offset, byte [] value) { return SendResponse (device, requestId, (ProfileState) status, offset, value); }
/// <summary> /// Initializes a new instance of the <see cref="AndroidBluetoothDevice" /> class. /// </summary> /// <param name="device">The device.</param> public AndroidBluetoothDevice(BluetoothDevice device) { _device = device; _uuid = UUID.RandomUUID(); }
private void OnBluetoothDisconnectedFromServer(BluetoothDevice device) { Debug.Log("Event - DisconnectedFromServer: " + BluetoothExamplesTools.FormatDevice(device)); // Stopping Unity networking on Bluetooth failure Network.Disconnect(); }
public void OnLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { throw new NotImplementedException(); }
protected BaseSphero(BluetoothDevice bluetoothDevice) { _bluetoothDevice = bluetoothDevice; }
private async void ConnectGenericDevice() { if (ChosenDevice != null) { await CheckBluetoothStatus(true); // check bluetooth status and activate it if is turned off if (!IsBluetoothEnabled) { AddLog("Can not connect with bluetooth disabled. Turn on the Bluetooth and try again.", AppLog.LogCategory.Warning); return; } // request access to the selected device BluetoothDevice = await BluetoothLEDevice.FromIdAsync(ChosenDevice.Id); DeviceAccessStatus accessStatus = await BluetoothDevice.RequestAccessAsync(); // log AddLog("[Connection: " + accessStatus.ToString() + "]" + " Connecting to " + BluetoothDevice.Name + "...", AppLog.LogCategory.Debug); AddLog("Connecting to " + BluetoothDevice.Name + "...", AppLog.LogCategory.Info); GattCharacteristicsResult hrGattCHaracteristics = null; // try to read the device charateristics try { var gattDeviceServicesResult = await BluetoothDevice.GetGattServicesForUuidAsync(HRserviceGuid); // get services with the HR service GUID // for each service withe the given GUID try to read get foreach (GattDeviceService service in gattDeviceServicesResult.Services) { AddLog("[" + ChosenDevice.Name + "] Found service. " + "\n - Handle: " + service.AttributeHandle.ToString() + "\n - UUID: " + service.Uuid.ToString(), AppLog.LogCategory.Debug); // log if (await service.GetCharacteristicsForUuidAsync(HRCharacteristicGuid) != null) { hrGattCHaracteristics = await service.GetCharacteristicsForUuidAsync(HRCharacteristicGuid); HRReaderService = service; break; } } } catch { AddLog("Device \"" + ChosenDevice.Name + "\" does not support HR service." + "\nSelect another one from the devices list.", AppLog.LogCategory.Warning); return; } // get the HR reader characteristic if (hrGattCHaracteristics != null) { foreach (GattCharacteristic characteristic in hrGattCHaracteristics.Characteristics.Where(c => c.Uuid.Equals(HRCharacteristicGuid))) { HRReaderCharacteristic = characteristic; } } else { // log something return; } // if HR characteristic can't be found, show an error and return if (HRReaderCharacteristic == null) { AddLog("Heart rate monitor characteristic NOT found.", AppLog.LogCategory.Debug); AddLog("Could not connect to Heart Rate service of the device \"" + ChosenDevice.Name + "\".", AppLog.LogCategory.Warning); return; } // if HR characteristic have been found, then start reading process else { AddLog("Heart rate monitor characteristic found [Handle: " + HRReaderCharacteristic.AttributeHandle.ToString() + "]", AppLog.LogCategory.Debug); BeginBluetoothReadProcess(); SwitchConnectButtonToDisconnectButton(); } } else { AddLog("The button should be disabled. Kowalski analisis.", AppLog.LogCategory.Debug); return; } }
private void onBluetoothDevicePicked(BluetoothDevice device) { BluetoothMultiplayerAndroid.Connect(device.address, GameConfig.Port); }
private static BluetoothDevice[] ConvertJavaBluetoothDeviceSet(AndroidJavaObject bluetoothDeviceJavaSet) { try { if (IsAndroidJavaObjectNull(bluetoothDeviceJavaSet)) return null; AndroidJavaObject[] deviceJavaArray = bluetoothDeviceJavaSet.Call<AndroidJavaObject[]>("toArray"); BluetoothDevice[] deviceArray = new BluetoothDevice[deviceJavaArray.Length]; for (int i = 0; i < deviceJavaArray.Length; i++) { deviceArray[i] = new BluetoothDevice(deviceJavaArray[i]); } return deviceArray; } catch (Exception) { Debug.LogError("Error while converting BluetoothDevice Set"); return null; } }
// Return current Bluetooth device public static BluetoothDevice GetCurrentDevice() { if (!PluginAvailable) return null; BluetoothDevice currentDevice; try { currentDevice = new BluetoothDevice(Plugin.Call<String>("getCurrentDevice")); } catch (Exception) { return null; } return currentDevice; }
public AndroidBluetoothDevice(BluetoothDevice device) { this.device = device; this.uuid = UUID.RandomUUID(); }
public override void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_ENABLE_BT: //��������� if (resultCode == Activity.RESULT_OK) { //�����Ѿ��� Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show(); } else { //�û������������ finish(); } break; case REQUEST_CONNECT_DEVICE: //��������ijһ�����豸 if (resultCode == Activity.RESULT_OK) { //�ѵ�������б��е�ij���豸�� string address = data.Extras.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); //��ȡ�б������豸��mac��ַ con_dev = mService.getDevByMac(address); mService.connect(con_dev); } break; } }
public AndroidBluetoothDevice (BluetoothDevice device) { this.device = device; }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); configCodes = Resources.GetStringArray(Resource.Array.ConfigCodes); ModeList = FindViewById <ListView>(Resource.Id.ModeListView); colorView = FindViewById <View>(Resource.Id.ColorExampleView); ArrayAdapter <String> lvAdapter = new ArrayAdapter <String>(this, Android.Resource.Layout.SimpleListItemSingleChoice, configCodes); seekBarHue = FindViewById <SeekBar>(Resource.Id.seekBar1); seekBarSat = FindViewById <SeekBar>(Resource.Id.seekBar2); seekBarVal = FindViewById <SeekBar>(Resource.Id.seekBar3); seekBarHue.Max = 360; seekBarSat.Max = 255; seekBarVal.Max = 255; seekBarHue.ProgressChanged += (object sender, SeekBar.ProgressChangedEventArgs e) => { if (e.FromUser) { ColorDrawable color = (ColorDrawable)colorView.Background; uint colorCode = 0; double Hue = e.Progress; int r, g, b; double h, s, v; h = seekBarHue.Progress; s = (float)seekBarSat.Progress / 255; v = (float)seekBarVal.Progress / 255; HsvToRgb(h, s, v, out r, out g, out b); colorCode += (uint)r; colorCode += (uint)g * 0x100; colorCode += (uint)b * 0x10000; colorCode += (uint)color.Color.A * 0x1000000; String colorString = "#" + colorCode.ToString("X"); Color ccolor = Color.ParseColor(colorString); colorView.SetBackgroundColor(ccolor); TextView HueText = FindViewById <TextView>(Resource.Id.textView1); HueText.Text = "Тон: " + e.Progress; } }; seekBarSat.ProgressChanged += (object sender, SeekBar.ProgressChangedEventArgs e) => { if (e.FromUser) { ColorDrawable color = (ColorDrawable)colorView.Background; uint colorCode = 0; int r, g, b; double h, s, v; h = seekBarHue.Progress; s = (float)seekBarSat.Progress / 255; v = (float)seekBarVal.Progress / 255; HsvToRgb(h, s, v, out r, out g, out b); colorCode += (uint)r; colorCode += (uint)g * 0x100; colorCode += (uint)b * 0x10000; colorCode += (uint)color.Color.A * 0x1000000; String colorString = "#" + colorCode.ToString("X"); Color ccolor = Color.ParseColor(colorString); colorView.SetBackgroundColor(ccolor); TextView SatText = FindViewById <TextView>(Resource.Id.textView2); SatText.Text = "Насыщенность: " + e.Progress; } }; seekBarVal.ProgressChanged += (object sender, SeekBar.ProgressChangedEventArgs e) => { if (e.FromUser) { ColorDrawable color = (ColorDrawable)colorView.Background; uint colorCode = 0; int r, g, b; double h, s, v; h = seekBarHue.Progress; s = (float)seekBarSat.Progress / 255; v = (float)seekBarVal.Progress / 255; HsvToRgb(h, s, v, out r, out g, out b); colorCode += (uint)r; colorCode += (uint)g * 0x100; colorCode += (uint)b * 0x10000; colorCode += (uint)color.Color.A * 0x1000000; String colorString = "#" + colorCode.ToString("X"); Color ccolor = Color.ParseColor(colorString); colorView.SetBackgroundColor(ccolor); TextView ValText = FindViewById <TextView>(Resource.Id.textView3); ValText.Text = "Яркость: " + e.Progress; } }; ModeList.Adapter = lvAdapter; ModeList.ChoiceMode = ChoiceMode.Single; ModeList.SetSelection(0); ModeList.SetItemChecked(0, true); AcceptButton = FindViewById <Button>(Resource.Id.button1); AcceptButton.Click += delegate { AcceptButtonClick(); }; BluetoothAdapter btAdapter = BluetoothAdapter.DefaultAdapter; if (btAdapter == null) { throw new Exception("No Bluetooth adapter found."); } if (!btAdapter.IsEnabled) { throw new Exception("Bluetooth adapter is not enabled."); } BluetoothDevice device = (from bd in btAdapter.BondedDevices where bd.Name == "ColorMusic" select bd).FirstOrDefault(); if (device == null) { throw new Exception("Named device not found."); } btSocket = device.CreateInsecureRfcommSocketToServiceRecord(UUID.FromString(btUUID)); try { btSocket.Connect(); } catch (IOException e) { btSocket.Close(); throw new Exception("Can't Connect"); } }
ScanEventArgs(BluetoothDevice device, int rssi) { this.Device = device; this.Rssi = rssi; }
private void onBluetoothClientConnected(BluetoothDevice device) { }
public async Task <bool> ConnectAsync(string _deviceName) { try { BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter; if (adapter == null) { Log("No Bluetooth adapter found."); } else if (!adapter.IsEnabled) { Log("Bluetooth adapter is not enabled."); } List <BluetoothDevice> L = new List <BluetoothDevice>(); foreach (BluetoothDevice d in adapter.BondedDevices) { Log("D: " + d.Name + " " + d.Address + " " + d.BondState.ToString()); L.Add(d); } BluetoothDevice device = null; device = L.Find(j => j.Name == _deviceName); if (device == null) { Log("Named device not found."); } else { Log("Device has been found: " + device.Name + " " + device.Address + " " + device.BondState.ToString()); } socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString(TARGET_UUID)); await socket.ConnectAsync(); if (socket != null && socket.IsConnected) { Log("Connection successful!"); } else { Log("Connection failed!"); } inStream = (InputStreamInvoker)socket.InputStream; outStream = (OutputStreamInvoker)socket.OutputStream; if (socket != null && socket.IsConnected) { Task t = new Task(() => Listen(inStream)); t.Start(); //Task t1 = new Task(() => PingEvent()); //t1.Start(); } else { //throw new Exception("Socket not existing or not connected."); } } catch (Exception e) { //throw new Exception("Socket not existing or not connected."); } return(socket.IsConnected); }
private void onBluetoothDisconnectedFromServer(BluetoothDevice device) { Network.Disconnect(); }
/// <summary> /// Gets a moniker that can be used to connect to the device. /// </summary> /// <param name="device">The device to connect to.</param> /// <returns>The connection moniker.</returns> public static BluetoothConnectionTarget GetConnectionTarget(this BluetoothDevice device) => new BluetoothConnectionTarget(device);
private void onBluetoothConnectToServerFailed(BluetoothDevice device) { }
private void OnBluetoothDevicePicked(BluetoothDevice device) { Debug.Log("Event - DevicePicked: " + BluetoothExamplesTools.FormatDevice(device)); // Trying to connect to a device user had picked AndroidBluetoothMultiplayer.Connect(device.Address, kPort); }
private void onBluetoothConnectedToServer(BluetoothDevice device) { Network.Connect(GameConfig.LocalIp, GameConfig.Port); }
private void OnBluetoothConnectedToServer(BluetoothDevice device) { Debug.Log("Event - ConnectedToServer: " + BluetoothExamplesTools.FormatDevice(device)); // Trying to negotiate a Unity networking connection, // when Bluetooth client connected successfully Network.Connect(kLocalIp, kPort); }
private void OnBluetoothDeviceDiscovered(BluetoothDevice device) { // For demo purposes, just display the device info Debug.Log( string.Format( "Event - DeviceDiscovered(): {0} [{1}], class: {2}, is connectable: {3}", device.Name, device.Address, device.DeviceClass, device.IsConnectable) ); }
public ClientConnectedEventArgs(BluetoothDevice Device, DuplexConnection Connection) { this.Device = Device; this.Connection = Connection; }
protected virtual void OnBluetoothClientDisconnected(BluetoothDevice device) { Debug.Log("Event - ClientDisconnected: " + BluetoothExamplesTools.FormatDevice(device)); }
private void OnBluetoothConnectionToServerFailed(BluetoothDevice device) { Debug.Log("Event - ConnectionToServerFailed: " + BluetoothExamplesTools.FormatDevice(device)); }
public Peripheral(CentralContext centralContext, BluetoothDevice native) : base(native.Name, ToDeviceId(native.Address)) { this.connSubject = new Subject <ConnectionState>(); this.context = new DeviceContext(centralContext, native); }
private async void AppBarButton_Click_1(object sender, RoutedEventArgs e) { try { StoreServicesCustomEventLogger logger = StoreServicesCustomEventLogger.GetDefault(); logger.Log("AddBluetooth"); string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" }; DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher( BluetoothLEDevice.GetDeviceSelectorFromPairingState(false), requestedProperties, DeviceInformationKind.AssociationEndpoint); // Register event handlers before starting the watcher. // Added, Updated and Removed are required to get all nearby devices // deviceWatcher.Added += DeviceWatcher_Added; // deviceWatcher.Updated += DeviceWatcher_Updated; // deviceWatcher.Removed += DeviceWatcher_Removed; // EnumerationCompleted and Stopped are optional to implement. // deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; // deviceWatcher.Stopped += DeviceWatcher_Stopped; // Start the watcher. //deviceWatcher.Start(); var displayInformation = Windows.Graphics.Display.DisplayInformation.GetForCurrentView(); double ScreenWidth = 100; double ScreenHeight = 100; if (displayInformation.CurrentOrientation == Windows.Graphics.Display.DisplayOrientations.Portrait) { ScreenWidth = Math.Round(Window.Current.Bounds.Width * displayInformation.RawPixelsPerViewPixel, 0); ScreenHeight = Math.Round(Window.Current.Bounds.Height * displayInformation.RawPixelsPerViewPixel, 0); } if (displayInformation.CurrentOrientation == Windows.Graphics.Display.DisplayOrientations.Landscape) { ScreenWidth = Math.Round(Window.Current.Bounds.Height * displayInformation.RawPixelsPerViewPixel, 0); ScreenHeight = Math.Round(Window.Current.Bounds.Width * displayInformation.RawPixelsPerViewPixel, 0); } // For devices with software buttons instead hardware else if (displayInformation.CurrentOrientation == Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped) { ScreenWidth = Math.Round(Window.Current.Bounds.Height * displayInformation.RawPixelsPerViewPixel, 0); ScreenHeight = Math.Round(Window.Current.Bounds.Width * displayInformation.RawPixelsPerViewPixel, 0); } Rect rect = new Rect(new Point(ScreenHeight, ScreenWidth), new Point(100, 100)); DevicePicker devicePicker = new DevicePicker(); //devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); // devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothDevice.GetDeviceSelectorFromPairingState(false)); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); var s = await devicePicker.PickSingleDeviceAsync(rect); if (s != null) { var sd = await s.Pairing.PairAsync(); // await new MessageDialog(sd.ToString()+"\n"+ DevicePairingResultStatus.Paired).ShowAsync(); if (sd.Status == DevicePairingResultStatus.Paired || sd.Status == DevicePairingResultStatus.AlreadyPaired || sd.Status == DevicePairingResultStatus.AccessDenied) { //var rfcommServices = await ClassBluetoothDeviceSelect.bluetoothDeviced.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceId.SerialPort.Uuid), BluetoothCacheMode.Uncached); var bluetoothDevice = await BluetoothDevice.FromIdAsync(s.Id); Frame.Navigate(typeof(BlankPageBluettotchDevice), new ClassBluetoothDevice() { namea = s.Name, bluetoothDeviced = bluetoothDevice }); } } } catch (Exception ex) { await new MessageDialog(ex.Message).ShowAsync(); } }
void onBluetoothConnectedToServerEvent(BluetoothDevice device) { Network.Connect(GlobleData.LocalIp, GlobleData.Port); }
public ScanEventArgs(BluetoothDevice device, int rssi, byte[] advertisementData) : this(device, rssi) { this.AdvertisementData = new AdvertisementData(advertisementData); }
void onBluetoothConnectToServerFailedEvent(BluetoothDevice device) { }
public ScanEventArgs(BluetoothDevice device, int rssi, ScanRecord scanRecord) : this(device, rssi) { this.AdvertisementData = new AdvertisementData(scanRecord); }
void onBluetoothDevicePickedEvent(BluetoothDevice device) { BluetoothMultiplayerAndroid.Connect(device.address, (ushort)GlobleData.Port); }
// Implemented for BluetoothAdapter.ILeScanCallback public void OnLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { manager.OnDeviceFound(device, ParseBroadcastPayloadFromScanRecord(scanRecord)); }
void onBluetoothDisconnectedFromServerEvent(BluetoothDevice device) { Network.Disconnect(); }
/// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception) { Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; // TODO: notify connected //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // rootPage.NotifyUser("Connected to Client: " + remoteDevice.Name, NotifyType.StatusMessage); //}); // Infinite read buffer loop while (true) { try { uint size = await reader.LoadAsync(sizeof(uint)); if (size < sizeof(uint)) { remoteDisconnection = true; return; } var type = DataHandler.RecognizeDataType(reader); switch (type) { case DataHandlerTypes.ByteArray: DataReceived?.Invoke(this, new DataReceivedEventArgs(await DataHandler.ReadByteArrayAsync(reader), typeof(byte[]))); break; case DataHandlerTypes.Int32: DataReceived?.Invoke(this, new DataReceivedEventArgs(await DataHandler.ReadInt32Async(reader), typeof(Int32))); break; case DataHandlerTypes.String: DataReceived?.Invoke(this, new DataReceivedEventArgs(await DataHandler.ReadStringAsync(reader), typeof(string))); break; case DataHandlerTypes.IBuffer: DataReceived?.Invoke(this, new DataReceivedEventArgs(await DataHandler.ReadIBufferAsync(reader), typeof(IBuffer))); break; } } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { // Client Disconnected Successfully break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); // Client Disconnected Successfully } }
void onBluetoothDiscoveryDeviceFoundEvent(BluetoothDevice device) { }
protected override void Process(DateTime now) { if (!Monitor.TryEnter(_hidReport) || State != DsState.Connected) { return; } try { #region Light bar manipulation if (!GlobalConfiguration.Instance.IsLightBarDisabled) { if (Battery < DsBattery.Medium) { if (!_mFlash) { _hidReport[12] = _hidReport[13] = 0x40; _mFlash = true; m_Queued = 1; } } else { if (_mFlash) { _hidReport[12] = _hidReport[13] = 0x00; _mFlash = false; m_Queued = 1; } } } if (GlobalConfiguration.Instance.Brightness != _mBrightness) { _mBrightness = GlobalConfiguration.Instance.Brightness; } SetLightBarColor(PadId); #endregion if ((now - m_Last).TotalMilliseconds >= 500) { if (_hidReport[7] > 0x00 || _hidReport[8] > 0x00) { m_Queued = 1; } } if (!m_Blocked && m_Queued > 0) { m_Last = now; m_Blocked = true; m_Queued--; BluetoothDevice.HID_Command(HciHandle.Bytes, Get_SCID(L2CAP.PSM.HID_Command), _hidReport); } } finally { Monitor.Exit(_hidReport); } }
void onBluetoothClientConnectedEvent(BluetoothDevice device) { }
void testConnect(BluetoothDevice btdev) { byte[] bta = new byte[8]; bta[0] = 0x00; bta[1] = 0x00; bta[2] = 0x00; bta[3] = 0x06; bta[4] = 0x66; bta[5] = 0x03; bta[6] = 0x09; bta[7] = 0xE8; BluetoothDevice btd = btdev;// new BluetoothDevice("test", bta); System.Net.Sockets.NetworkStream nws; //first download the layout program byte[] buf; try { ddump("connecting to " + btd.AddressStr); nws = btd.Connect(StandardServices.SerialPortServiceGuid); if (nws == null) { ddump("Connect failed!"); return; } buf = null; if (radioFP.Checked) { buf = Encoding.Unicode.GetBytes(Intermec.Printer.Language.Fingerprint.Demo.FP_2_WalmartLabel()); } else if (radioIPL.Checked) { buf = Encoding.Unicode.GetBytes(Intermec.Printer.Language.Fingerprint.Demo.IPL_2_WalmartLabel()); } if (buf == null) { return; } ddump("writing 1..."); nws.Write(buf, 0, buf.Length); ddump("...writing 1 done"); if (nws.DataAvailable) { ddump("reading..."); readData(nws); ddump("...reading done"); } ddump("closing net stream..."); nws.Close(); ddump("... net stream closed"); } catch (System.IO.IOException ex) { ddump("Exception: " + ex.Message); } catch (System.Net.Sockets.SocketException ex) { ddump("Exception: " + ex.Message); } catch (Exception ex) { ddump("Exception: " + ex.Message); } }
private void SetSelectedDev(BluetoothDevice dev) { HoneywellDeviceHub.GetInstance().SelectedBleDev = dev; }
public async Task <DeviceInformation> PickSingleDeviceAsync() { NativeMethods.BLUETOOTH_SELECT_DEVICE_PARAMS sdp = new NativeMethods.BLUETOOTH_SELECT_DEVICE_PARAMS(); sdp.dwSize = Marshal.SizeOf(sdp); sdp.hwndParent = Process.GetCurrentProcess().MainWindowHandle; sdp.numDevices = 1; /*if(!string.IsNullOrEmpty(Appearance.Title)) * { * sdp.info = Appearance.Title; * }*/ //defaults sdp.fShowAuthenticated = true; sdp.fShowUnknown = false; List <int> codMasks = new List <int>(); if (Filter.SupportedDeviceSelectors.Count > 0) { foreach (string filter in Filter.SupportedDeviceSelectors) { var parts = filter.Split(':'); switch (parts[0]) { case "bluetoothClassOfDevice": int codMask = 0; if (int.TryParse(parts[1], NumberStyles.HexNumber, null, out codMask)) { codMasks.Add(codMask); break; } break; case "bluetoothPairingState": bool pairingState = bool.Parse(parts[1]); if (pairingState) { sdp.fShowAuthenticated = true; sdp.fShowUnknown = false; } else { sdp.fShowAuthenticated = false; sdp.fShowUnknown = true; } break; } } } sdp.hwndParent = NativeMethods.GetForegroundWindow(); if (codMasks.Count > 0) { // marshal the CODs to native memory sdp.numOfClasses = codMasks.Count; sdp.prgClassOfDevices = Marshal.AllocHGlobal(8 * codMasks.Count); for (int i = 0; i < codMasks.Count; i++) { Marshal.WriteInt32(IntPtr.Add(sdp.prgClassOfDevices, 8 * i), codMasks[i]); } } /*if (Filter.SupportedDeviceSelectors.Count > 0) * { * _callback = new NativeMethods.PFN_DEVICE_CALLBACK(FilterDevices); * sdp.pfnDeviceCallback = _callback; * //sdp.pvParam = Marshal.AllocHGlobal(4); * //Marshal.WriteInt32(sdp.pvParam, 1); * }*/ bool success = NativeMethods.BluetoothSelectDevices(ref sdp); if (sdp.prgClassOfDevices != IntPtr.Zero) { Marshal.FreeHGlobal(sdp.prgClassOfDevices); sdp.prgClassOfDevices = IntPtr.Zero; sdp.numOfClasses = 0; } if (success) { BLUETOOTH_DEVICE_INFO info = Marshal.PtrToStructure <BLUETOOTH_DEVICE_INFO>(sdp.pDevices); NativeMethods.BluetoothSelectDevicesFree(ref sdp); foreach (string query in Filter.SupportedDeviceSelectors) { var parts = query.Split(':'); if (parts[0] == "bluetoothService") { Guid serviceUuid = Guid.Parse(parts[1]); foreach (Guid g in BluetoothDevice.GetRfcommServices(ref info)) { if (g == serviceUuid) { return(new DeviceInformation(info, serviceUuid)); } } return(null); } } return(new DeviceInformation(info)); } return(null); }
public DeviceContext(BluetoothDevice device) { this.NativeDevice = device; this.Callbacks = new GattCallbacks(); this.Actions = new ConcurrentQueue <Func <Task> >(); }
private void OnBluetoothClientConnected(BluetoothDevice device) { Debug.Log("Event - ClientConnected: " + BluetoothExamplesTools.FormatDevice(device)); }
/// <summary> /// Connect to the server. This just calls BluetoothClient.Connect() /// </summary> /// <param name="device">The bluetooth device to connect to.</param> /// <returns></returns> public bool Connect(BluetoothDevice device) { return(bt.Connect(device)); }
public void OnLeScan(BluetoothDevice bleDevice, int rssi, byte[] scanRecord) { Trace.Message("Adapter.LeScanCallback: " + bleDevice.Name); _adapter.HandleDiscoveredDevice(new Device(_adapter, bleDevice, null, null, rssi, scanRecord)); }
public static string FormatDevice(BluetoothDevice device) { return string.Format("{0} [{1}], class: {2}, connectable: {3}", device.Name, device.Address, device.DeviceClass, device.IsConnectable); }
/// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception e) { //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage); //}); Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // rootPage.NotifyUser("Connected to Client: " + remoteDevice.Name, NotifyType.StatusMessage); //}); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // ConversationListBox.Items.Add("Received: " + message); //}); } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // rootPage.NotifyUser("Client Disconnected Successfully", NotifyType.StatusMessage); //}); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // rootPage.NotifyUser("Client disconnected", NotifyType.StatusMessage); //}); } }
/// <summary> /// Invoked once the user has selected the device to connect to. /// Once the user has selected the device, /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ConnectButton_Click(object sender, RoutedEventArgs e) { // Make sure user has selected a device first if (resultsListView.SelectedItem != null) { rootPage.NotifyUser("Connecting to remote device. Please wait...", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Please select an item to connect to", NotifyType.ErrorMessage); return; } RfcommChatDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as RfcommChatDeviceDisplay; // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(deviceInfoDisp.Id).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { rootPage.NotifyUser("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices", NotifyType.ErrorMessage); return; } // If not, try to get the Bluetooth device try { bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id); } catch (Exception ex) { rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); return; } // If we were unable to get a valid Bluetooth device object, // it's most likely because the user has specified that all unpaired devices // should not be interacted with. if (bluetoothDevice == null) { rootPage.NotifyUser("Bluetooth Device returned null. Access Status = " + accessStatus.ToString(), NotifyType.ErrorMessage); } // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { chatService = rfcommServices.Services[0]; } else { rootPage.NotifyUser( "Could not discover the chat service on the remote device", NotifyType.StatusMessage); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { rootPage.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { rootPage.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; deviceWatcher.Stop(); lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); SetChatUI(attributeReader.ReadString(serviceNameLength), bluetoothDevice.Name); chatWriter = new DataWriter(chatSocket.OutputStream); DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND rootPage.NotifyUser("Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; break; default: throw; } } }
public BluetoothDevice ToDevice() { BluetoothDevice result = new BluetoothDevice(Address); result.SetClassOfDevice(classOfDevice); return result; }
public BluetoothDeviceEvents(BluetoothDevice This) { this.This = This; }