Exemple #1
0
        public static async System.Threading.Tasks.Task <BluetoothSocket> SocAsync(BluetoothDevice device)
        {
            BluetoothSocket _socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
            await _socket.ConnectAsync();

            return(_socket);
        }
            public ConnectThread(BluetoothChatService chatService, BluetoothDevice device, bool secure)
            {
                this.chatService = chatService;
                mmDevice         = device;
                BluetoothSocket tmp = null;

                mSocketType = secure ? "Secure" : "Insecure";

                // Get a BluetoothSocket for a connection with the
                // given BluetoothDevice
                try
                {
                    if (secure)
                    {
                        tmp = device.CreateRfcommSocketToServiceRecord(MY_UUID_SECURE);
                    }
                    else
                    {
                        tmp = device.CreateInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
                    }
                }
                catch (IOException e)
                {
                    Log.E(TAG, "Socket Type: " + mSocketType + "create() failed", e);
                }
                mmSocket = tmp;
            }
Exemple #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);
            }
        }
        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);
            }
        }
Exemple #5
0
        private void BT_SocketConnection(BluetoothDevice btDevice)
        {
            ParcelUuid[] uuids = null;
            if (btDevice.FetchUuidsWithSdp())
            {
                uuids = btDevice.GetUuids();
            }
            if ((uuids != null) && (uuids.Length > 0))
            {
                BluetoothSocket btSocket = null;
                foreach (var uuid in uuids)
                {
                    try
                    {
                        btSocket = btDevice.CreateRfcommSocketToServiceRecord(uuid.Uuid);
                        btSocket.Connect();
                        if (btSocket.IsConnected)
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("ex: " + ex.Message);
                    }
                }

                if (btSocket.IsConnected)
                {
                    Toast.MakeText(this, "Bluetooth socket is connected!", ToastLength.Long).Show();
                }
            }
        }
Exemple #6
0
        private async Task <bool> InitConnection()
        {
            //Start connecting to arduino device
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            System.Console.WriteLine("Connecting to device:" + device);

            //We indicate to the adapter that it is no longer visible
            mBluetoothAdapter.CancelDiscovery();
            try {
                //We initiate the communication socket with the arduino
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);

                //We connect the socket
                await btSocket.ConnectAsync();

                System.Console.WriteLine("Connection Initiated");
                IsConnected = true;
            } catch (System.Exception e) {
                //In case of generating errors, we close the socket
                Console.WriteLine("Fail to connect");
                Console.WriteLine(e.Message);
                await DisconnectAsync();
            }

            return(IsConnected);
        }
Exemple #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();
            }
        }
Exemple #8
0
        public void Connect()
        {
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            System.Console.WriteLine("Connect" + device);
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                btSocket.Connect();
                System.Console.WriteLine("Connection Okay");
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
                try
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    System.Console.WriteLine("Imposible Connect");
                }
                System.Console.WriteLine("Socket Create");
            }
            beginListenForData();
            dataToSend = new Java.Lang.String("e");
            writeData(dataToSend);
        }
        public void Connect()
        {
            BluetoothDevice device = (from bd in this.mBluetoothAdapter.BondedDevices where bd.Name == "DESKTOP-SHHL6ED" select bd).FirstOrDefault();

            foreach (var ff in this.mBluetoothAdapter.BondedDevices)
            {
                Result.Text += ff.Address + "\n";
            }
            System.Console.WriteLine("Conexion en curso" + device);
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                btSocket.Connect();
                System.Console.WriteLine("Conexion Correcta");
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
                try
                {
                    // dataToSend = new Java.Lang.String("0");
                    // writeData(dataToSend);
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    System.Console.WriteLine("Imposible Conectar");
                }
                System.Console.WriteLine("Socket Creado");
            }
            beginListenForData();
            //dataToSend = new Java.Lang.String("0");
            // writeData(dataToSend);
        }
        public async Task <string> Connect()
        {
            try
            {
                btAdapter = BluetoothAdapter.DefaultAdapter;
                if (btAdapter == null)
                {
                    return("Bluetooth Is Not Available");
                }

                if (!btAdapter.IsEnabled)
                {
                    return("Bluetooth Is Not Enabled");
                }

                BluetoothDevice device = (from bd in btAdapter.BondedDevices
                                          where bd.Name == connectionName
                                          select bd).FirstOrDefault();

                if (device == null)
                {
                    return("No Paired Device Named " + connectionName);
                }
                socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
                socket.Connect();
                return("connected");
            }
            catch (Exception e)
            {
                return("Could Not Connect To " + connectionName);
            }
        }
        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;
                }
            }
        }
 private void Connect()
 {
     mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
     device            = mBluetoothAdapter.GetRemoteDevice(address);
     Toast.MakeText(this, "Conectando a " + device.Name, ToastLength.Short).Show();
     mBluetoothAdapter.CancelDiscovery();
     try
     {
         btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
         btSocket.Connect();
         Toast.MakeText(this, "Conexión establecida", ToastLength.Short).Show();
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine(e.Message);
         try
         {
             btSocket.Close();
         }
         catch (Exception)
         {
             Toast.MakeText(this, "Imposible conectar", ToastLength.Short).Show();
         }
     }
     BeginListenForData();
 }
Exemple #13
0
 public async Task <bool> Init()
 {
     btAdapter = BluetoothAdapter.DefaultAdapter;
     if (btAdapter != null)
     {
         if (btAdapter.IsEnabled)
         {
             var bondedDevices = btAdapter.BondedDevices;
             if (bondedDevices.Count > 0)
             {
                 var             devices = bondedDevices.ToList();
                 BluetoothDevice device  = devices
                                           .FirstOrDefault(x => x.Name.Equals("DSD TECH HC-05"));
                 if (device == null)
                 {
                     return(false);
                 }
                 ParcelUuid[] uuids = device.GetUuids();
                 socket = device.CreateRfcommSocketToServiceRecord(uuids[0].Uuid);
                 try
                 {
                     await socket.ConnectAsync();
                 }
                 catch (Exception)
                 {
                     throw new Exception("Fehler beim Aufbau einer Bluetoothverbindung");
                 }
                 OutputStream = socket.OutputStream;
                 InputStream  = socket.InputStream;
             }
         }
     }
     return(true);
 }
Exemple #14
0
        //Evento de conexion al Bluetooth
        public void Connect()
        {
            //Inicia conexão com o arduino
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            System.Console.WriteLine("Conectando " + device);

            mBluetoothAdapter.CancelDiscovery();
            try {
                //socket de comunicação com o arduino
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                //conectando socket
                btSocket.Connect();
                // Aviso sonoro do sistema
                var p = new Dictionary <string, string> ();
                mTts.Speak("Bem vindo ao UFBA Acessivel.", QueueMode.Add, p);
                //Espera(3000);
                //inicio();
                conectado = true;
                System.Console.WriteLine("Conectado!!");
            } catch (System.Exception e) {
                Console.WriteLine(e.Message);
                try {
                    btSocket.Close();
                } catch (System.Exception) {
                    System.Console.WriteLine("Erro de Conexão");
                }
            }

            //Inicio da espera de dados
            beginListenForData();
        }
Exemple #15
0
 /// <summary>
 /// Sends a contact request to the specified Bluetooth device.
 /// </summary>
 /// <param name="device">The device to send the request to.</param>
 /// <param name="myAddress">The local address to send to the device.</param>
 /// <returns>The Erebus address of the device if the request was accepted; otherwise null.</returns>
 public static ErebusAddress?RequestAddContact(BluetoothDevice device, ErebusAddress myAddress)
 {
     Log.RecordEvent(typeof(BluetoothUtils), $"Attempting to add Bluetooth device '{device.Name}' as a contact.", LogEntrySeverity.Info);
     try
     {
         var s = device.CreateRfcommSocketToServiceRecord(RfcommAddContactService);
         s.Connect();
         using (var r = new BinaryReader(s.InputStream))
             using (var w = new BinaryWriter(s.OutputStream))
             {
                 w.Write(true);
                 r.ReadBoolean();
                 w.Write(myAddress);
                 var addr  = r.ReadErebusAddress();
                 var vkp   = new VerificationKeyProvider();
                 var local = vkp.CreatePrivateKey();
                 w.Write(local.Item2.Length);
                 w.Write(local.Item2);
                 vkp.AddKeyPair(addr, local.Item1, r.ReadBytes(r.ReadInt32()));
                 Log.RecordEvent(typeof(BluetoothUtils), $"Successfully negotiated contact with {addr} via Bluetooth RFCOMM.", LogEntrySeverity.Info);
                 return(addr);
             }
     }
     catch (Exception e)
     {
         Log.RecordEvent(typeof(BluetoothUtils), $"Exception adding contact: {e.Message}; assuming other user rejected request.", LogEntrySeverity.Error);
         return(null);
     }
 }
        public static BluetoothSocket GetSocket(BluetoothDevice device)
        {
            var socket = device.CreateRfcommSocketToServiceRecord(PRINTER_UUID);

            socket.Connect();
            return(socket);
        }
        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);
                }
            }
        }
Exemple #18
0
        //Evento de conexion al Bluetooth
        public void Connect()
        {
            //Iniciamos la conexion con el arduino
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            System.Console.WriteLine("Conexion en curso" + device);

            //Indicamos al adaptador que ya no sea visible
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                //Inicamos el socket de comunicacion con el arduino
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                //Conectamos el socket
                btSocket.Connect();
                System.Console.WriteLine("Conexion Correcta");
            }
            catch (System.Exception e)
            {
                //en caso de generarnos error cerramos el socket
                Console.WriteLine(e.Message);
                try
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    System.Console.WriteLine("Imposible Conectar");
                }
                System.Console.WriteLine("Socket Creado");
            }
            //Una vez conectados al bluetooth mandamos llamar el metodo que generara el hilo
            //que recibira los datos del arduino
            beginListenForData();
        }
            public ConnectThread(BluetoothDevice device, BluetoothChatService service, bool secure)
            {
                this.device  = device;
                this.service = service;
                BluetoothSocket tmp = null;

                socketType = secure ? "Secure" : "Insecure";

                try
                {
                    if (secure)
                    {
                        tmp = device.CreateRfcommSocketToServiceRecord(MY_UUID_SECURE);
                    }
                    else
                    {
                        tmp = device.CreateInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
                    }
                }
                catch (Java.IO.IOException e)
                {
                    Log.Error(TAG, "create() failed", e);
                }
                socket        = tmp;
                service.state = STATE_CONNECTING;
            }
        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);
        }
Exemple #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");
     }
 }
        public void Connect()
        {
            bluetoothConn.Text += "Cautare dispozitiv remote";
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            bluetoothConn.Text += "Comexiune in curs" + device.Name + "\n";

            //Thread.Sleep(20000);
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                btSocket.Connect();
                bluetoothConn.Text = bluetoothConn.Text + "Conexiune Creata";
            }
            catch (System.Exception e)
            {
                bluetoothConn.Text += e.Message;
                try
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    bluetoothConn.Text += "Conexiune nereusita";
                }
                bluetoothConn.Text += "Socket creat";
            }
            beginListenForData();

            //writeData(dataToSend);
        }
        private BluetoothSocket BtConnect(BluetoothDevice device)
        {
            BluetoothSocket socket = null;

            ParcelUuid[] uuids = null;
            if (device.FetchUuidsWithSdp())
            {
                uuids = device.GetUuids();
            }
            if ((uuids != null) && (uuids.Length > 0))
            {
                foreach (var uuid in uuids)
                {
                    try
                    {
                        socket = device.CreateRfcommSocketToServiceRecord(uuid.Uuid);
                        socket.Connect();
                        break;
                    }
                    catch (System.Exception ex)
                    {
                        socket = null;
                    }
                }
            }
            return(socket);
        }
        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}");
            }
        }
        public async void PrintText(BluetoothDevice selectedDevice, List <string> input)
        {
            try
            {
                BluetoothSocket _socket = selectedDevice.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));

                await _socket.ConnectAsync();

                string footerSpace = "\r\n" + "\r\n" + "\r\n" + "\r\n" + "\r\n";

                for (int i = 0; i < input.Count; i++)
                {
                    string toPrint = input[i] + "\r\n";
                    if (i == input.Count - 1)
                    {
                        toPrint = input[i] + footerSpace;
                    }
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(toPrint);
                    await _socket.OutputStream.WriteAsync(buffer, 0, buffer.Length);
                }
                _socket.Close();
            }
            catch (Exception exp)
            {
                //BluetoothMessage("Attention", "Please turn on the printer.");
                //throw exp;
            }
        }
Exemple #26
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);
            }
        }
Exemple #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);
            }
        }
        void DeviceListClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            // Cancel discovery because it's costly and we're about to connect
            mBluetoothAdapter.CancelDiscovery();

            // Get the device MAC address, which is the last 17 chars in the View
            var info    = (e.View as TextView).Text.ToString();
            var address = info.Substring(info.Length - 17);

            string[] lines       = info.ToString().Split(new string[] { "\n" }, StringSplitOptions.None);
            var      device_Name = lines[0];

            Toast.MakeText(this, device_Name, ToastLength.Long).Show();


            BluetoothDevice btDevice = newlyDiscoveredBTDevices.Where(x => x.Name == device_Name).SingleOrDefault();

            try
            {
                BluetoothSocket btSocket = btDevice.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
                btSocket.Connect();
            }
            catch (Exception ex)
            {
                Console.WriteLine("ex: " + ex.Message);
            }

            //Intent intent = new Intent(this, typeof(BluetoothChat));
            //intent.PutExtra(BluetoothChat.DEVICE_NAME, device_Name);
            //StartActivity(intent);
        }
 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;
         }
     }
 }
Exemple #30
0
        /// <summary>
        /// Connects to the device.
        /// </summary>
        /// <returns>A stream of the connection.</returns>
        public Stream Connect()
        {
            var s = device.CreateRfcommSocketToServiceRecord(BluetoothUtils.RfcommConnectionService);

            s.Connect();
            return(new SplitStream(s.InputStream, s.OutputStream));
        }