예제 #1
0
 public void Dispose()
 {
     Adapter.DisconnectDeviceAsync(this);
 }
        /// <summary>
        /// Closes the connection interface associated with this bluetooth device.
        /// </summary>
        /// <exception cref="XBeeException">If there is any XBee error.</exception>
        /// <seealso cref="IsOpen"/>
        /// <seealso cref="Open"/>
        public void Close()
        {
            Debug.WriteLine("----- Close");

            // Do nothing if the device is not open.
            if (!IsOpen)
            {
                return;
            }

            // Create a task to disconnect the device.
            Task task = Task.Run(async() =>
            {
                // Unsubscribe from the RX characteristic.
                rxCharacteristic.ValueUpdated -= DataReceived;
                try
                {
                    if (device != null && device.State == DeviceState.Connected)
                    {
                        await rxCharacteristic.StopUpdatesAsync();
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("----- BLE interface - Error unsubscribing RX characteristic: " + e.Message);
                }

                // Disconnect the device.
                try
                {
                    if (device != null && device.State == DeviceState.Connected)
                    {
                        await adapter.DisconnectDeviceAsync(device);
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("----- BLE interface - Error disconnecting the device: " + e.Message);
                }

                IsOpen = false;
                lock (disconnectLock)
                {
                    Monitor.Pulse(disconnectLock);
                }
            });

            if (!task.IsCompleted)
            {
                // Wait until the task finishes.
                lock (disconnectLock)
                {
                    Monitor.Wait(disconnectLock, DISCONNECTION_TIMEOUT);
                }
            }

            if (device != null && device.State != DeviceState.Disconnected && device.State != DeviceState.Limited)
            {
                // Set interface connection as closed (although there was a problem closing it...)
                IsOpen = false;
                throw new XBeeException(ERROR_DISCONNECTION);
            }
        }
예제 #3
0
        public BluetoothNugetPage()
        {
            InitializeComponent();

            this.BindingContext = this;

            _cts = new CancellationTokenSource();

            this._device = null;

            _bluetoothAdapter                     = CrossBluetoothLE.Current.Adapter;
            _bluetoothAdapter.ScanTimeout         = 8000;
            _bluetoothAdapter.DeviceDiscovered   += OnDeviceDiscovered;
            _bluetoothAdapter.DeviceDisconnected += OnDeviceDisconnected;
            _bluetoothAdapter.DeviceConnected    += OnDeviceConnected;
            _bluetoothAdapter.ScanTimeoutElapsed += (sender, e) =>
            {
                _device         = null;
                IsSearchEnabled = true;
                OnPropertyChanged(nameof(IsSearchEnabled));

                UserDialogs.Instance.Toast("Search Timeout");
            };

            IsSearchEnabled = true;
            OnPropertyChanged(nameof(IsSearchEnabled));

            IsConnectEnabled = false;
            OnPropertyChanged(nameof(IsConnectEnabled));


            this.SearchCommand = new Command((arg) =>
            {
                _device = null;

                IsSearchEnabled = false;
                OnPropertyChanged(nameof(IsSearchEnabled));

                if (_bluetoothAdapter.IsScanning)
                {
                    _bluetoothAdapter.StopScanningForDevicesAsync().ContinueWith((o) =>
                    {
                        _bluetoothAdapter.StartScanningForDevicesAsync();
                    });
                }
                else
                {
                    _bluetoothAdapter.StartScanningForDevicesAsync();
                }
            }, (arg) => IsSearchEnabled);

            this.ConnectCommand = new Command((arg) =>
            {
                TryConnect();
            }, (arg) => IsConnectEnabled);

            this.DisconnectCommand = new Command((arg) =>
            {
                _bluetoothAdapter.DisconnectDeviceAsync(_device);
                IsDisconnectEnabled = false;
                IsSearchEnabled     = true;
                IsConnectEnabled    = false;
                DeviceFoundName     = "";
                DeviceConnected     = "";
                DeviceFoundDistance = "";
                OnPropertyChanged(nameof(DeviceFoundName));
                OnPropertyChanged(nameof(DeviceConnected));
                OnPropertyChanged(nameof(DeviceFoundDistance));
                OnPropertyChanged(nameof(IsDisconnectEnabled));
                OnPropertyChanged(nameof(IsSearchEnabled));
                OnPropertyChanged(nameof(IsConnectEnabled));
            }, (arg) => IsDisconnectEnabled);
        }
예제 #4
0
 public async Task DisconnectAsync(IDevice device)
 {
     await _adapter.DisconnectDeviceAsync(device);
 }
예제 #5
0
        public async Task Disconnect(IDevice device, IAdapter adapter)
        {
            await adapter.DisconnectDeviceAsync(device);

            Debug.WriteLine("Succesfull");
        }
예제 #6
0
        private async void connectBleDevice()
        {
            if (IsBleConnected)
            {
                BtnBleConnectTxt = "CONNECT";
                IsBleConnected   = false;
                lblDataSource    = "";
                bleDevices.Clear();
                await bleAdapter.DisconnectDeviceAsync(connectedDevice);
            }
            else
            {
                BtnBleConnectTxt = "DISCONNECT";
                try
                {
                    IsBleConnected     = false;
                    connectedDevice    = null;
                    gridDataVisible    = false;
                    gridBleScanVisible = true;
                    connectedDevice    = await bleAdapter.ConnectToKnownDeviceAsync(new Guid(currentDeviceUuid));

                    dialogScr.Toast("Droplet state: " + connectedDevice.State.ToString());
                    try
                    {
                        batteryInfoService = await connectedDevice.GetServiceAsync(new Guid("0000180f-0000-1000-8000-00805f9b34fb"));

                        batteryVoltageCharacteristic = await batteryInfoService.GetCharacteristicAsync(new Guid("00002a19-0000-1000-8000-00805f9b34fb"));

                        batteryVoltageCharacteristic.ValueUpdated += BatteryVoltageCharacteristic_ValueUpdated;
                        await batteryVoltageCharacteristic.StartUpdatesAsync();
                    }
                    catch (Exception e)
                    {
                        dialogScr.Toast("Battery read error: " + e.Message);
                    }

                    deviceInfoService = await connectedDevice.GetServiceAsync(Guid.Parse("0000180a-0000-1000-8000-00805f9b34fb"));

                    manufacturerCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a29-0000-1000-8000-00805f9b34fb"));

                    deviceModelCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a24-0000-1000-8000-00805f9b34fb"));

                    deviceSerialCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a25-0000-1000-8000-00805f9b34fb"));

                    deviceHWrevCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a27-0000-1000-8000-00805f9b34fb"));

                    deviceFWrevCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a26-0000-1000-8000-00805f9b34fb"));

                    deviceSWrevCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a28-0000-1000-8000-00805f9b34fb"));

                    dataService = await connectedDevice.GetServiceAsync(Guid.Parse("c97433f0-be8f-4dc8-b6f0-5343e6100eb4"));

                    dataReadCharacteristic = await dataService.GetCharacteristicAsync(Guid.Parse("c97433f1-be8f-4dc8-b6f0-5343e6100eb4"));

                    dataWriteCharacteristic = await dataService.GetCharacteristicAsync(Guid.Parse("c97433f2-be8f-4dc8-b6f0-5343e6100eb4"));

                    dataReadCharacteristic.ValueUpdated += DataReadCharacteristic_ValueUpdated;
                    await dataReadCharacteristic.StartUpdatesAsync();

                    byte[] batteryVoltageBytes = await batteryVoltageCharacteristic.ReadAsync();

                    byte[] manufacturerBytes = await manufacturerCharacteristic.ReadAsync();

                    byte[] deviceModelBytes = await deviceModelCharacteristic.ReadAsync();

                    byte[] deviceSerialBytes = await deviceSerialCharacteristic.ReadAsync();

                    byte[] deviceHWrevBytes = await deviceHWrevCharacteristic.ReadAsync();

                    byte[] deviceFWrevBytes = await deviceFWrevCharacteristic.ReadAsync();

                    byte[] deviceSWrevBytes = await deviceSWrevCharacteristic.ReadAsync();

                    Debug.WriteLine("Battery : " + batteryVoltageBytes[0].ToString() + " %");
                    Debug.WriteLine("Manufacturer: " + System.Text.Encoding.Default.GetString(manufacturerBytes));
                    Debug.WriteLine("Device model: " + System.Text.Encoding.Default.GetString(deviceModelBytes));
                }
                catch (Exception e)
                {
                    dialogScr.Toast("BLE connection error: " + e.Message);
                    Debug.WriteLine("BLE connection error: " + e.Message);
                }
                IsBleConnected     = true;
                gridBleScanVisible = false;
                gridDataVisible    = true;
                lblDataSource      = "BLE - Droplet";
            }
        }
예제 #7
0
        /*
         * Mandamos a imprimir los datos del parte
         */
        public async void Imprimir(Boolean imprimir)
        {
            try
            {
                lblLoadingText.Text = "Imprimiendo ticket...";

                RepositorySatApp BBDD = new RepositorySatApp();
                var empresa           = BBDD.Get <Generales>(1);
                var Nombre            = empresa.Empresa;
                var nif       = empresa.NIF;
                var direc     = empresa.Direccion;
                var telf      = empresa.Telefono1;
                var comercial = empresa.N_Comercial;

                //Obtenemos y guardamos en objetos la información que deseamos imprimir
                //Transformamos los datos en Bytes antes de enviarlos a la impresora

                var parte        = Variables.DatosParte;
                var masDatos     = BBDD.GetSat(parte.N_Parte);
                var masCliente   = BBDD.Get <Cliente>(masDatos.Cliente);
                var masProvincia = BBDD.GetProvincias(masCliente.Provincia);
                var lineasParte  = BBDD.GetAllLineasParte(Variables.DatosParte.N_Parte.ToString());

                //Obtiene nombre comercial. De momento cliente no la quiere
                var codempresa = BBDD.Get <Generales>(0);

                //Hay que traerse la tabla comercialcliente
                // string masComercial = BBDD.GetComercialCliente(codempresa.Codigo, parte.CodigoCliente);

                string masPersonal = BBDD.GetNombreTecnico(masDatos.Realizado_Por);


                //Esta es la copia buena 28/01/2020
                BBDD.CerrarConexion();

                // Convertimos los strings a bytes y los imprimimos
                byte[] negrita      = new byte[] { 0x1B, 0x21, 0x08 };
                byte[] normal       = new byte[] { 0x1B, 0x21, 0x00 };
                byte[] negritamedia = new byte[] { 0x1B, 0x21, 0x20 };

                byte[] N_Parte      = Encoding.ASCII.GetBytes("Numero Parte:       " + parte.N_Parte);
                byte[] Fecha        = Encoding.ASCII.GetBytes("Fecha aviso:        " + parte.Fecha.ToShortDateString());
                byte[] HoraAviso    = Encoding.ASCII.GetBytes("Hora aviso:         " + masDatos.Hora_Entrada.ToShortTimeString());
                byte[] FechaCerrado = Encoding.ASCII.GetBytes("Fecha realizado:    " + Convert.ToDateTime(masDatos.Fecha_Realizado.ToString()).ToShortDateString());
                var    horainicio   = masDatos.HoraInicioTarea.AddHours(1);
                var    horafin      = masDatos.HoraFinTarea.AddHours(1);


                byte[] Cliente      = Encoding.ASCII.GetBytes("Cliente:           " + parte.NombreCliente);
                byte[] nifCli       = Encoding.ASCII.GetBytes("DNI / NIF:          " + masCliente.NIF);
                byte[] Direccion    = Encoding.ASCII.GetBytes("Direccion:          " + parte.DireccionParte);
                byte[] Poblacion    = Encoding.ASCII.GetBytes("C.P / Poblacion:    " + masCliente.C_P);
                byte[] Provincia    = Encoding.ASCII.GetBytes("Provincia:          " + masProvincia.Provincia);
                byte[] nomcomercial = Encoding.ASCII.GetBytes("Tecnico:            " + masPersonal);

                byte[] Anomalia = Encoding.ASCII.GetBytes("Anomalia:\n " + parte.AnomaliaParte);
                //byte[] Telefono = Encoding.ASCII.GetBytes("Telefono: " + parte.TelefonoCliente);
                byte[] Solucion = Encoding.ASCII.GetBytes("Trabajo efectuado:\n " + parte.Solucion);
                // byte[] Observaciones = Encoding.ASCII.GetBytes("Observaciones adicionales:\n " + parte.Observaciones);
                byte[] Pago     = Encoding.ASCII.GetBytes("Forma de Pago: " + parte.FormaPago);
                byte[] Base     = Encoding.ASCII.GetBytes("          Base imponible:         " + parte.Base_Total.ToString("N2"));
                byte[] valorIva = Encoding.ASCII.GetBytes("          IVA:                    " + parte.Iva_Total.ToString("N2"));
                byte[] Total    = Encoding.ASCII.GetBytes("          Total:                  " + parte.Total.ToString("N2"));


                byte[] estrellitas         = Encoding.ASCII.GetBytes("===============================================\n");
                byte[] separacontinua      = Encoding.ASCII.GetBytes("_______________________________________________\n");
                byte[] separacion          = Encoding.ASCII.GetBytes("------------------------------------------------\n");
                byte[] separaverticalFirma = Encoding.ASCII.GetBytes("Firma Trabajador:     |   Firma Cliente:\n");
                byte[] separavertical      = Encoding.ASCII.GetBytes("                      | \n");
                byte[] salto    = Encoding.ASCII.GetBytes("\n");
                byte[] firma1   = Encoding.ASCII.GetBytes("Firma Trabajador:");
                byte[] firma2   = Encoding.ASCII.GetBytes("Firma Cliente:");
                byte[] ArtServ  = Encoding.ASCII.GetBytes("             Articulos y servicio:");
                byte[] Cabecera = Encoding.ASCII.GetBytes("Referencia   Precio   Cantidad   Importe    Iva\n");

                byte[] N_empresa        = Encoding.ASCII.GetBytes("          " + Nombre + "\n");
                byte[] dic_empresa      = Encoding.ASCII.GetBytes("          " + direc + "\n");
                byte[] telf_empresa     = Encoding.ASCII.GetBytes("               Telf: " + telf + "\n");
                byte[] nif_empresa      = Encoding.ASCII.GetBytes("               N.I.F: " + nif + "\n");
                byte[] Nombre_Comercial = Encoding.ASCII.GetBytes("       " + comercial);
                byte[] CabLineas        = Encoding.ASCII.GetBytes("                PARTE TRABAJO\n");
                byte[] Cabdesg          = Encoding.ASCII.GetBytes("        Desglose categorias impositivas\n");
                byte[] desglose         = Encoding.ASCII.GetBytes("            Base     Iva    Importe\n");
                byte[] valordesglose    = Encoding.ASCII.GetBytes("            " + parte.Base_Total + "      " + parte.TantoIva1 + "     " + parte.Iva_Total);
                byte[] CabTotales       = Encoding.ASCII.GetBytes("               Totales finales:\n");
                byte[] gracias          = Encoding.ASCII.GetBytes("    Le damos las gracias por su confianza\n");
                byte[] docvista         = Encoding.ASCII.GetBytes("Este documento solo es una vista preliminar y no reemplaza al documento de facturación\n");


                var servicios = await dispositivo.GetServicesAsync();


                foreach (var l in servicios)
                {
                    if (l.Name == "Unknown Service") //Obtiene el servicio del que depende la caracteristica que nos permite enviar datos a la impresora
                    {
                        var server         = l as IService;
                        var caracteristica = await server.GetCharacteristicsAsync();


                        foreach (var m in caracteristica)
                        {
                            if (m.Name == "Unknown characteristic") //Localiza la caracteristica que se usa para enviar datos a la impresora
                            {
                                var carac = m as ICharacteristic;

                                //Cabecera ticket
                                if (carac.CanWrite && imprimir)  // Este if comprueba si el proximo caracter es imprimible y si el booleano es true o false
                                {                                // SIN ESTE IF NO IMPRIME
                                    await carac.WriteAsync(negrita);

                                    await carac.WriteAsync(N_empresa);

                                    await carac.WriteAsync(dic_empresa);

                                    await carac.WriteAsync(telf_empresa);

                                    await carac.WriteAsync(nif_empresa);//fin cabecera ticket

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    //Datos parte
                                    await carac.WriteAsync(normal);

                                    await carac.WriteAsync(N_Parte);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(Fecha);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(HoraAviso);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(FechaCerrado);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    //Datos cliente
                                    await carac.WriteAsync(Cliente);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(nifCli);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(Direccion);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(Poblacion);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(Provincia);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(nomcomercial);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    //Incidencia
                                    await carac.WriteAsync(Anomalia);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(Solucion);

                                    await carac.WriteAsync(salto);

                                    // await carac.WriteAsync(Observaciones);
                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    //Cabecera lineas tarea
                                    await carac.WriteAsync(estrellitas);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(CabLineas);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(ArtServ); //Articulos y servicios

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(Cabecera); //Cabecera lineasSat

                                    await carac.WriteAsync(separacontinua);

                                    await carac.WriteAsync(salto);

                                    foreach (var h in lineasParte) //Lineas partesat
                                    {
                                        var    precio  = Math.Round(h.Precio, 2);
                                        var    importe = Math.Round(h.Importe, 2);
                                        byte[] desc    = Encoding.ASCII.GetBytes(h.Descripcion + "\n");
                                        byte[] refer   = Encoding.ASCII.GetBytes(" " + h.Referencia.ToString());
                                        byte[] espacio = Encoding.ASCII.GetBytes(" ");

                                        byte[] prec = Encoding.ASCII.GetBytes(precio.ToString("N2") + "       ");
                                        byte[] cant = Encoding.ASCII.GetBytes(h.Cantidad.ToString());
                                        byte[] imp  = Encoding.ASCII.GetBytes(importe.ToString("N2") + "        ");
                                        byte[] iva  = Encoding.ASCII.GetBytes(h.Iva.ToString() + "\n");
                                        await carac.WriteAsync(desc);

                                        if (CuentaDigito(h.Referencia) <= 2)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("     ");
                                            await carac.WriteAsync(refer);

                                            await carac.WriteAsync(espacio);
                                        }
                                        else
                                        {
                                            await carac.WriteAsync(refer);
                                        }

                                        if (CuentaDigito(precio) >= 5)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("  ");
                                        }
                                        else if (CuentaDigito(precio) == 4)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("   ");
                                        }
                                        else if (CuentaDigito(precio) == 3)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("    ");
                                        }
                                        else if (CuentaDigito(precio) == 2)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("     ");
                                        }
                                        else if (CuentaDigito(precio) == 1 || CuentaDigito(precio) == 0)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("      ");
                                        }
                                        await carac.WriteAsync(espacio);

                                        await carac.WriteAsync(prec);

                                        await carac.WriteAsync(cant);

                                        if (CuentaDigito(importe) >= 5)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("  ");
                                        }
                                        else if (CuentaDigito(importe) == 4)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("    ");
                                        }
                                        else if (CuentaDigito(importe) == 3)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("     ");
                                        }
                                        else if (CuentaDigito(importe) == 2)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("      ");
                                        }
                                        else if (CuentaDigito(importe) == 1 || CuentaDigito(importe) == 0)
                                        {
                                            espacio = Encoding.ASCII.GetBytes("       ");
                                        }
                                        await carac.WriteAsync(espacio);

                                        await carac.WriteAsync(imp);

                                        await carac.WriteAsync(iva);
                                    }

                                    //Desglose categorias impositivas
                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(Cabdesg);

                                    await carac.WriteAsync(desglose);

                                    await carac.WriteAsync(separacontinua);

                                    await carac.WriteAsync(valordesglose);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    //Totales finales
                                    await carac.WriteAsync(CabTotales);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(Base);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(valorIva);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(Total);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    //Firmas
                                    await carac.WriteAsync(separacontinua);

                                    await carac.WriteAsync(separaverticalFirma);

                                    await carac.WriteAsync(separavertical);

                                    await carac.WriteAsync(separavertical);

                                    await carac.WriteAsync(separavertical);

                                    await carac.WriteAsync(separavertical);

                                    await carac.WriteAsync(separavertical);

                                    await carac.WriteAsync(separavertical);

                                    await carac.WriteAsync(separacontinua);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(negritamedia);

                                    await carac.WriteAsync(Nombre_Comercial);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(normal);

                                    await carac.WriteAsync(gracias);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(docvista);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    await carac.WriteAsync(salto);

                                    var respuesta = await Application.Current.MainPage.DisplayAlert("Aviso", "Si desea una copia, pulse el botón de imprimir", "Ok", "Cancelar");

                                    if (respuesta == true)  // Si la respuesta es Cancelar, salimos del bucle
                                    {
                                        Imprimir(imprimir);
                                    }
                                    else
                                    {
                                        imprimir = false;
                                        popupLoadingView.IsVisible  = false;
                                        activityIndicator.IsRunning = false;
                                        btnImprimir.IsEnabled       = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }


                await adaptador.DisconnectDeviceAsync(dispositivo);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }