Beispiel #1
0
        private void AtualizaBalanca1(BluetoothSocket socket1)
        {
            try
            {
                socket1.Close();
                socket1.Dispose();
                Thread.Sleep(150);
                socket1 = Validacoes.VerificaDeviceAtivo(socket1);
                socket1.Connect();
                Validacoes.VerificaStatusPlafaforma(socket1, 1);



                if (Validacoes.Nrplataformas > 1)
                {
                    socket1.Close();
                    AtualizaBalanca2(socket1);
                }
                else
                {
                    if (Validacoes.Estabilidade1 == "E")
                    {
                        TxtPeso.SetTextColor(Android.Graphics.Color.Green);
                    }
                    else
                    {
                        TxtPeso.SetTextColor(Android.Graphics.Color.Red);
                    }

                    int Pesototal = Validacoes.Peso1 +
                                    Validacoes.Peso2 +
                                    Validacoes.Peso3 +
                                    Validacoes.Peso4 +
                                    Validacoes.Peso5 +
                                    Validacoes.Peso6;
                    RunOnUiThread(() => TxtPeso.Text = Convert.ToString(Pesototal));
                    socket1.Close();

                    progressBar.Visibility = Android.Views.ViewStates.Invisible;
                    TxtProgress.Visibility = Android.Views.ViewStates.Invisible;

                    AtualizaBalanca1(socket1);
                }
            }
            catch (Exception ex)
            {
                if (Fecharthread == "S")
                {
                    threadBalancaPesagem.Interrupt();
                }
                else
                {
                    if (socket1.IsConnected == true)
                    {
                        socket1.Close();
                    }
                    AtualizaBalanca1(socket1);
                }
            }
        }
Beispiel #2
0
        private void PerformUpdate()
        {
            EdiabasInit();
            Android.App.ProgressDialog progress = new Android.App.ProgressDialog(this);
            progress.SetCancelable(false);
            progress.SetMessage(GetString(Resource.String.can_adapter_fw_update_active));
            progress.Show();

            _adapterThread = new Thread(() =>
            {
                bool updateOk  = false;
                bool connectOk = false;
                try
                {
                    connectOk = !InterfacePrepare();
                    BluetoothSocket bluetoothSocket = EdBluetoothInterface.BluetoothSocket;
                    if (bluetoothSocket == null)
                    {
                        connectOk = false;
                    }
                    else
                    {
                        connectOk = true;
                        updateOk  = PicBootloader.FwUpdate(bluetoothSocket);
                    }
                }
                catch (Exception)
                {
                    updateOk = false;
                }
                RunOnUiThread(() =>
                {
                    if (IsJobRunning())
                    {
                        _adapterThread.Join();
                    }
                    progress.Hide();
                    progress.Dispose();
                    string message;
                    if (updateOk)
                    {
                        message = GetString(Resource.String.can_adapter_fw_update_ok);
                    }
                    else
                    {
                        message = connectOk
                            ? GetString(Resource.String.can_adapter_fw_update_failed)
                            : GetString(Resource.String.can_adapter_fw_update_conn_failed);
                    }
                    _activityCommon.ShowAlert(message, updateOk ? Resource.String.alert_title_info : Resource.String.alert_title_error);
                    UpdateDisplay();
                    if (updateOk)
                    {
                        PerformRead();
                    }
                });
            });
            _adapterThread.Start();
            UpdateDisplay();
        }
Beispiel #3
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            status = FindViewById <TextView> (Resource.Id.statusText);
            TryToConnect();

            FindViewById <Button> (Resource.Id.light1).Click += delegate { SendAMessage("q", "toggling light 1"); };
            FindViewById <Button> (Resource.Id.light2).Click += delegate { SendAMessage("w", "toggling light 2"); };
            FindViewById <Button> (Resource.Id.light3).Click += delegate { SendAMessage("e", "toggling light 3"); };
            FindViewById <Button> (Resource.Id.door1).Click  += delegate { SendAMessage("1", "toggling door 1"); };
            FindViewById <Button> (Resource.Id.door2).Click  += delegate { SendAMessage("2", "toggling door 2"); };
            FindViewById <Button> (Resource.Id.door3).Click  += delegate { SendAMessage("3", "toggling door 3"); };
            connectorButton        = FindViewById <Button> (Resource.Id.cnx);
            connectorButton.Click += delegate {
                if (socket != null && socket.IsConnected)
                {
                    socket.Close();
                    socket.Dispose();
                    socket = null;
                    connectorButton.Text = "Connect";
                    status.Text          = "ain't connected";
                }
                else
                {
                    TryToConnect();
                }
            };
            connectorButton.Enabled = true;
        }
Beispiel #4
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);
            }
        }
Beispiel #5
0
            public void Run()
            {
                BluetoothSocket socket = null;

                // Keep listening until exception occurs or a socket is returned.
                while (true)
                {
                    try
                    {
                        System.Console.WriteLine("Tentativo di Conessione come Server");

                        socket = mmServerSocket.Accept();
                    }
                    catch (Java.IO.IOException e)
                    {
                        System.Console.WriteLine("Errore: " + e);
                        break;
                    }
                    System.Console.WriteLine("Connesso come Server");

                    if (socket != null)
                    {
                        mConnectedThread = new ConnectedThread(socket);
                        mConnectedThread.Start();
                        break;
                    }
                }
            }
Beispiel #6
0
        private void connected(BluetoothSocket socket, BluetoothDevice device)
        {
            if (null != _ConnectThread)
            {
                _ConnectThread = null;
            }
            if (null != _RxThread)
            {
                _RxThread = null;
            }
            if (null != _TxThread)
            {
                _TxThread = null;
            }

            setState(ConnectState.CONNECTED);

            _RxThread      = new Thread(new ParameterizedThreadStart(rxTask));
            _RxThread.Name = "Receive thread";
            _RxThread.Start(socket);

            _TxThread      = new Thread(new ParameterizedThreadStart(txTask));
            _TxThread.Name = "Transmit thread";
            _TxThread.Start(socket);
        }
Beispiel #7
0
        private void Connected(BluetoothSocket bluetoothSocket)
        {
            Log.Debug(Name, $"create ConnectedThread");

            Socket = bluetoothSocket;

            try
            {
                InStream  = bluetoothSocket.InputStream;
                OutStream = bluetoothSocket.OutputStream;
            }
            catch (Java.IO.IOException e)
            {
                Log.Error(Name, "temp sockets not created", e);
                ConnectionLost();
            }

            State = BluetoothState.Connected;

            Log.Info(Name, "BEGIN mConnectedThread");

            CallbackObject callback = new CallbackObject
            {
                Buffer = new byte[1024]
            };

            InStream.BeginRead(callback.Buffer, 0, callback.Length, ReadCallback, callback);
        }
Beispiel #8
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();
            }
        }
Beispiel #9
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");
     }
 }
Beispiel #10
0
            private async Task <ConnectionEstablishState> establishConnectionAsync()
            {
                if (_Device == null)
                {
                    return(ConnectionEstablishState.Failed);
                }
                BluetoothSocket tmp = null;

                if (_BluetoothAdapter == null)
                {
                    _BluetoothAdapter = BluetoothAdapter.DefaultAdapter;
                }
                try
                {
                    tmp = _Device.CreateInsecureRfcommSocketToServiceRecord(_SdpUuid);
                }
                catch (Java.IO.IOException)
                {
                    return(ConnectionEstablishState.Failed);
                }
                _BluetoothSocket = tmp;
                _BluetoothAdapter.CancelDiscovery();
                try
                {
                    await _BluetoothSocket.ConnectAsync();

                    System.Diagnostics.Debug.WriteLine("BLUETOOTH::SUCCESSFUL ");
                }
                catch (Exception)
                {
                    try
                    {
                        _BluetoothSocket.Close();
                    }
                    catch (Java.IO.IOException)
                    {
                        return(ConnectionEstablishState.Failed);
                    }
                    return(ConnectionEstablishState.Failed);
                }
                try
                {
                    _InputStream  = _BluetoothSocket.InputStream;
                    _OutputStream = _BluetoothSocket.OutputStream;
                }
                catch (Java.IO.IOException)
                {
                    try
                    {
                        _BluetoothSocket.Close();
                    }
                    catch (Java.IO.IOException)
                    {
                        return(ConnectionEstablishState.Failed);
                    }
                    return(ConnectionEstablishState.Failed);
                }
                _LastSendDateTime = DateTime.Now;
                return(ConnectionEstablishState.Succeeded);
            }
Beispiel #11
0
        public void Crea(BluetoothDevice device, BluetoothSocket BthSocket)
        {
            IntPtr createRfcommSocket = JNIEnv.GetMethodID(device.Class.Handle, "createRfcommSocket", "(I)Landroid/bluetooth/BluetoothSocket;");
            IntPtr _socket            = JNIEnv.CallObjectMethod(device.Handle, createRfcommSocket, new global::Android.Runtime.JValue(1));

            BthSocket = Java.Lang.Object.GetObject <BluetoothSocket>(_socket, JniHandleOwnership.TransferLocalRef);
        }
            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;
            }
Beispiel #13
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);
        }
Beispiel #14
0
        public async Task <bool> Connect(string deviceName)
        {
            if (!_bluetoothAdapter.Enable())
            {
                return(false);
            }

            try
            {
                var device = _bluetoothAdapter.GetRemoteDevice(deviceName);
                _bluetoothAdapter.CancelDiscovery();
                _btSocket = device.CreateRfcommSocketToServiceRecord(MyUuid);

                await _btSocket.ConnectAsync();

                if (_btSocket.IsConnected)
                {
                    Connected = true;
                }
            }
            catch (Exception ex)
            {
                Connected = false;
                var error = $"Cannot connect to bluetooth device ({deviceName}):, {ex.Message}, {ex.StackTrace}.";
                Log.Info(_tag, error);
            }

            return(Connected);
        }
        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;
            }
        }
Beispiel #16
0
        public ConnectedThread(BluetoothService service, BluetoothSocket socket)
        {
            this.service = service;
            this.socket  = socket;
            Stream tempIn  = null;
            Stream tempOut = null;

            this.handler = this.service.MessageHandler;

            try
            {
                tempIn = this.socket.InputStream;
            }
            catch (IOException e)
            {
                Logger.Log("Error occurred when creating input stream " + e.Message);
            }

            try
            {
                tempOut = this.socket.OutputStream;
            }
            catch (IOException e)
            {
                Logger.Log("Error occurred when creating output  stream " + e.Message);
            }

            InStream = tempIn;
            InStream.Flush();
            OutStream = tempOut;
            OutStream.Flush();
        }
            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;
            }
Beispiel #18
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);
            }
        }
Beispiel #19
0
        public void Connected(BluetoothSocket socket, BluetoothDevice device)
        {
            if (Debug)
            {
                Log.Debug(Tag, "Connected");
            }

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

            if (connectedThread != null)
            {
                connectedThread.Cancel();
                connectedThread = null;
            }

            // Canceller accepttråden fordi vi kun vil have et device på vores connection.
            if (acceptThread != null)
            {
                acceptThread.Cancel();
                acceptThread = null;
            }

            connectedThread = new ConnectedThread(socket, this);
            connectedThread.Start();

            // Her skal der være noget der sender vores connected device til gui.

            SetState(State_Connected);
        }
Beispiel #20
0
        public void Initialize()
        {
            // Permitir apenas uma execução por vez
            if (Monitor.TryEnter(connectionLock))
            {
                try
                {
                    // Indicar que estamos tentando inicializar
                    initialized = false;

                    // Ligar o adaptador Bluetooth do celular para nossa aplicação
                    TurnOnBluetooth();

                    // Criar um socket de conexão Bluetooth com o Robô
                    BluetoothSocket btSocket = CreateConnection(Robot.DEFAULT_UUID, Robot.DEFAULT_ADDRESS);
                    if (btSocket == null)
                    {
                        throw new System.ApplicationException("Robô não encontrado.");
                    }

                    // Criar uma representação do Robô
                    robot = new Robot(btSocket);

                    // Indicar que o processo de inicialização foi concluído com sucesso
                    initialized = true;
                }
                finally
                {
                    Monitor.Exit(connectionLock);
                }
            }
        }
        public static void ConfirmHC(Activity activity, BluetoothSocket socket, BluetoothDevice device, Context context)
        {
            //Tell the user we're talking to HC-05
            var status = activity.FindViewById <TextView>(Resource.Id.textView2);

            status.Append("\nConnected to HC-05 Suspected Skimmer; Sending \"P\"...");
            activity.FindViewById <ScrollView>(Resource.Id.scrollView1).FullScroll(Android.Views.FocusSearchDirection.Down);

            //Talk to it
            Stream mminputStream  = socket.InputStream;
            Stream mmoutputStream = socket.OutputStream;

            byte[] buffer = new byte[1];

            buffer[0] = Convert.ToByte('P');

            mmoutputStream.Write(buffer, 0, 1);
            mminputStream.Read(buffer, 0, 1);

            status.Append("\nReceived " + Convert.ToChar(buffer[0]));

            if (Convert.ToChar(buffer[0]) == 'M')
            {
                context.StartActivity(new Intent(context, typeof(Alert)));
            }
            else
            {
                YellowAlert(context);
            }

            var unpair = device.Class.GetMethod("removeBond", null);

            unpair.Invoke(device, null);
        }
        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);
        }
Beispiel #23
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);
            }
        }
Beispiel #24
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();
                }
            }
        }
Beispiel #25
0
            private byte[] mmBuffer; // mmBuffer store for the stream

            public ConnectedThread(BluetoothSocket socket)
            {
                mmSocket = socket;
                InputStream  tmpIn  = null;
                OutputStream tmpOut = null;


                // Get the input and output streams; using temp objects because
                // member streams are final.
                try
                {
                    tmpIn = ((Android.Runtime.InputStreamInvoker)socket.InputStream).BaseInputStream;
                }
                catch (System.IO.IOException e)
                {
                    System.Console.WriteLine("Errore: " + e);
                }
                try
                {
                    tmpOut = ((Android.Runtime.OutputStreamInvoker)socket.OutputStream).BaseOutputStream;
                }
                catch (Java.IO.IOException e)
                {
                    System.Console.WriteLine("Errore: " + e);
                }

                mmInStream  = tmpIn;
                mmOutStream = tmpOut;
            }
Beispiel #26
0
        public async Task <IEasyBluetoothConnection> Connect(string mac)
        {
            var device = FindPairedDevice(mac);

            if (device == null)
            {
                return(null);
            }

            var uuid = FindPairedDeviceFirstUUID(mac);

            if (uuid == null)
            {
                return(null);
            }
            BluetoothSocket socket = device.CreateRfcommSocketToServiceRecord(uuid);

            mBluetoothAdapter.CancelDiscovery();

            try
            {
                System.Diagnostics.Debug.WriteLine("Tratando de conectar");
                await socket.ConnectAsync();
            }
            catch (Java.IO.IOException ex)
            {
                socket.Close();
                System.Diagnostics.Debug.WriteLine("No se puede conectar");
                throw new IOException("Error de conexión bluetooth al dispositivo con MAC: " + mac, ex);
            }

            return(new EasyConnection(device, socket) as IEasyBluetoothConnection);
        }
Beispiel #27
0
 private void DisconnectBondedDevice()
 {
     if (reader != null)
     {
         reader.Close();
         reader = null;
     }
     if (writer != null)
     {
         writer.Close();
         writer = null;
     }
     if (bluetoothSocket != null)
     {
         try
         {
             bluetoothSocket.Close();
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine(ex.Message);
         }
         bluetoothSocket = null;
     }
 }
Beispiel #28
0
        void ClientHandle(BluetoothSocket Client)
        {
            ClientConnected = true;

            Thread.Sleep(5000);

            byte[] Buffer = Encoding.ASCII.GetBytes("1");
            Client.OutputStream.Write(Buffer, 0, Buffer.Length);


            Buffer = new byte[1];
            string Packet = string.Empty;

            while (true)
            {
                int    PacketInt       = Client.InputStream.Read(Buffer, 0, Buffer.Length);
                string OneStringPacket = Encoding.ASCII.GetString(Buffer, 0, PacketInt);

                if (OneStringPacket == "!")
                {
                    System.Console.WriteLine(Packet);
                    Save();
                    Save(Packet);

                    Packet = string.Empty;
                }
                else
                {
                    Packet += OneStringPacket;
                }
            }
        }
 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 override void Run()
            {
                Logger.Log("Run: AcceptThread Running");

                BluetoothSocket socket = null;

                try
                {
                    Logger.Log("Run: RFCOM server socket start.....");

                    socket = serverSocket.Accept();

                    Logger.Log("Run: RFCOM server socket Accepted Connection");
                }
                catch (IOException e)
                {
                    Logger.Log("Run: " + e.Message);
                }

                if (socket != null)
                {
                    service.Connected(socket);
                }

                Logger.Log("END AcceptThread");
            }