// Connects to the device public void ConnectToDevice() { Task cTask = Task.Factory.StartNew(() => { if (!adapter.IsEnabled) { adapter.Enable(); } adapter.StartDiscovery(); ICollection <BluetoothDevice> devices = adapter.BondedDevices; if (devices.Count != 0) { foreach (var device in devices) { if (device.Name.Contains("raspberrypi")) { cDevice = device; } } } if (cDevice != null) { Java.Util.UUID uuid = Java.Util.UUID.FromString("94f39d29-7d6d-437d-973b-fba39e49d4ee"); try { cSocket = cDevice.CreateRfcommSocketToServiceRecord(uuid); while (!cSocket.IsConnected) { cSocket.Connect(); } string str; while ((str = ReadLetter().Result) != "") { if (str.Contains("hi")) { RunOnUiThread(() => Snackbar.Make(Window.DecorView.RootView, "Connected!", Snackbar.LengthLong).Show()); SendCommand("hello"); break; } } } catch (Exception) { RunOnUiThread(() => Snackbar.Make(Window.DecorView.RootView, "Error while connecting to the device", Snackbar.LengthLong).Show()); } } else { RunOnUiThread(() => Snackbar.Make(Window.DecorView.RootView, "Error while connecting to the device. Check bluetooth connection", Snackbar.LengthLong).Show()); } }); Task.WaitAll(new Task[] { cTask }); }
internal static Guid FromNative(this NativeGuid guid) { #if __ANDROID__ return(Guid.Parse(guid.ToString())); #elif __IOS__ return(Guid.Parse(guid.AsString())); #elif WINDOWS_PHONE_APP return(guid); #endif }
internal static NativeGuid ToNative(this Guid guid) { #if __ANDROID__ return(NativeGuid.FromString(guid.ToString("D"))); #elif __IOS__ return(new NativeGuid(guid.ToString("D"))); #elif WINDOWS_PHONE_APP return(guid); #endif }
private bool EnableNotification(string address, Java.Util.UUID serUuid, Java.Util.UUID charUuit) { if (mLeService == null) { return(false); } var gatt = mLeService.GetBluetoothGatt(address); var c = GattUtil.GetGattCharacteristic(gatt, serUuid, charUuit); return(SetCharacteristieNotification(gatt, c, true)); }
public virtual Guid FromJavaUuid(Java.Util.UUID uuid) { var str = uuid.ToString(); var guid = new Guid(str); #if true || DEBUG var txtN = guid.ToString("D"); // Hyphens no braces. var txtJ = uuid.ToString(); Utils.MiscUtils.Trace_Assert(string.Equals(txtJ, txtN, StringComparison.OrdinalIgnoreCase), "NOT equal " + txtJ + " and " + txtN); #endif return(guid); }
public bool Connect(Android.Content.Context context, Button btConnect, out BluetoothSocket socket, out string message) { message = string.Empty; if (btConnect != null) { btConnect.Text = "Connecting.."; } socket = null; //BluetoothDevice device = null; string result = string.Empty; try { Java.Util.UUID id = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"); BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter; adapter.StartDiscovery(); //BluetoothManager btm = (BluetoothManager)context.GetSystemService(Context.BluetoothService); if (adapter.BondedDevices.Count(x => x.Name == "HC-06") == 0) { adapter = null; message = "HC-06 device is not paired"; btConnect.Text = "Connect"; return(false); } BluetoothDevice k9BTdevice = adapter.BondedDevices.First(x => x.Name == "HC-06"); socket = k9BTdevice.CreateRfcommSocketToServiceRecord(id); try { k9BTdevice.SetPairingConfirmation(false); // k9BTdevice.Dispose(); k9BTdevice.SetPairingConfirmation(true); btConnect.Text = "Connect"; } catch (Exception ex) { }; k9BTdevice.CreateBond(); //context.ApplicationContext. socket.Connect(); btConnect.Text = "Connected"; } catch (Exception ex) { message = ex.Message; return(false); } return(true); }
async Task AddTileAsync() { string tileName = "8Ball"; try { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final android.graphics.BitmapFactory.Options options = new android.graphics.BitmapFactory.Options(); BitmapFactory.Options options = new BitmapFactory.Options(); options.InScaled = false; BandIcon tileIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.tile, options)); //BandIcon badgeIcon = mCheckboxBadging.Checked ? BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options)) : null; BandIcon badgeIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options)); uuid = Java.Util.UUID.RandomUUID(); BandTile tile = new BandTile.Builder(uuid, tileName, tileIcon) .SetTileSmallIcon(badgeIcon) // .SetTheme(mCheckboxCustomTheme.Checked ? mThemeView.Theme : null) .Build(); try { var result = await Model.Instance.Client.TileManager.AddTileTaskAsync(this, tile); if (result) { Toast.MakeText(this, "Tile added", ToastLength.Short).Show(); } else { Toast.MakeText(this, "Unable to add tile", ToastLength.Short).Show(); } } catch (Exception ex) { Util.ShowExceptionAlert(this, "Add tile", ex); } // Refresh our tile list and count await RefreshData(); RefreshControls(); } catch (Exception e) { Util.ShowExceptionAlert(this, "Add tile", e); } }
public async Task OpenOutputStream() { try { if (btAdapter == null) { btAdapter = BluetoothAdapter.DefaultAdapter; var devices = btAdapter.BondedDevices; if (devices != null && devices.Count > 0) { printer = devices.FirstOrDefault(); UUID = Java.Util.UUID.FromString(UuidUniverseProfile); //aguarda 1s Thread.Sleep(2300); //aguarda 1s //Thread.Sleep(1000); socket = printer.CreateRfcommSocketToServiceRecord(UUID); socket.Connect(); if (socket.IsConnected) { mmOutStream = socket.OutputStream; } } } else { if (!btAdapter.IsEnabled) { btAdapter.Enable(); } } } catch (System.Exception ex) { Toast.MakeText(Android.App.Application.Context, "Não foi possível se conectar na impressora {0}\n\nVerifique as configurações de impressão e tente novamente", ToastLength.Long).Show(); return; } }
private bool SetupBlueTooth() { _bluetoothAdapter = BluetoothAdapter.DefaultAdapter; // If the adapter is null, then Bluetooth is not supported if (_bluetoothAdapter == null) { _testLabel.Text = "Bluetooth: Failed Adapter"; return(false); } _bluetoothAdapter.Enable(); _myUUID = Java.Util.UUID.FromString("ec79da00-853f-11e4-b4a9-0800200c9a69"); _myName = _myUUID.ToString(); return(true); }
public async Task <DeviceConnectionResponse> Connect() { if (this.socket == null) { Java.Util.UUID uuid = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); this.socket = this.device.CreateRfcommSocketToServiceRecord(uuid); } try { await this.socket.ConnectAsync(); return(DeviceConnectionResponse.Success); } catch (Java.IO.IOException ex) { Log.Error("BluetoothSocket.Connect()", ex.Message); return(DeviceConnectionResponse.Failure( new DeviceConnectionException(this, "BluetoothSocket.ConnectAsync()", ex))); } }
public ConnectThread(ContentPage contentPage, BluetoothDevice device) { BluetoothSocket auxSocket = null; mmDevice = device; mmContentPage = contentPage; try { Java.Util.UUID uuid = Java.Util.UUID.FromString(mUUID); auxSocket = (BluetoothSocket)mmDevice.Class.GetMethod("createRfcommSocket", new Java.Lang.Class[] { Java.Lang.Integer.Type }).Invoke(mmDevice, 1); Debug.WriteLine("BluetoothSocket: CREATED"); Debug.WriteLine($"Name: {device.Name}, Address: {device.Address}"); } catch (Java.IO.IOException e) { Debug.WriteLine("BluetoothSocket: NOT CREATED"); e.PrintStackTrace(); } mmSocket = auxSocket; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_main); Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); fab = FindViewById <FloatingActionButton>(Resource.Id.fab); fab.Click += FabOnClick; tvOutput = FindViewById <TextView>(Resource.Id.output); tvStatus = FindViewById <TextView>(Resource.Id.status); tvStatus.MovementMethod = new ScrollingMovementMethod(); devices.Add("System GPS", null); var devicePicker = FindViewById <Spinner>(Resource.Id.device_picker); Java.Util.UUID SERIAL_UUID = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); var adapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter; if (adapter != null) { foreach (var d in adapter.BondedDevices.Where(d => { var uuids = d.GetUuids(); return(uuids != null && uuids.Any(t => t.Uuid.ToString().Equals("00001101-0000-1000-8000-00805F9B34FB", StringComparison.InvariantCultureIgnoreCase))); })) { devices[d.Name + " " + d.Address] = d.Address; } } devicePicker.Adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, devices.Keys.ToArray()); devicePicker.SetSelection(0); if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != Permission.Granted) { ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.WriteExternalStorage }, 1000); } LogD.Debug("Started"); }
private async void Start() { startButton.Enabled = false; status = FindViewById <TextView>(Resource.Id.output); var devicePicker = FindViewById <Spinner>(Resource.Id.device_picker); var id = devicePicker.SelectedItem.ToString(); var btAddress = devices[id]; if (btAddress == null) { if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Permission.Granted) { ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.AccessFineLocation }, 1000); return; } if (launched) { return; } launched = true; listener = new NmeaParser.SystemNmeaDevice(ApplicationContext); } else //Bluetooth { try { status.Text = "Opening bluetooth..."; var adapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter; var bt = Android.Bluetooth.BluetoothAdapter.DefaultAdapter.GetRemoteDevice(btAddress); Java.Util.UUID SERIAL_UUID = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for Serial Device Service socket = bt.CreateRfcommSocketToServiceRecord(SERIAL_UUID); try { await socket.ConnectAsync(); } catch (Java.IO.IOException) { // This sometimes fails. Use fallback approach to open socket // Based on https://stackoverflow.com/a/41627149 socket.Dispose(); var m = bt.Class.GetMethod("createRfcommSocket", new Java.Lang.Class[] { Java.Lang.Integer.Type }); socket = m.Invoke(bt, new Java.Lang.Object[] { 1 }) as Android.Bluetooth.BluetoothSocket; socket.Connect(); } listener = new NmeaParser.StreamDevice(socket.InputStream); } catch (System.Exception ex) { socket?.Dispose(); socket = null; status.Text += "\nError opening Bluetooth device:\n" + ex.Message; } } if (listener != null) { listener.MessageReceived += Listener_MessageReceived; status.Text += "\nOpening device..."; await listener.OpenAsync(); status.Text += "\nConnected!"; startButton.Enabled = !(stopButton.Enabled = true); } else { startButton.Enabled = !(stopButton.Enabled = false); } }
public static Task SendMessageTaskAsync(this IBandNotificationManager manager, Java.Util.UUID tileId, string title, string body, Java.Util.Date date, MessageFlags flags) { return(manager.SendMessageAsync(tileId, title, body, date, flags).AsTask()); }
public static Task ShowDialogTaskAsync(this IBandNotificationManager manager, Java.Util.UUID tileId, string title, string body) { return(manager.ShowDialogAsync(tileId, title, body).AsTask()); }
public static Task SendMessageTaskAsync(this IBandNotificationManager manager, Java.Util.UUID tileId, string title, string body, DateTime date) { return(manager.SendMessageTaskAsync(tileId, title, body, date, false)); }
public static Task SendMessageTaskAsync(this IBandNotificationManager manager, Java.Util.UUID tileId, string title, string body, DateTime date, bool showDialog) { return(manager.SendMessageTaskAsync(tileId, title, body, date, showDialog ? MessageFlags.ShowDialog : MessageFlags.None)); }
public static Uuid ToUuid(this Java.Util.UUID uuid) { return(new Uuid((ulong)uuid.MostSignificantBits, (ulong)uuid.LeastSignificantBits)); }
public static Guid ToGuid(this Java.Util.UUID self) { return(Guid.Parse(self.ToString())); }
public bool ConnectLeGattDevice(Context context, BluetoothDevice device) { try { BtGattDisconnect(); _gattConnectionState = State.Connecting; _gattServicesDiscovered = false; _btGattSppInStream = new MemoryQueueBufferStream(true); _btGattSppOutStream = new BGattOutputStream(this); _bluetoothGatt = device.ConnectGatt(context, false, new BGattCallback(this)); if (_bluetoothGatt == null) { LogString("*** ConnectGatt failed"); return(false); } _btGattConnectEvent.WaitOne(2000, false); if (_gattConnectionState != State.Connected) { LogString("*** GATT connection timeout"); return(false); } _btGattDiscoveredEvent.WaitOne(2000, false); if (!_gattServicesDiscovered) { LogString("*** GATT service discovery timeout"); return(false); } IList <BluetoothGattService> services = _bluetoothGatt.Services; if (services == null) { LogString("*** No GATT services found"); return(false); } #if DEBUG foreach (BluetoothGattService gattService in services) { if (gattService.Uuid == null || gattService.Characteristics == null) { continue; } Android.Util.Log.Info(Tag, string.Format("GATT service: {0}", gattService.Uuid)); foreach (BluetoothGattCharacteristic gattCharacteristic in gattService.Characteristics) { if (gattCharacteristic.Uuid == null) { continue; } Android.Util.Log.Info(Tag, string.Format("GATT characteristic: {0}", gattCharacteristic.Uuid)); Android.Util.Log.Info(Tag, string.Format("GATT properties: {0}", gattCharacteristic.Properties)); } } #endif _gattCharacteristicSppRead = null; _gattCharacteristicSppWrite = null; _gattCharacteristicUuidSppRead = null; _gattCharacteristicUuidSppWrite = null; BluetoothGattService gattServiceSpp = _bluetoothGatt.GetService(GattServiceCarlySpp); BluetoothGattCharacteristic gattCharacteristicSpp = gattServiceSpp?.GetCharacteristic(GattCharacteristicCarlySpp); if (gattCharacteristicSpp != null) { if ((gattCharacteristicSpp.Properties & (GattProperty.Read | GattProperty.Write | GattProperty.Notify)) == (GattProperty.Read | GattProperty.Write | GattProperty.Notify)) { _gattCharacteristicSppRead = gattCharacteristicSpp; _gattCharacteristicSppWrite = gattCharacteristicSpp; _gattCharacteristicUuidSppRead = GattCharacteristicCarlySpp; _gattCharacteristicUuidSppWrite = GattCharacteristicCarlySpp; #if DEBUG Android.Util.Log.Info(Tag, "SPP characteristic Carly found"); #endif } } else { gattServiceSpp = _bluetoothGatt.GetService(GattServiceWgSoftSpp); BluetoothGattCharacteristic gattCharacteristicSppRead = gattServiceSpp?.GetCharacteristic(GattCharacteristicWgSoftSppRead); BluetoothGattCharacteristic gattCharacteristicSppWrite = gattServiceSpp?.GetCharacteristic(GattCharacteristicWgSoftSppWrite); if (gattCharacteristicSppRead != null && gattCharacteristicSppWrite != null) { if (((gattCharacteristicSppRead.Properties & (GattProperty.Read | GattProperty.Notify)) == (GattProperty.Read | GattProperty.Notify)) && ((gattCharacteristicSppWrite.Properties & (GattProperty.Write)) == (GattProperty.Write))) { _gattCharacteristicSppRead = gattCharacteristicSppRead; _gattCharacteristicSppWrite = gattCharacteristicSppWrite; _gattCharacteristicUuidSppRead = GattCharacteristicWgSoftSppRead; _gattCharacteristicUuidSppWrite = GattCharacteristicWgSoftSppWrite; } #if DEBUG Android.Util.Log.Info(Tag, "SPP characteristic WgSoft found"); #endif } } if (_gattCharacteristicSppRead == null || _gattCharacteristicSppWrite == null) { LogString("*** No GATT SPP characteristic found"); return(false); } if (!_bluetoothGatt.SetCharacteristicNotification(_gattCharacteristicSppRead, true)) { LogString("*** GATT SPP enable notification failed"); return(false); } BluetoothGattDescriptor descriptor = _gattCharacteristicSppRead.GetDescriptor(GattCharacteristicConfig); if (descriptor == null) { LogString("*** GATT SPP config descriptor not found"); return(false); } if (BluetoothGattDescriptor.EnableNotificationValue == null) { LogString("*** GATT SPP EnableNotificationValue not present"); return(false); } _gattWriteStatus = GattStatus.Failure; descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray()); if (!_bluetoothGatt.WriteDescriptor(descriptor)) { LogString("*** GATT SPP write config descriptor failed"); return(false); } if (!_btGattWriteEvent.WaitOne(2000)) { LogString("*** GATT SPP write config descriptor timeout"); return(false); } if (_gattWriteStatus != GattStatus.Success) { LogString("*** GATT SPP write config descriptor status failure"); return(false); } #if false byte[] sendData = Encoding.UTF8.GetBytes("ATI\r"); _btGattSppOutStream.Write(sendData, 0, sendData.Length); while (_btGattReceivedEvent.WaitOne(2000, false)) { #if DEBUG Android.Util.Log.Info(Tag, "GATT SPP data received"); #endif } while (_btGattSppInStream.HasData()) { int data = _btGattSppInStream.ReadByteAsync(); if (data < 0) { break; } #if DEBUG Android.Util.Log.Info(Tag, string.Format("GATT SPP byte: {0:X02}", data)); #endif } #endif return(true); } catch (Exception) { _gattConnectionState = State.Disconnected; _gattServicesDiscovered = false; return(false); } }
static Guid AsGUID(Java.Util.UUID uuid) { return(Guid.Parse(uuid.ToString())); }
public static Task SendMessageTaskAsync(this IBandNotificationManager manager, Java.Util.UUID tileId, string title, string body, DateTime date, MessageFlags flags) { return(manager.SendMessageTaskAsync(tileId, title, body, new Java.Util.Date(date.Year, date.Month, date.Day), flags)); }
async Task AddTileAsync () { string tileName = "8Ball"; try { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final android.graphics.BitmapFactory.Options options = new android.graphics.BitmapFactory.Options(); BitmapFactory.Options options = new BitmapFactory.Options(); options.InScaled = false; BandIcon tileIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.tile, options)); //BandIcon badgeIcon = mCheckboxBadging.Checked ? BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options)) : null; BandIcon badgeIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options)); uuid = Java.Util.UUID.RandomUUID(); BandTile tile = new BandTile.Builder(uuid, tileName, tileIcon) .SetTileSmallIcon(badgeIcon) // .SetTheme(mCheckboxCustomTheme.Checked ? mThemeView.Theme : null) .Build(); try { var result = await Model.Instance.Client.TileManager.AddTileTaskAsync(this, tile); if (result) { Toast.MakeText(this, "Tile added", ToastLength.Short).Show(); } else { Toast.MakeText(this, "Unable to add tile", ToastLength.Short).Show(); } } catch (Exception ex) { Util.ShowExceptionAlert(this, "Add tile", ex); } // Refresh our tile list and count await RefreshData(); RefreshControls(); } catch (Exception e) { Util.ShowExceptionAlert(this, "Add tile", e); } }
public static Task SendMessageTaskAsync(this IBandNotificationManager manager, Java.Util.UUID tileId, string title, string body, DateTime date, MessageFlags flags) { var javaDate = new Java.Util.Date(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second); return(manager.SendMessageTaskAsync(tileId, title, body, javaDate, flags)); }
public static int GetAssignedNumber(Java.Util.UUID uuid) { // Keep only the significant bits of the UUID return((int)((uuid.MostSignificantBits & 0x0000FFFF00000000L) >> 32)); }
public static async Task <bool> SetPagesTaskAsync(this IBandTileManager manager, Java.Util.UUID tileId, params PageData[] pageDatas) { return((bool)await manager.SetPagesAsync(tileId, pageDatas).AsTask()); }
void IBluetoothListener.Construct(Guid service) { _svcClassOrig = service; _svcClass = _fcty.ToJavaUuid(service); }
public static async Task <bool> RemoveTileTaskAsync(this IBandTileManager manager, Java.Util.UUID tileId) { return((bool)await manager.RemoveTileAsync(tileId).AsTask()); }
public static Task SendMessageTaskAsync(this IBandNotificationManager manager, Java.Util.UUID tileId, string title, string body, DateTime date, MessageFlags flags) { var javaDate = new Java.Util.Date((long)(date.ToUniversalTime() - JavaEpoch).TotalMilliseconds); return(manager.SendMessageTaskAsync(tileId, title, body, javaDate, flags)); }