예제 #1
0
        protected override async Task InitializeAsync()
        {
            await base.InitializeAsync();

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

                throw new Exception(error);
            }

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

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

            _bluetoothAdvertiserCallback = new AndroidBluetoothServerAdvertisingCallback(_deviceIdService, _deviceIdCharacteristic);

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

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

                Application.Context.RegisterReceiver(_bluetoothBroadcastReceiver, intentFilter);
            }
        }
예제 #2
0
        public Task <bool> WriteValueAsync(byte[] data)
        {
            var result = gattCharacteristics.SetValue(data);

            result = GattService.WaterBoilerMatDevice.WriteCharacteristic(gattCharacteristics);
            return(Task.FromResult(result));
        }
예제 #3
0
        void _bluettothServerCallback_NotificationSent(object sender, BleEventArgs e)
        {
            var user = JsonConvert.DeserializeObject <UserProfile>(Settings.User);


            _characteristic.SetValue(user.Id);

            _bluetoothServer.NotifyCharacteristicChanged(e.Device, _characteristic, false);
            //if (_count == 0)
            //    {
            //        _sw = new Stopwatch();
            //        _sw.Start();
            //    }

            //    if (_count < 1000)
            //    {


            //        _count++;

            //    }
            //    else
            //    {
            //        _sw.Stop();
            //        Console.WriteLine("Sent # {0} notifcations. Total kb:{2}. Time {3}(s). Throughput {1} bytes/s", _count,
            //            _count * 20.0f / _sw.Elapsed.TotalSeconds, _count * 20 / 1000, _sw.Elapsed.TotalSeconds);
            //    }
        }
예제 #4
0
        /// <summary>
        /// Write byte data to the Bluetooth device.
        /// </summary>
        /// <param name="data">The array of bytes to write.</param>
        /// <returns>True if the write succeeded.</returns>
        public bool Write(params byte[] data)
        {
            if (State != BlueState.Connected)
            {
                return(false);
            }
            if (_TX == null)
            {
                Debug.WriteLineIf(sw.TraceError, $"--> Write no TX characteristic");
                return(false);
            }
            bool res = _TX.SetValue(data);

            if (!res)
            {
                Debug.WriteLineIf(sw.TraceVerbose, "--> TX SetValue failed");
                return(false);
            }
            else
            {
                res = _gatt.WriteCharacteristic(_TX);
                if (!res)
                {
                    Debug.WriteLineIf(sw.TraceVerbose, "--> TX WriteCharacteristic failed");
                    return(false);
                }
            }
            return(true);
        }
        private bool SetFlag(BluetoothGatt gatt)
        {
            if (gatt == null || _racpCharacteristic == null)
            {
                return(false);
            }

            sbyte[] bArr = { -64, 2, -31, 1, 5, 1, 1, 1, 1, 1, 0 };
            _racpCharacteristic.SetValue(new byte[bArr.Length]);
            for (var i = 0; i < bArr.Length; i++)
            {
                _racpCharacteristic.SetValue((byte[])(Array)bArr);
            }

            return(gatt.WriteCharacteristic(_racpCharacteristic));
        }
예제 #6
0
        private bool InternalWrite(byte[] data)
        {
            _nativeCharacteristic.SetValue(data);
            Trace.Message("Write {0}", Id);

            return(_gatt.WriteCharacteristic(_nativeCharacteristic));
        }
예제 #7
0
        /// <summary>
        /// Write the specified data to the characteristic
        /// </summary>
        /// <param name="data">Data.</param>
        public void Write(byte[] data, CharacteristicWriteType writeType)
        {
            if (!CanWrite)
            {
                throw new InvalidOperationException("Characteristic does not support WRITE");
            }

            _nativeCharacteristic.SetValue(data);

            if (writeType == CharacteristicWriteType.WithResponse)
            {
                _nativeCharacteristic.WriteType = GattWriteType.Default;
            }
            else if (writeType == CharacteristicWriteType.WithoutResponse)
            {
                _nativeCharacteristic.WriteType = GattWriteType.NoResponse;
            }

            var success = _gatt.WriteCharacteristic(_nativeCharacteristic);

            if (!success)
            {
                WriteComplete?.Invoke(this, new CharacteristicWriteEventArgs(false, this));
                //throw new CharacteristicException("Write failed", CharacteristicException.Code.WriteFailed);
            }
        }
예제 #8
0
        void _bluettothServerCallback_NotificationSent(object sender, BleEventArgs e)
        {
            if (_count == 0)
            {
                _sw = new Stopwatch();
                _sw.Start();
            }

            if (_count < 1000)
            {
                var chars  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                var random = new Random();
                var result = new string(
                    Enumerable.Repeat(chars, 20)
                    .Select(s => s[random.Next(s.Length)])
                    .ToArray());
                _characteristic.SetValue(result);

                _bluetoothServer.NotifyCharacteristicChanged(e.Device, _characteristic, false);

                _count++;
            }
            else
            {
                _sw.Stop();
                Console.WriteLine("Sent # {0} notifcations. Total kb:{2}. Time {3}(s). Throughput {1} bytes/s", _count,
                                  _count * 20.0f / _sw.Elapsed.TotalSeconds, _count * 20 / 1000, _sw.Elapsed.TotalSeconds);
            }
        }
예제 #9
0
        public BattByteTestServer()
        {
            _serverCallback    = new ServerCallback();
            _advertiseCallback = new AdvertiseCallback();

            var appContext = Android.App.Application.Context;
            var manager    = (BluetoothManager)appContext.GetSystemService(Application.BluetoothService);
            var server     = manager.OpenGattServer(appContext, _serverCallback);

            _serverCallback.GattServer = server;

            _adapter = manager.Adapter;

            var battByteService = new BluetoothGattService(UUID.FromString("BEEF".ToGuid().ToString()), GattServiceType.Primary);

            var voltageCharacteristic = new BluetoothGattCharacteristic(UUID.FromString("BEF0".ToGuid().ToString()), GattProperty.Read, GattPermission.Read);

            voltageCharacteristic.SetValue(new byte[] { 0xB0, 0x0B });
            battByteService.AddCharacteristic(voltageCharacteristic);

            var tempCharacteristic = new BluetoothGattCharacteristic(UUID.FromString("BEF1".ToGuid().ToString()), GattProperty.Read, GattPermission.Read);

            tempCharacteristic.SetValue(9876, GattFormat.Sint16, 0);
            battByteService.AddCharacteristic(tempCharacteristic);

            server.AddService(battByteService);
            _server = server;
            StartAdvertising("Blah!");
        }
예제 #10
0
        Task DoWriteValue(byte[] value)
        {
            _characteristic.SetValue(value);
            bool written = Service.Device.Gatt.NativeGatt.WriteCharacteristic(_characteristic);

            Service.Device.Gatt.WaitForCharacteristicWrite();
            return(Task.CompletedTask);
        }
예제 #11
0
 public override void OnCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, bool preparedWrite,
                                                   bool responseNeeded, int offset, byte[] value)
 {
     characteristic.SetValue(value);
     if (responseNeeded)
     {
         Server.SendResponse(device, requestId, GattStatus.Success, offset, value);
     }
 }
예제 #12
0
        private void GattServerCallback_OnDeviceAdded(BluetoothDevice device)
        {
            if (gattServer != null)
            {
                BluetoothGattCharacteristic timeCharacteristic = gattServer.Services.Where(s => s.Uuid == TIME_SERVICE).First().GetCharacteristic(CURRENT_TIME);
                timeCharacteristic.SetValue(GetExactTime());

                gattServer.NotifyCharacteristicChanged(device, timeCharacteristic, false);
            }
        }
        private void SetCustomData_MC(BluetoothGattCharacteristic bluetoothGattCharacteristic)
        {
            using var gregorianCalendar = new GregorianCalendar();
            var b = (byte)((gregorianCalendar.Get(CalendarField.Year) % 100) & 255);

            byte[] bArr =
            {
                1,                                                              0, b, (byte)(((gregorianCalendar.Get(CalendarField.Year) - b) / 100) & 255),
                (byte)((gregorianCalendar.Get(CalendarField.Month) + 1) & 255),
                (byte)gregorianCalendar.Get(CalendarField.DayOfMonth),
                (byte)(gregorianCalendar.Get(CalendarField.HourOfDay) & 255),
                (byte)(gregorianCalendar.Get(CalendarField.Minute) & 255),
                (byte)(gregorianCalendar.Get(CalendarField.Second) & 255)
            };
            bluetoothGattCharacteristic.SetValue(new byte[bArr.Length]);
            for (var i = 0; i < bArr.Length; i++)
            {
                bluetoothGattCharacteristic.SetValue(bArr);
            }
        }
예제 #14
0
        /// <summary>
        /// Performs a Characteristic Value write to a Bluetooth LE device.
        /// </summary>
        /// <param name="value">A byte array object which contains the data to be written to the Bluetooth LE device.</param>
        /// <returns>The object that manages the asynchronous operation, which, upon completion, returns the status with which the operation completed.</returns>
        private async Task <GattCommunicationStatus> DoWriteValueAsync(byte[] value, GattWriteOption writeOption)
        {
            bool success = _characteristic.SetValue(value);

            if (_service.Device._bluetoothGatt.WriteCharacteristic(_characteristic))
            {
                return(GattCommunicationStatus.Success);
            }

            return(GattCommunicationStatus.Unreachable);
        }
        /// <summary>
        /// Write the specified data to the characteristic
        /// </summary>
        /// <param name="data">Data.</param>
        public void Write(byte[] data)
        {
            if (!CanWrite)
            {
                throw new InvalidOperationException("Characteristic does not support WRITE");
            }

            _nativeCharacteristic.SetValue(data);
            _nativeCharacteristic.WriteType = GattWriteType.NoResponse;

            _gatt.WriteCharacteristic(_nativeCharacteristic);
        }
예제 #16
0
 private void PlatformWrite(byte[] data)
 {
     if (!_characteristic.SetValue(data))
     {
         RaiseWriteFailed(BLEErrorCode.InternalError);
         return;
     }
     if (!_gatt.WriteCharacteristic(_characteristic))
     {
         RaiseWriteFailed(BLEErrorCode.InternalError);
     }
 }
        private void SetOpCode(BluetoothGattCharacteristic bluetoothGattCharacteristic, int i, int i2, int[] numArr)
        {
            if (bluetoothGattCharacteristic == null)
            {
                return;
            }
            bluetoothGattCharacteristic.SetValue(new byte[(numArr.Length > 0 ? 1 : 0) + 2 + numArr.Length * 2]);
            bluetoothGattCharacteristic.SetValue(i, GattFormat.Uint8, 0);
            bluetoothGattCharacteristic.SetValue(i2, GattFormat.Uint8, 1);
            if (numArr.Length <= 0)
            {
                return;
            }
            bluetoothGattCharacteristic.SetValue(1, GattFormat.Uint8, 2);
            var i3 = 3;

            foreach (int intValue in numArr)
            {
                bluetoothGattCharacteristic.SetValue(intValue, GattFormat.Uint16, i3);
                i3 += 2;
            }
        }
        private bool SetCustomFlag(BluetoothGatt gatt)
        {
            if (gatt == null || _customTimeCharacteristic == null)
            {
                return(false);
            }

            sbyte[] bArr = { -64, 2, -31, 1, 5, 1, 1, 1, 1, 1, 0 };
            try {
                _customTimeCharacteristic.SetValue(new byte[bArr.Length]);
                for (var i = 0; i < bArr.Length; i++)
                {
                    _customTimeCharacteristic.SetValue((byte[])(Array)bArr);
                }

                return(gatt.WriteCharacteristic(_customTimeCharacteristic));
            } catch (Exception e) {
                Log.Error("setCustomFlagError", e.Message);
            }

            return(false);
        }
 private void SetCustomTimeSync(BluetoothGattCharacteristic bluetoothGattCharacteristic, Calendar calendar)
 {
     if (bluetoothGattCharacteristic == null)
     {
         return;
     }
     _timesyncUtcTzCnt++;
     sbyte[] bArr =
     {
         -64,                                                    3, 1, 0, (sbyte)(calendar.Get(CalendarField.Year) & 255),
         (sbyte)((calendar.Get(CalendarField.Year) >> 8) & 255),
         (sbyte)((calendar.Get(CalendarField.Month) + 1) & 255),
         (sbyte)(calendar.Get(CalendarField.DayOfMonth) & 255),
         (sbyte)(calendar.Get(CalendarField.HourOfDay) & 255),
         (sbyte)(calendar.Get(CalendarField.Minute) & 255),      (sbyte)(calendar.Get(CalendarField.Second) & 255)
     };
     bluetoothGattCharacteristic.SetValue(new byte[bArr.Length]);
     for (var i = 0; i < bArr.Length; i++)
     {
         bluetoothGattCharacteristic.SetValue((byte[])(Array)bArr);
     }
 }
예제 #20
0
        private void InternalWrite(byte[] data)
        {
            if (!_nativeCharacteristic.SetValue(data))
            {
                throw new CharacteristicReadException("Gatt characteristic set value FAILED.");
            }

            Trace.Message("Write {0}", Id);

            if (!_gatt.WriteCharacteristic(_nativeCharacteristic))
            {
                throw new CharacteristicReadException("Gatt write characteristic FAILED.");
            }
        }
        private void InternalWrite(byte[] data)
        {
            if (Configuration.IsForceUI)
            {
                using (var h = new Handler(Looper.MainLooper))
                {
                    h.Post(() =>
                    {
                        if (!_nativeCharacteristic.SetValue(data))
                        {
                            throw new CharacteristicReadException("Gatt characteristic set value FAILED.");
                        }

                        Trace.Message("Write {0}", Id);

                        if (!_gatt.WriteCharacteristic(_nativeCharacteristic))
                        {
                            throw new CharacteristicReadException("Gatt write characteristic FAILED.");
                        }
                    });
                }
            }
            else
            {
                if (!_nativeCharacteristic.SetValue(data))
                {
                    throw new CharacteristicReadException("Gatt characteristic set value FAILED.");
                }

                Trace.Message("Write {0}", Id);

                if (!_gatt.WriteCharacteristic(_nativeCharacteristic))
                {
                    throw new CharacteristicReadException("Gatt write characteristic FAILED.");
                }
            }
        }
예제 #22
0
            public void senddexfile()
            {
                try
                {
                    BluetoothGattCharacteristic charac = ConnectedGatt.GetService(DEX_SERVICE_SPP)
                                                         .GetCharacteristic(DEX_CHARACTERISTIC_DATAWRITE);
                    string filepath = "DEX_SAMPLE.txt";
                    byte[] buffer   = new byte[20];

                    lock (ConnectedGatt)
                    {
                        try
                        {
                            Stream inputstream = asm.Open(filepath);
                            while (inputstream.Read(buffer, 0, buffer.Length) > 0)
                            {
                                charac.SetValue(buffer);
                                Java.Lang.Thread.Sleep(20);
                                bool status = ConnectedGatt.WriteCharacteristic(charac);
                                if (!status)
                                {
                                    MainActivity.RunOnUiThread(() =>
                                    {
                                        Log.Info(TAG + DexService.Operation, "send dexFile completed!");
                                    });
                                    break;
                                }

                                Arrays.Fill(buffer, 0);
                            }

                            inputstream.Close();
                        }
                        catch (Java.IO.IOException e)
                        {
                            e.PrintStackTrace();
                        }
                        catch (InterruptedException e)
                        {
                            e.PrintStackTrace();
                        }
                    }
                }
                catch (Java.Lang.Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
예제 #23
0
        private void SetValue()
        {
            String inputStr = valueInput.Text;

            String[] valStr   = inputStr.Split(':');
            byte[]   newValue = new byte[valStr.Length];

            for (int i = 0; i < valStr.Length; i++)
            {
                newValue[i] = Convert.ToByte(valStr[i], 16);
            }

            characteristic.SetValue(newValue);
            gatt.WriteCharacteristic(characteristic);
        }
예제 #24
0
        public void WriteCommand(EVrcRigCommand command)
        {
            if (gatt == null)
            {
                return;
            }

            var ms = new MemoryStream(20);

            using (var writer = new BinaryWriter(ms)) {
                writer.Write((byte)command);
            }

            writeCharacteristic.SetValue(ms.ToArray());
            gatt.WriteCharacteristic(writeCharacteristic);
        }
        // Overridden from BaseLeConnection
        public override bool Write(byte[] packet)
        {
            if (!isConnected)
            {
                return(false);
            }

            if (writeCharacteristic.SetValue(packet))
            {
                return(gatt.WriteCharacteristic(writeCharacteristic));
            }
            else
            {
                return(false);
            }
        }
예제 #26
0
        public override void OnCharacteristicReadRequest(
            BluetoothDevice device, int requestId, int offset,
            BluetoothGattCharacteristic target)
        {
            base.OnCharacteristicReadRequest(device, requestId, offset, target);

            var guid = AsGUID(target.Uuid);

            if (characteristics.ContainsKey(guid))
            {
                var value = characteristics[guid]();

                target.SetValue(value);

                Server.SendResponse(device, requestId, GattStatus.Success,
                                    offset, value);
            }
        }
예제 #27
0
 public void Write(byte[] data)
 {
     if (!CanWrite)
     {
         throw new InvalidOperationException("Characteristic does not support WRITE");
     }
     _nativeCharacteristic.WriteType = GattWriteType.Default;
     _nativeCharacteristic.SetValue(data);
     if (!_gatt.WriteCharacteristic(_nativeCharacteristic))
     {
         Thread.Sleep(100);
         if (!_gatt.WriteCharacteristic(_nativeCharacteristic))
         {
             Thread.Sleep(100);
             _gatt.WriteCharacteristic(_nativeCharacteristic);
         }
     }
 }
예제 #28
0
        bool InternalWrite(byte[] data)
        {
            if (!CanWrite)
            {
                throw new InvalidOperationException("Characteristic does not support WRITE");
            }

            _gattCallback.CharacteristicValueWritten += OnCharacteristicValueWritten;

            _nativeCharacteristic.SetValue(data);
            Mvx.Trace(".....Write {0}", ID);

            var ret = _gatt.WriteCharacteristic(_nativeCharacteristic);

            if (!ret)
            {
                _gattCallback.CharacteristicValueWritten -= OnCharacteristicValueWritten;
            }
            return(ret);
        }
        protected override void Initialize()
        {
            base.Initialize();

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

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

            _deviceIdService = new BluetoothGattService(UUID.FromString(DEVICE_ID_SERVICE_UUID), GattServiceType.Primary);
            _deviceIdService.AddCharacteristic(_deviceIdCharacteristic);
        }
예제 #30
0
        /// <summary>
        ///
        /// </summary>
        public virtual int WriteRXCharacteristic(byte[] value)
        {
            BluetoothGattService rxService = m_Gatt
                                             .GetService(m_UuidServ);

            if (rxService == null)
            {
                return(-1);
            }
            BluetoothGattCharacteristic rxChar = rxService
                                                 .GetCharacteristic(m_UuidRx);

            if (rxChar == null)
            {
                return(-2);
            }
            rxChar.SetValue(value);
            bool status = m_Gatt.WriteCharacteristic(rxChar);

            return((status)?0:-3);
        }