public async Task Print(string deviceName, string text)
        {
            using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
            {
                BluetoothDevice device = (from bd in bluetoothAdapter?.BondedDevices
                                          where bd?.Name == deviceName
                                          select bd).FirstOrDefault();
                try
                {
                    if (device != null)
                    {
                        using (BluetoothSocket bluetoothSocket = device?.
                                                                 CreateRfcommSocketToServiceRecord(
                                   UUID.FromString("00001101-0000-1000-8000-00805F9B34FB")))

                        {
                            bluetoothSocket?.Connect();
                            byte[] buffer = Encoding.UTF8.GetBytes(text);
                            bluetoothSocket?.OutputStream.Write(buffer, 0, buffer.Length);
                            bluetoothSocket.Close();
                        }
                    }
                    else
                    {
                        await Application.Current.MainPage.DisplayAlert("Hata Mesajı", "Yazıcı seçimi boş geçilemez!!!", "Cancel");
                    }
                }
                catch (Exception exp)
                {
                    throw exp;
                }
            }
        }
Ejemplo n.º 2
0
        public override void OnReceive(Context context, Intent intent)
        {
            var hostAddress    = intent.GetStringExtra(HostAddressTag);
            var workId         = intent.GetStringExtra(WorkIdTag);
            var notificationId = intent.GetIntExtra(NotificationIdTag, 0);

            if (workId != null && notificationId != 0 && hostAddress != null)
            {
                Log.Debug("Aborting work for {Action} {NotificationId} {WorkId}", intent.Action, notificationId, workId);
                try
                {
                    WorkManager.GetInstance(Application.Context).CancelWorkById(UUID.FromString(workId));
                    NotificationHelper.DestroyNotification(notificationId);

                    switch (intent.Action)
                    {
                    case ActionKindShutdown:
                        SystemStateManager.Clear(hostAddress, SystemStateKind.Shutdown);
                        break;

                    case ActionKindHibernate:
                        SystemStateManager.Clear(hostAddress, SystemStateKind.Hibernate);
                        break;

                    case ActionKindRestart:
                        SystemStateManager.Clear(hostAddress, SystemStateKind.Restart);
                        break;
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }
        }
Ejemplo n.º 3
0
        public static void PrintNew(string bt_printer)
        {
            try{
                string path      = Android.OS.Environment.ExternalStorageDirectory.ToString();
                string filename  = "ic_logo.png";
                string fullPath  = System.IO.Path.Combine(path, filename);
                byte[] dataBytes = System.IO.File.ReadAllBytes(fullPath);
                Bitmap icon      = BitmapFactory.DecodeFile(fullPath);
                var    ms        = new MemoryStream();
                icon.Compress(Bitmap.CompressFormat.Png, 90, ms);
                var iconBytes = ms.ToArray();

                if (bt_printer != "" || bt_printer != null || bt_printer.Length > 0)
                {
                    byte[]          SELECT_BIT_IMAGE_MODE = { 0x1B, 0x2A, 33, 255, 3 };
                    BluetoothSocket socket = null;

                    SELECT_BIT_IMAGE_MODE = iconBytes;

                    BluetoothDevice hxm             = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(bt_printer);
                    UUID            applicationUUID = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
                    socket = hxm.CreateRfcommSocketToServiceRecord(applicationUUID);
                    socket.Connect();

                    socket.OutputStream.Write(SELECT_BIT_IMAGE_MODE, 0, SELECT_BIT_IMAGE_MODE.Length);
                    socket.Close();
                }
            }catch (Exception ex) {
                Shared.Services.Logs.Insights.Send("Print", ex);
            }
        }
Ejemplo n.º 4
0
        private async void StartBeaconing()
        {
            if (!this.BeaconServiceReady)
            {
                System.Diagnostics.Debug.WriteLine("Beaconing cannot be started.  Service is not ready.");
                return;
            }

            this.StopBeaconing();

            // fetch beacon regions
            var ServerBeaconRegions = await Lighthouse.GetBeaconRegions();

            // start monitoring on each region
            foreach (Lighthouse.LHPEBeaconRegion region in ServerBeaconRegions)
            {
                SecureBeaconRegion BeaconRegion = null;
                if (region.Minor != null)
                {
                    BeaconRegion = new SecureBeaconRegion(region.Id, UUID.FromString(region.UUID), new Integer(Convert.ToInt32(region.Major)), new Integer(Convert.ToInt32(region.Minor)));
                }
                else if (region.Major != null)
                {
                    BeaconRegion = new SecureBeaconRegion(region.Id, UUID.FromString(region.UUID), new Integer(Convert.ToInt32(region.Major)), null);
                }
                else
                {
                    BeaconRegion = new SecureBeaconRegion(region.Id, UUID.FromString(region.UUID), null, null);
                }
                BeaconRegions.Add(BeaconRegion);

                this.BeaconManager.StartMonitoring(BeaconRegion);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get the UUID's for the device details and sets the list
        /// </summary>
        /// <param name="gatt">Gatt.</param>
        private void getDeviceDetails(BluetoothGatt gatt)
        {
            try
            {
                UUID deviceInfoUUID = UUID.FromString(BluetoothConstants.DEVICE_INFO_SERVICE);
                BluetoothGattService deviceInfoSer = gatt.GetService(deviceInfoUUID);

                deviceChar = new List <BluetoothGattCharacteristic> {
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SERIALNUM)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_MODELNUM)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SOFTWARE_REV)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_FIRMWARE_REV)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_HARDWARE_REV))
                };

                foreach (BluetoothGattCharacteristic c in deviceChar)
                {
                    try
                    {
                        gatt.SetCharacteristicNotification(c, false);
                        requestCharacteristic(gatt);
                    }
                    catch (System.Exception e)
                    {
                        string t = "";
                        // if the char dont exit for thiss
                    }
                }
            } catch (System.Exception e)
            {
                // stop ourselves
                sendStateUpdate(gatt.Device.Address, false, "Device could not be read from: " + e.Message);
            }
        }
Ejemplo n.º 6
0
        private async void Test()
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;

            if (adapter == null)
            {
                throw new Exception("No Bluetooth adapter found.");
            }

            if (!adapter.IsEnabled)
            {
                throw new Exception("Bluetooth adapter is not enabled.");
            }

            var device = adapter.GetRemoteDevice("00:15:83:10:D6:40");

            if (device == null)
            {
                throw new Exception("Named device not found.");
            }

            var _socket = device.CreateInsecureRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
            await _socket.ConnectAsync();

            byte[] buffer = Encoding.UTF8.GetBytes("1");
            byte[] input  = new byte[1000];
            await _socket.OutputStream.WriteAsync(buffer, 0, buffer.Length);

            await _socket.InputStream.ReadAsync(input, 0, 1000);

            string st = Encoding.UTF8.GetString(input);

            Console.WriteLine($"FROMCUP: {st}");
        }
Ejemplo n.º 7
0
        private async System.Threading.Tasks.Task ConnectToBTAsync()
        {
            if (adapter == null)
            {
                Toast.MakeText(this, "No bt adapter found", ToastLength.Short).Show();
            }

            if (!adapter.IsEnabled)
            {
                Toast.MakeText(this, "bt adapter not enabled", ToastLength.Short).Show();
            }


            BluetoothDevice device = (from bd in adapter.BondedDevices
                                      where bd.Name == "HC-05"
                                      select bd).FirstOrDefault();

            if (device == null)
            {
                Toast.MakeText(this, "no device found...", ToastLength.Short).Show();
            }

            _socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));

            try
            {
                await _socket.ConnectAsync();
            }
            catch (Exception e)
            {
                Toast.MakeText(this, "could not connect", ToastLength.Short).Show();
            }
        }
Ejemplo n.º 8
0
        /**
         * Enables or disables notification on a give characteristic.
         *
         * @param characteristic Characteristic to act on.
         * @param enabled If true, enable notification.  False otherwise.
         */
        internal void SetCharacteristicNotification(BluetoothGattCharacteristic characteristic, bool enabled)
        {
            if (bluetoothAdapter == null || bluetoothGatt == null)
            {
                logger.TraceWarning("BluetoothAdapter not initialized");
                return;
            }

            if (characteristic.Uuid.Equals(UUID.FromString(SampleGattAttributes.PRESSURE_NOTIFICATION_HANDLE)))
            {
                bluetoothGatt.SetCharacteristicNotification(characteristic, enabled);
                logger.TraceInformation("Setting notification: Pressure Characteristic detected ");

                BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(UUID.FromString("00002902-0000-1000-8000-00805F9B34FB"));
                if (descriptor != null)
                {
                    logger.TraceInformation("Setting notification: Pressure Descriptor Found");
                    descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray <byte>());
                    bluetoothGatt.WriteDescriptor(descriptor);
                    logger.TraceInformation("Setting notification: Write Pressure Descriptor");
                }
                else
                {
                    logger.TraceWarning("NOTIFICATION SET UP IGNORED");
                }
            }
        }
Ejemplo n.º 9
0
        private void BtComm()
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
            string           address = adapter.BondedDevices.FirstOrDefault(device => device.Name.Contains("Rover1"))?.Address;

            try
            {
                BluetoothDevice device = adapter.GetRemoteDevice(address);
                adapter.CancelDiscovery();
                BluetoothSocket socket =
                    device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
                socket.Connect();
                Stream output = socket.OutputStream;
                _readerThread = new Thread(() => ReaderLoop(socket.InputStream));
                _readerThread.Start();
                foreach (string message in _messageBuffer.GetConsumingEnumerable())
                {
                    byte[] data = Encoding.ASCII.GetBytes(message);
                    output.Write(data, 0, data.Length);
                    output.Flush();
                }
                _readerThread.Abort();
                Thread.Sleep(2000);
                output.Close();
                socket.Close();
                socket.Dispose();
                device.Dispose();
            }
            catch (Exception e)
            {
                Log.Error("RoverController", $"Exception {e}");
            }
        }
Ejemplo n.º 10
0
        public IBluetoothSocket Connect(RoomVoiceControl.Bluetooth.BluetoothDevice device)
        {
            IBluetoothSocket socket = null;

            Android.Bluetooth.BluetoothDevice bluetoothDevice = mBluetoothAdapter.GetRemoteDevice(device.Address);
            UserDialogs.Instance.Toast("Connecting to " + bluetoothDevice);

            try
            {
                btSocket = bluetoothDevice.CreateRfcommSocketToServiceRecord(UUID.FromString(MY_UUID));

                btSocket.Connect();

                socket = new AndroidBluetoothSocket()
                {
                    BTSocket = btSocket
                };

                UserDialogs.Instance.Toast("Connected to Bluetooth!");
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
                try
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    UserDialogs.Instance.Alert("Connection Error!");
                }
            }

            return(socket);
        }
        private async void ExecuteDeletePerson(string mPersonGroupId, string mPersonId)
        {
            string result = string.Empty;

            mProgressDialog.Show();
            AddLog("Request: Deleting person " + mPersonId);

            try
            {
                var faceClient = new FaceClient();
                mProgressDialog.SetMessage("Deleting selected persons...");
                SetInfo("Deleting selected persons...");
                UUID personId = UUID.FromString(mPersonId);
                await faceClient.DeletePerson(mPersonGroupId, personId);

                result = mPersonId;
            }
            catch (Java.Lang.Exception e)
            {
                result = null;
                AddLog(e.Message);
            }

            RunOnUiThread(() =>
            {
                mProgressDialog.Dismiss();

                if (result != null)
                {
                    SetInfo("Person " + result + " successfully deleted");
                    AddLog("Response: Success. Deleting person " + result + " succeed");
                }
            });
        }
        public ConnectedThread(BluetoothDevice device, string UUIDString)
        {
            // Initializing objects
            m_BtAdapter  = BluetoothAdapter.DefaultAdapter;
            m_UuidString = UUIDString;
            m_FailedCon  = false;

            // Converting the UUID string into a UUID object
            MY_UUID = UUID.FromString(m_UuidString); // Wandelt den UUID String in ein UUID Objekt um

            // Use a temporary object that is later assigned to m_Socket
            BluetoothSocket tmp = null;

            m_Device = device;

            // Get a BluetoothSocket to connect with the given BluetoothDevice
            // Workaround to get the Bluetoothsocket
            tmp = device.CreateRfcommSocketToServiceRecord(MY_UUID);
            Class testClass = tmp.RemoteDevice.Class;

            Class[] paramTypes = new Class[] { Integer.Type };

            Method m = testClass.GetMethod("createRfcommSocket", paramTypes);

            Java.Lang.Object[] param = new Java.Lang.Object[] { Integer.ValueOf(1) };

            m_Socket = (BluetoothSocket)m.Invoke(tmp.RemoteDevice, param);
        }
        private void SetPersonSelected(int position)
        {
            TextView textView = (TextView)FindViewById(Resource.Id.text_person_selected);

            if (position > 0)
            {
                String personGroupIdSelected = mPersonListAdapter.personGroupIds[position];
                mPersonListAdapter.personGroupIds[position] = mPersonListAdapter.personGroupIds[0];
                mPersonListAdapter.personGroupIds[0]        = personGroupIdSelected;

                String personIdSelected = mPersonListAdapter.personIdList[position];
                mPersonListAdapter.personIdList[position] = mPersonListAdapter.personIdList[0];
                mPersonListAdapter.personIdList[0]        = personIdSelected;

                ListView listView = (ListView)FindViewById(Resource.Id.list_persons);
                listView.Adapter = mPersonListAdapter;
                SetPersonSelected(0);
            }
            else if (position < 0)
            {
                SetVerifyButtonEnabledStatus(false);
                textView.SetTextColor(Color.Red);
                textView.Text = "no person selected for verification warning";
            }
            else
            {
                mPersonGroupId = mPersonListAdapter.personGroupIds[0];
                mPersonId      = UUID.FromString(mPersonListAdapter.personIdList[0]);
                String personName = StorageHelper.GetPersonName(mPersonId.ToString(), mPersonGroupId, this);

                RefreshVerifyButtonEnabledStatus();
                textView.SetTextColor(Color.Black);
                textView.Text = String.Format("Person to use: {0}", personName);
            }
        }
Ejemplo n.º 14
0
        private static UUID FromShortUuid(string shortUuid, string baseUuid = null)
        {
            if (baseUuid == null)
            {
                baseUuid = bluetoothBaseUuid;
            }

            var split   = shortUuid.Replace("0x", "").ToCharArray();
            var newUuid = "";

            if (split.Length == 4)// 16 bit
            {
                var splitBase = baseUuid.ToCharArray();
                for (var i = 0; i < split.Length; i++)
                {
                    splitBase[4 + i] = split[i];
                }
                newUuid = splitBase.Aggregate(newUuid, (current, s) => current + s);
                return(UUID.FromString(newUuid));
            }
            else if (split.Length == 8)
            {
                var splitBase = baseUuid.ToCharArray();
                for (var i = 0; i < split.Length; i++)
                {
                    splitBase[i] = split[i];
                }
                newUuid = splitBase.Aggregate(newUuid, (current, s) => current + s);
                return(UUID.FromString(newUuid));
            }
            Debugger.Break();
            return(null);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Start scanning for devices.
        /// </summary>
        /// <param name="serviceUuids">White-listed service UUIDs</param>
        public async void StartScanningForDevices(params string[] serviceUuids)
        {
            DiscoveredDevices = new List <IDevice>();
            IsScanning        = true;

            var uuids = new List <UUID>();

            foreach (var id in serviceUuids)
            {
                var guid = id.ToGuid();
                uuids.Add(UUID.FromString(guid.ToString("D")));
            }

            if (uuids.Count == 0)
            {
                _adapter.StartLeScan(this);
            }
            else
            {
                _adapter.StartLeScan(uuids.ToArray(), this);
            }

            await Task.Delay(ScanTimeout);

            if (IsScanning)
            {
                StopScanningForDevices();
                ScanTimeoutElapsed(this, EventArgs.Empty);
            }
        }
Ejemplo n.º 16
0
        public Task <IBLECharacteristic> ReadCharacteristicAsync(string serviceGUID, string characteristicGUID)
        {
            readCharacteristicTCS = new TaskCompletionSource <IBLECharacteristic>();

            try
            {
                if (_gatt == null)
                {
                    Debug.WriteLine("Connect to Bluetooth Device first");
                    readCharacteristicTCS.TrySetException(new Exception("Connect to Bluetooth Device first"));
                }

                BluetoothGattCharacteristic chara = _gatt.GetService(UUID.FromString(serviceGUID)).GetCharacteristic(UUID.FromString(characteristicGUID));

                if (null == chara)
                {
                    readCharacteristicTCS.TrySetException(new Exception("Bluetooth Gatt Characteristic " + characteristicGUID + " Does Not Exist"));
                }
                if (false == _gatt.ReadCharacteristic(chara))
                {
                    readCharacteristicTCS.TrySetException(new Exception("ReadCharacteristic was not initiated successfully"));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                readCharacteristicTCS.TrySetException(new Exception(e.Message));
            }

            return(readCharacteristicTCS.Task);
        }
Ejemplo n.º 17
0
 public SendData(Handler handler)
 {
     BluetoothAdapter = BluetoothAdapter.DefaultAdapter;
     state            = StateEnum.None;
     MessageHandler   = handler;
     uuid             = UUID.FromString("c88ae110-c0e0-11ea-b3de-0242ac130004");
 }
Ejemplo n.º 18
0
        public Task <bool> UnsubscribeCharacteristic(string serviceGUID, string characteristicGUID, string descriptorGUID)
        {
            unsubscribeCharacteristicTCS = new TaskCompletionSource <bool>();

            try
            {
                if (_gatt == null)
                {
                    Debug.WriteLine("Connect to Bluetooth Device first");
                    unsubscribeCharacteristicTCS.TrySetException(new Exception("Connect to Bluetooth Device first"));
                }

                BluetoothGattCharacteristic chara = _gatt.GetService(UUID.FromString(serviceGUID)).GetCharacteristic(UUID.FromString(characteristicGUID));
                if (null == chara)
                {
                    subscribeCharacteristicTCS.TrySetException(new Exception("Characteristic Id: " + characteristicGUID + " Not Found in Service: " + serviceGUID));
                }

                _gatt.SetCharacteristicNotification(chara, false);

                BluetoothGattDescriptor descriptor = chara.GetDescriptor(UUID.FromString(descriptorGUID));
                descriptor.SetValue(BluetoothGattDescriptor.DisableNotificationValue.ToArray());
                _gatt.WriteDescriptor(descriptor);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                unsubscribeCharacteristicTCS.TrySetException(new Exception(e.Message));
            }

            return(unsubscribeCharacteristicTCS.Task);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Connect to the device given host name
        /// </summary>
        /// <param name="deviceHostName">Raw host name of the device</param>
        /// <returns>True if connected successfully. Else False</returns>
        public async Task <bool> ConnectAsync(string deviceHostName)
        {
            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }

            if (!_adapter.IsEnabled)
            {
                throw new Exception("Bluetooth is off. Please turn it on from settings.");
            }

            SelectedDevice = _adapter.BondedDevices.FirstOrDefault(d => d.Address == deviceHostName);

            if (SelectedDevice != null)
            {
                var uuids = SelectedDevice.GetUuids();
                if (uuids != null && uuids.Length > 0)
                {
                    return(await Task.Run <bool>(() =>
                    {
                        _socket = SelectedDevice.CreateRfcommSocketToServiceRecord(UUID.FromString(uuids[0].ToString()));
                        _socket.Connect();
                        return IsConnected;
                    }));
                }
            }

            return(IsConnected);
        }
Ejemplo n.º 20
0
        // tries to open a connection to the bluetooth printer device
        public void OpenBT()
        {
                        try
            {
                if (BlueToothOpen)
                {
                    return;
                }
                // Standard SerialPortService ID
                UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
                BTSocket = BTDevice.CreateRfcommSocketToServiceRecord(uuid);
                BTSocket.Connect();
                BTOutputStream = new StreamWriter(BTSocket.OutputStream);
                BTInputStream  = new StreamReader(BTSocket.InputStream);

                //                BluetoothServerSocket serverSock = mBluetoothAdapter.ListenUsingRfcommWithServiceRecord("Bluetooth", Java.Util.UUID.FromString(uuid));
                //                mmSocket = serverSock.Accept();
                //                mmSocket.InputStream.ReadTimeout = 1000;
                //                serverSock.Close();//服务器获得连接后腰及时关闭ServerSocket
                //                启动新的线程,开始数据传输

                BlueToothOpen = true;
            }
            catch (System.Exception Ex)
            {
                BlueToothOpen = false;
                BTSocket.Dispose();
                WriteErrorLog(Ex);
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Connects the controller with bluetooth device.
 /// </summary>
 /// <param name="device">Bluetooth device</param>
 public void Connect(BluetoothDevice device)
 {
     try
     {
         BluetoothSocket tempBTSocket = null;
         try
         {
             tempBTSocket = device.CreateRfcommSocketToServiceRecord(UUID.FromString(BLUETOOTH_UUID_STRING));
             tempBTSocket.Connect();
         }
         catch (IOException ex)
         {
             Log.Debug("SocketConnection", "Connection Error 1");
         }
         mSocket       = tempBTSocket;
         mSocketWriter = new SocketWriter(tempBTSocket.OutputStream);
         byte[] bytes = new byte[10] {
             10, 0, 0, 0, 0, 0, 0, 0, 0, 0
         };
         mSocketWriter.Write(bytes);
     }
     catch (IOException ex)
     {
         Log.Debug("SocketConnection", "Connection Error 2");
     }
 }
Ejemplo n.º 22
0
        protected override async Task InitializeAsync()
        {
            await base.InitializeAsync();

            // BLE requires location permissions
            if (await SensusServiceHelper.Get().ObtainPermissionAsync(Permission.Location) != PermissionStatus.Granted)
            {
                // throw standard exception instead of NotSupportedException, since the user might decide to enable location in the future
                // and we'd like the probe to be restarted at that time.
                string error = "Geolocation is not permitted on this device. Cannot start Bluetooth probe.";
                await SensusServiceHelper.Get().FlashNotificationAsync(error);

                throw new Exception(error);
            }

            _deviceIdCharacteristic = new BluetoothGattCharacteristic(UUID.FromString(DEVICE_ID_CHARACTERISTIC_UUID), GattProperty.Read, GattPermission.Read);
            _deviceIdCharacteristic.SetValue(Encoding.UTF8.GetBytes(SensusServiceHelper.Get().DeviceId));

            _deviceIdService = new BluetoothGattService(UUID.FromString(Protocol.Id), GattServiceType.Primary);
            _deviceIdService.AddCharacteristic(_deviceIdCharacteristic);

            _bluetoothAdvertiserCallback = new AndroidBluetoothServerAdvertisingCallback(_deviceIdService, _deviceIdCharacteristic);

            if (ScanMode.HasFlag(BluetoothScanModes.Classic))
            {
                _bluetoothBroadcastReceiver = new AndroidBluetoothDeviceReceiver(this);

                IntentFilter intentFilter = new IntentFilter();
                intentFilter.AddAction(BluetoothDevice.ActionFound);

                Application.Context.RegisterReceiver(_bluetoothBroadcastReceiver, intentFilter);
            }
        }
Ejemplo n.º 23
0
        private BluetoothSocket CreateConnection(String uuid, String address)
        {
            BluetoothDevice pairedBTDevice = null;
            BluetoothSocket btSocket       = null;

            // Preparando ...
            try
            {
                // Iniciamos a conexão com o dispositivo solicitado
                pairedBTDevice = mBluetoothAdapter.GetRemoteDevice(address);

                // Indicamos ao adaptador que não seja visível
                mBluetoothAdapter.CancelDiscovery();
            }
            catch (Exception e)
            {
                throw new System.ApplicationException("Erro ao encontrar o Robô.", e);
            }

            // Conectando ...
            try
            {
                // Inicamos o socket de comunicação com o Raspberry
                btSocket = pairedBTDevice.CreateRfcommSocketToServiceRecord(UUID.FromString(uuid));

                // Tentar conectar ao socket (processo assíncrono)
                btSocket.ConnectAsync();

                // 5 tentativas
                for (int try_conn = 0; try_conn < 5; try_conn++)
                {
                    // Esperar por 1 segundo
                    Thread.Sleep(1000);

                    // Checar o resultado da tentativa
                    if (btSocket.IsConnected)
                    {
                        // Sucesso! Retorna o socket e finaliza o processo
                        return(btSocket);
                    }
                }

                // Esgotando as 5 tentativas, fecha-se o socket e retorna um erro
                btSocket.Close();
                throw new System.ApplicationException("Falha ao tentar conectar ao Robô.");
            }
            catch (Exception e)
            {
                // Em caso de erro, fechamos o socket
                try
                {
                    btSocket.Close();
                }
                catch (Exception ex)
                {
                    // Ignore
                }
                throw new System.ApplicationException("Erro ao tentar conectar ao Robô.", e);
            }
        }
Ejemplo n.º 24
0
        private void ConnectToDevice(TextView statusMessage)
        {
            var adapter = BluetoothAdapter.DefaultAdapter;

            if (adapter == null)
            {
                statusMessage.Text = "No Bluetooth adapter found.";
                return;
            }
            else if (!adapter.IsEnabled)
            {
                statusMessage.Text = "Please turn on Bluetooth";
                return;
            }

            var device = adapter.BondedDevices.Where(d => d.Name == "HC-05").FirstOrDefault();

            if (device == null)
            {
                statusMessage.Text = "Could not find HC-05";
                return;
            }

            _socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
            _socket.Connect();
            statusMessage.Text = "Connected";
        }
Ejemplo n.º 25
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            isRecording = false;
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);
            textBox = FindViewById <TextView>(Resource.Id.search_voice_btn);
            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            var adapter = BluetoothAdapter.DefaultAdapter;
            var device  = adapter.BondedDevices.FirstOrDefault(x => x.Name == "Richmond’s iPhone");

            var _socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
            var t       = _socket.ConnectAsync();

            t.GetAwaiter().GetResult();
            var s = t.Status;

            // Read data from the device
            //await _socket.InputStream.ReadAsync(buffer, 0, buffer.Length);

            //// Write data to the device
            //await _socket.OutputStream.WriteAsync(buffer, 0, buffer.Length);
            FloatingActionButton fab = FindViewById <FloatingActionButton>(Resource.Id.fab);

            fab.Click += FabOnClick;
        }
        private BluetoothSocket TryGetSocket(BluetoothDevice bluetoothDevice, string uuid = null)
        {
            UUID id = UUID.FromString(uuid ?? "00001101-0000-1000-8000-00805F9B34FB");

            try
            {
                _btSocket = bluetoothDevice?.CreateRfcommSocketToServiceRecord(id);       // Secure Socket
                return(_btSocket);
            }
            catch (Exception e1)
            {
                Console.WriteLine(e1);

                try
                {
                    _btSocket = bluetoothDevice?.CreateInsecureRfcommSocketToServiceRecord(id);       // Insecure Socket
                    return(_btSocket);
                }
                catch (Exception e2)
                {
                    Console.WriteLine(e2);
                    _btSocket?.Dispose();
                    return(null);
                }
            }
        }
Ejemplo n.º 27
0
        public static void Print(string bt_printer, string value)
        {
            try{
                if (bt_printer != "" || bt_printer != null || bt_printer.Length > 0)
                {
                    var x = BluetoothAdapter.DefaultAdapter.BondedDevices;

                    BluetoothSocket socket    = null;
                    BufferedReader  inReader  = null;
                    BufferedWriter  outReader = null;

                    BluetoothDevice hxm             = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(bt_printer);
                    UUID            applicationUUID = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
                    socket = hxm.CreateRfcommSocketToServiceRecord(applicationUUID);
                    socket.Connect();

                    inReader  = new BufferedReader(new InputStreamReader(socket.InputStream));
                    outReader = new BufferedWriter(new OutputStreamWriter(socket.OutputStream));
                    outReader.Write(value);
                    outReader.Flush();
                    Thread.Sleep(5 * 1000);
                    var s = inReader.Ready();
                    inReader.Skip(0);
                    //close all
                    inReader.Close();
                    socket.Close();
                    outReader.Close();
                }
            }catch (Exception ex) {
                Shared.Services.Logs.Insights.Send("Print", ex);
            }
        }
Ejemplo n.º 28
0
        public void Connect(BluetoothDevice device, bool secure, string code)
        {
            MY_UUID_SECURE   = UUID.FromString(MY_UUID + code);
            MY_UUID_INSECURE = UUID.FromString(MY_UUID + code);

            if (state == STATE_CONNECTING)
            {
                if (connectThread != null)
                {
                    connectThread.Cancel();
                    connectThread = null;
                }
            }

            // Cancel any thread currently running a connection
            if (connectedThread != null)
            {
                connectedThread.Cancel();
                connectedThread = null;
            }

            // Start the thread to connect with the given device
            connectThread = new ConnectThread(device, this, secure);
            connectThread.Start();

            UpdateUserInterfaceTitle();
        }
 public async Task Print(string deviceName, byte[] buffer)
 {
     using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
     {
         BluetoothDevice device = (from bd in bluetoothAdapter?.BondedDevices
                                   where bd?.Name == deviceName
                                   select bd).FirstOrDefault();
         try
         {
             using (BluetoothSocket bluetoothSocket = device?.
                                                      CreateRfcommSocketToServiceRecord(
                        UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")))
             {
                 bluetoothSocket?.Connect();
                 //byte[] buffer = Encoding.UTF8.GetBytes(text);
                 bluetoothSocket?.OutputStream.Write(buffer, 0, buffer.Length);
                 bluetoothSocket.Close();
             }
         }
         catch (Exception exp)
         {
             throw exp;
         }
     }
 }
        public void testParseInvalidUuid()
        {
            UUID       uuid = UUID.FromString("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6");
            Identifier id   = Identifier.Parse("2f234454cf6d4a0fadf2f4911ba9ffa6");

            AssertEx.AreEqual("Malformed UUID was parsed as expected.", id.ToUuid(), uuid);
        }