public override void OnCharacteristicReadRequest( BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) { base.OnCharacteristicReadRequest(device, requestId, offset, characteristic); if (_gattServer == null) { return; } var response = PayloadFormatter .GetBytesToSend(new PackageData(_tracingInformation.DeviceId)) .Skip(offset) .ToArray(); _logger.LogDebug($"Advertiser - Device connected. Sending response to {device.Address}. Offset={offset}, ResponseLength={response.Length}."); _gattServer.SendResponse(device, requestId, GattStatus.Success, offset, response); }
public override void OnCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, GattStatus status) { if (gatt != _btLeGattSpp._bluetoothGatt) { return; } GattStatus resultStatus = GattStatus.Failure; if (status == GattStatus.Success) { if (characteristic.Uuid != null && characteristic.Uuid.Equals(GattCharacteristicSpp)) { resultStatus = status; } } _btLeGattSpp._gattWriteStatus = resultStatus; _btLeGattSpp._btGattWriteEvent.Set(); }
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); }
public static int GetBatteryVoltage(this BluetoothGattCharacteristic characteristic) { if (characteristic == null) { return(-1); } if (characteristic.Uuid != BcoreUuid.BatteryVol) { return(-1); } var value = characteristic.GetValue(); if (value == null || value.Length != BatteryVoltageDataLength) { return(-1); } return((value[IdxBatteryVoltageDataLow] & 0xff) | (value[IdxBatteryVoltageDataHigh] << 8)); }
public BleServer(Context ctx) { _bluetoothManager = (BluetoothManager)ctx.GetSystemService(Context.BluetoothService); _bluetoothAdapter = _bluetoothManager.Adapter; _bluettothServerCallback = new BleGattServerCallback(); _bluetoothServer = _bluetoothManager.OpenGattServer(ctx, _bluettothServerCallback); var service = new BluetoothGattService(UUID.FromString("ffe0ecd2-3d16-4f8d-90de-e89e7fc396a5"), GattServiceType.Primary); _characteristic = new BluetoothGattCharacteristic(UUID.FromString("d8de624e-140f-4a22-8594-e2216b84a5f2"), GattProperty.Read | GattProperty.Notify | GattProperty.Write, GattPermission.Read | GattPermission.Write); _characteristic.AddDescriptor(new BluetoothGattDescriptor(UUID.FromString("28765900-7498-4bd4-aa9e-46c4a4fb7b07"), GattDescriptorPermission.Read | GattDescriptorPermission.Write)); service.AddCharacteristic(_characteristic); _bluetoothServer.AddService(service); _bluettothServerCallback.CharacteristicReadRequest += _bluettothServerCallback_CharacteristicReadRequest; _bluettothServerCallback.NotificationSent += _bluettothServerCallback_NotificationSent; Console.WriteLine("Server created!"); BluetoothLeAdvertiser myBluetoothLeAdvertiser = _bluetoothAdapter.BluetoothLeAdvertiser; var builder = new AdvertiseSettings.Builder(); builder.SetAdvertiseMode(AdvertiseMode.LowLatency); builder.SetConnectable(true); builder.SetTimeout(0); builder.SetTxPowerLevel(AdvertiseTx.PowerHigh); AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder(); dataBuilder.SetIncludeDeviceName(true); byte[] bytes = Encoding.ASCII.GetBytes("jp"); dataBuilder.AddManufacturerData(1984, bytes); dataBuilder.SetIncludeTxPowerLevel(true); myBluetoothLeAdvertiser.StartAdvertising(builder.Build(), dataBuilder.Build(), new BleAdvertiseCallback()); }
public sealed override void BuildCharacteristic(BluetoothGattCharacteristic characteristic) { if (!characteristic.Uuid.Equals(Uuid)) { throw new GattCharactersticMismatch(this, characteristic.Uuid); } var bytes = characteristic.GetValue(); if (bytes == null) { return; } //1 bit per flag, as a boolean TimeOffsetPresent = bytes[0].BitAt(0); GlucoseConcentrationPresent = bytes[0].BitAt(1); _glucoseConcentrationUnits = bytes[0].BitAt(2); SensorStatusAnnunciationPresent = bytes[0].BitAt(3); ContextInformationFollows = bytes[0].BitAt(4); SequenceNumber = characteristic.GetIntValue(GattFormat.Uint16, 1).IntValue(); _baseTime.ConvertFromCharacteristicByBytes(bytes.SubarrayAt(3, 9)); //7 bytes for the date. BaseTime = _baseTime.Date; TimeOffset = characteristic.GetIntValue(GattFormat.Sint16, 10).IntValue(); var glcConcentration = characteristic.GetFloatValue(GattFormat.Sfloat, 12).FloatValue(); if (_glucoseConcentrationUnits) { GlucoseConcentration = Math.Round(glcConcentration * 100000 / MmollToMgdl, 1); } else { GlucoseConcentration = Math.Round(glcConcentration * 1000 * MmollToMgdl, 1); } Type = (GlucoseTypes)bytes.SubarrayAt(14, 14).ToInt16().NibbleAt(false); SampleLocation = (GlucoseSampleLocation)bytes.SubarrayAt(14, 14).ToInt16().NibbleAt(true); //need a nibble at method //SensorStatusAnnunciation = bytes.SubarrayAt(17, 19); }
private static void SetCharacteristicNotification_private(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid) { try { bool indication; BluetoothGattCharacteristic characteristic = gatt.GetService(serviceUuid).GetCharacteristic(characteristicUuid); gatt.SetCharacteristicNotification(characteristic, true); BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(BLEHelpers.ClientCharacteristicConfig); indication = (Convert.ToInt32(characteristic.Properties) & 32) != 0; Log.Error("Indication", indication.ToString()); descriptor.SetValue(indication ? BluetoothGattDescriptor.EnableIndicationValue.ToArray() : BluetoothGattDescriptor.EnableNotificationValue.ToArray()); gatt.WriteDescriptor(descriptor); } catch (Exception e) { e.PrintStackTrace(); } }
public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { if (status != 0) { return; } if (HasCurrentTimeService(gatt)) { BluetoothGattCharacteristic timeCharacteristic = gatt.GetService(UUID.FromString("00001805-0000-1000-8000-00805f9b34fb")) .GetCharacteristic( UUID.FromString("00002A2B-0000-1000-8000-00805f9b34fb")); timeCharacteristic.SetValue(GetCurrentTimeLocal()); gatt.WriteCharacteristic(timeCharacteristic); } else { ListenToMeasurements(gatt); } }
/// <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); }
private void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { var uuid = characteristic.Uuid.ToString().ToLower(); if (_notifyList.Contains(uuid)) { var dataBytes = characteristic.GetValue(); if (OWBoard.SerialWriteUUID.Equals(uuid, StringComparison.InvariantCultureIgnoreCase) == false && OWBoard.SerialReadUUID.Equals(uuid, StringComparison.InvariantCultureIgnoreCase) == false) { // If our system is little endian, reverse the array. if (BitConverter.IsLittleEndian) { Array.Reverse(dataBytes); } } BoardValueChanged.Invoke(uuid, dataBytes); } }
public void ReadData() { _limit = 0; var bluetoothService = _bluetoothGatt.GetService(SERVICE_UUID); if (bluetoothService == null) { this.ReadDataErrorMessage = "Service of Scannner not found."; return; } _bluetoothData = bluetoothService.GetCharacteristic(DATA_UUID); if (_bluetoothData == null) { this.ReadDataErrorMessage = "Data characteristic not found."; return; } this.ReadPackage(); }
public override View GetView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.Inflate(ctx, Resource.Layout.item_service, null); holder.serviceUUID = convertView.FindViewById <TextView>(Resource.Id.service_uuid); holder.writeType = convertView.FindViewById <TextView>(Resource.Id.service_characteristics); holder.type = convertView.FindViewById <TextView>(Resource.Id.service_type); holder.chooseState = convertView.FindViewById <TextView>(Resource.Id.choose_state); convertView.SetTag(Resource.Id.service_uuid, holder.serviceUUID); convertView.SetTag(Resource.Id.service_characteristics, holder.writeType); convertView.SetTag(Resource.Id.service_type, holder.type); convertView.SetTag(Resource.Id.choose_state, holder.chooseState); } else { holder.serviceUUID = (TextView)convertView.GetTag(Resource.Id.service_uuid); holder.writeType = (TextView)convertView.GetTag(Resource.Id.service_characteristics); holder.type = (TextView)convertView.GetTag(Resource.Id.service_type); holder.chooseState = (TextView)convertView.GetTag(Resource.Id.choose_state); } BluetoothGattCharacteristic characteristic = characteristics[position]; holder.serviceUUID.Text = characteristic.Uuid + ""; holder.writeType.Text = "当前特征值WriteType为 : " + characteristic.WriteType; holder.type.Text = "当前特征值Value还没有获取到"; if (position == curPos) { holder.chooseState.Text = "当前选中状态 : 已选中"; } else { holder.chooseState.Text = "当前选中状态 : 未选中"; } return(convertView); }
/// <summary> /// Process a callback from the Gatt for device services discovered while we're connecting /// </summary> private void GattCallback_ServicesDiscovered(object sender, EventArgs e) { Debug.WriteLineIf(sw.TraceInfo, "++> GattCallback_ServicesDiscovered"); _service = _gatt.GetService(uuidService); _TX = _service.GetCharacteristic(uuidTX); _RX = _service.GetCharacteristic(uuidRX); BluetoothGattDescriptor config = _RX.GetDescriptor(uuidCharacteristicConfig); if (config == null) { Debug.WriteLineIf(sw.TraceError, "--> _RX.GetDescriptor failed"); ErrorMessage = "RX.GetDescriptor failed"; Disconnect(); return; } bool b = _gatt.SetCharacteristicNotification(_RX, true); b = config.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray()); b = _gatt.WriteDescriptor(config); // now that services are connected, we're ready to go State = BlueState.Connected; }
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; } }
public override void OnCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) { base.OnCharacteristicReadRequest(device, requestId, offset, characteristic); //Console.WriteLine("Read request from {0}", device.Name); try { //App.ItemsList.Add(new Models.Item() { Text = string.Format("Read request from {0}", device.Name) }); } catch (Exception ex) { } if (CharacteristicReadRequest != null) { CharacteristicReadRequest(this, new BleEventArgs() { Device = device, Characteristic = characteristic, RequestId = requestId, Offset = offset }); } }
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); } }
public Characteristic(BluetoothGattCharacteristic nativeCharacteristic, BluetoothGatt gatt, GattCallback gattCallback) { this._nativeCharacteristic = nativeCharacteristic; this._gatt = gatt; this._gattCallback = gattCallback; if (this._gattCallback != null) { // wire up the characteristic value updating on the gattcallback this._gattCallback.CharacteristicValueUpdated += (object sender, CharacteristicReadEventArgs e) => { // it may be other characteristics, so we need to test if (e.Characteristic.ID == this.ID) { // update our underlying characteristic (this one will have a value) //TODO: is this necessary? probably the underlying reference is the same. //this._nativeCharacteristic = e.Characteristic; this.ValueUpdated(this, e); } }; } }
public BleServer(Context ctx) { _bluetoothManager = (BluetoothManager)ctx.GetSystemService(Context.BluetoothService); _bluetoothAdapter = _bluetoothManager.Adapter; _bluettothServerCallback = new BleGattServerCallback(); _bluetoothServer = _bluetoothManager.OpenGattServer(ctx, _bluettothServerCallback); var service = new BluetoothGattService(UUID.FromString("ffe0ecd2-3d16-4f8d-90de-e89e7fc396a5"), GattServiceType.Primary); _characteristic = new BluetoothGattCharacteristic(UUID.FromString("d8de624e-140f-4a22-8594-e2216b84a5f2"), GattProperty.Read | GattProperty.Notify | GattProperty.Write, GattPermission.Read | GattPermission.Write); service.AddCharacteristic(_characteristic); _bluetoothServer.AddService(service); SensorSpeed speed = SensorSpeed.UI; OrientationSensor.Start(speed); OrientationSensor.ReadingChanged += OrientationSensor_ReadingChanged; _bluettothServerCallback.CharacteristicReadRequest += _bluettothServerCallback_CharacteristicReadRequest; Console.WriteLine("Server created!"); BluetoothLeAdvertiser myBluetoothLeAdvertiser = _bluetoothAdapter.BluetoothLeAdvertiser; var builder = new AdvertiseSettings.Builder(); builder.SetAdvertiseMode(AdvertiseMode.LowLatency); builder.SetConnectable(true); builder.SetTimeout(0); builder.SetTxPowerLevel(AdvertiseTx.PowerHigh); AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder(); dataBuilder.SetIncludeDeviceName(true); dataBuilder.SetIncludeTxPowerLevel(true); myBluetoothLeAdvertiser.StartAdvertising(builder.Build(), dataBuilder.Build(), new BleAdvertiseCallback()); }
//ble注册的服务中的特征值改变的回调 public override void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { lock (charNotifyListeners) { base.OnCharacteristicChanged(gatt, characteristic); byte[] values = characteristic.GetValue(); string uuid = characteristic.Uuid + ""; string str = "changed characteristic's uuid is : " + characteristic.Uuid + "\r\n"; str += "changed characteristic's WriteType is : " + characteristic.WriteType + "\r\n"; str += "changed characteristic's GetValue is "; //Log.Error("dana.ye->xamarin->bt", str); foreach (byte b in values) { str += ": " + b; } //Log.Error("dana.ye->xamarin->bt", str); foreach (ICharacteristicNotifyListener cListener in charNotifyListeners) { cListener.OnCharacteristicCallback(characteristic); } } }
//ble设置服务中的特征值的回调 public override void OnCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, [GeneratedEnum] GattStatus status) { lock (charListeners) { base.OnCharacteristicWrite(gatt, characteristic, status); byte[] values = characteristic.GetValue(); string uuid = characteristic.Uuid + ""; string str = "write characteristic's uuid is : " + characteristic.Uuid + "\r\n"; str += "write characteristic's WriteType is : " + characteristic.WriteType + "\r\n"; str += "write characteristic's GetValue is "; //Log.Error("dana.ye->xamarin->bt", str); foreach (byte b in values) { str += ": " + b; } Log.Error("dana.ye->xamarin->bt", str); foreach (ICharacteristicCallbackListener cListener in charListeners) { cListener.OnCharacteristicCallback(characteristic); } } }
public void BroadcastUpdate(String action, BluetoothGattCharacteristic characteristic) { Intent intent = new Intent(action); // This is special handling for the Heart Rate Measurement profile. Data parsing is // carried out as per profile specifications: // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml if (SampleGattAttributes.PRESSURE_NOTIFICATION_HANDLE.Equals(characteristic.Uuid.ToString())) { logger.TraceInformation("Building Broadcaster: Pressure characteristic data"); logger.TraceInformation(characteristic.Uuid.ToString()); // For all other profiles, writes the data formatted in HEX. byte[] data = characteristic.GetValue(); if (data != null && data.Length > 0) { Bundle extras = new Bundle(); long lData = 0; String sData; var stringBytes = BitConverter.ToString(data); lData = BytesToLong(data, 0, 1); sData = lData.ToString(); extras.PutString(EXTRA_DATA, stringBytes); extras.PutString(EXTRA_SENSOR_A, sData); extras.PutString(EXTRA_SENSOR_B, BytesToLong(data, 2, 3).ToString()); intent.PutExtras(extras); } } SendBroadcast(intent); }
public override void OnCharacteristicWriteRequest( BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, bool preparedWrite, bool responseNeeded, int offset, byte[] value) { base.OnCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value); if (CharacteristicWriteRequest != null) { CharacteristicWriteRequest(this, new BleEventArgs() { Device = device, ResponseNeeded = responseNeeded, RequestId = requestId, Characteristic = characteristic, PreparedWrite = preparedWrite, Offset = offset, Value = value }); } }
public GattCharacteristic(BluetoothGattCharacteristic bluetoothGattCharacteristic) { BluetoothGattCharacteristic = bluetoothGattCharacteristic; }
internal GattCharacteristic(GattService service, Android.Bluetooth.BluetoothGattCharacteristic characteristic) : this(service) { _characteristic = characteristic; }
public override void OnCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, bool preparedWrite, bool responseNeeded, int offset, byte[] value) { base.OnCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value); ASCIIEncoding ascii = new ASCIIEncoding(); string decoded = ascii.GetString(value); //Console.WriteLine("Input: [{0}]", decoded); try { //App.ItemsList.Add(new Models.Item() { Text = string.Format("Write request [{0}]", decoded) }); } catch (Exception ex) { } if (CharacteristicWriteRequest != null) { CharacteristicWriteRequest(this, new BleEventArgs() { Device = device, Characteristic = characteristic, Value = value, RequestId = requestId, Offset = offset }); } }
public override void OnCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, GattStatus status) { base.OnCharacteristicWrite(gatt, characteristic, status); }
public override void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { base.OnCharacteristicChanged(gatt, characteristic); CharacteristicValueUpdated?.Invoke(this, new CharacteristicReadCallbackEventArgs(characteristic)); }
public GattCharacteristicEventArgs(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, GattStatus status) : base(gatt, status) { this.Characteristic = characteristic; }
public GattCharacteristicEventArgs(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) : this(gatt, characteristic, GattStatus.Success) { }
//Call Back BLE onDiscovered private void Blecallback_Discovered_Event(List <BluetoothServiceDevice> obj) { bool findDeviceJOY = false; bool findDeviceTELEMETRY = false; BluetoothGattCharacteristic clientchar = null; //Verifica Servizi se sono compatibili foreach (BluetoothServiceDevice s in obj) { string myservice = myUUID.DEVICE_SERVICE_UUID.Replace("-", "").ToLower(); if (s.service.Uuid.ToString().Replace("-", "").ToLower() == myservice) { if (s.characteristic.Uuid.ToString().Replace("-", "").ToLower() == myUUID.JOY_CHARACTERISTIC_CONFIG.Replace("-", "").ToLower()) { findDeviceJOY = true; if (joyBLE == null) { joyBLE = new BluetoothServiceDevice(); } joyBLE.service = s.service; joyBLE.characteristic = s.characteristic; joyBLE.gatt = s.gatt; } else if (s.characteristic.Uuid.ToString().Replace("-", "").ToLower() == myUUID.TELEMETRY_CHARACTERISTIC_CONFIG.Replace("-", "").ToLower()) { findDeviceTELEMETRY = true; if (telemetryBLE == null) { telemetryBLE = new BluetoothServiceDevice(); } telemetryBLE.service = s.service; telemetryBLE.characteristic = s.characteristic; telemetryBLE.gatt = s.gatt; } } } if ((findDeviceJOY) && (findDeviceTELEMETRY)) { //Richietsa Attivavazione Char Notification ble.CLoseAll_SetCharacteristicNotification(); ble.SetCharacteristicNotification(telemetryBLE.gatt, telemetryBLE.characteristic, myUUID.CLIENT_UUID); } else { // ************************************************************************************************************************************************************************************************************************************************************** /* Handler mHandler = new Handler(); * mHandler.PostDelayed(new Action(delegate { * Finish(); * }), 2000); */ if (obj != null) { foreach (BluetoothServiceDevice s in obj) { if (s.gatt != null) { s.gatt.Disconnect(); s.gatt.Close(); } } } activity.RunOnUiThread(() => Action_Error("Errore Connessione!!!")); } }