private async Task readTemp() { ICharacteristic characteristic = null; for (int i = 0; i < characteristics.Count; i++) { if (characteristics[i].Key.Equals("tempData")) { characteristic = characteristics[i].Value; } } characteristic.ValueUpdated += (o, args) => { byte[] bytes = args.Characteristic.Value; temperatureData = AmbientData(bytes); onPropertyChanged(nameof(TemperatureData)); }; await characteristic.StartUpdatesAsync(); }
private async void InitalizeCommandButton_Clicked(object sender, EventArgs e) { try { var service = await _connectedDevice.GetServiceAsync(GattIdentifiers.UartGattServiceId); if (service != null) { sendCharacteristic = await service.GetCharacteristicAsync(GattIdentifiers.UartGattCharacteristicSendId); receiveCharacteristic = await service.GetCharacteristicAsync(GattIdentifiers.UartGattCharacteristicReceiveId); if (receiveCharacteristic != null) { var descriptors = await receiveCharacteristic.GetDescriptorsAsync(); receiveCharacteristic.ValueUpdated += (o, args) => { var receivedBytes = args.Characteristic.Value; XamarinEssentials.MainThread.BeginInvokeOnMainThread(() => { Output.Text += Encoding.UTF8.GetString(receivedBytes, 0, receivedBytes.Length) + Environment.NewLine; }); }; await receiveCharacteristic.StartUpdatesAsync(); InitButton.IsEnabled = !(ScanButton.IsEnabled = true); } } else { Output.Text += "UART GATT service not found." + Environment.NewLine; } } catch { Output.Text += "Error initializing UART GATT service." + Environment.NewLine; } }
async Task Connect(IReadOnlyList <IService> services) { var adapter = CrossBluetoothLE.Current.Adapter; service = services.FirstOrDefault((s) => s.Id == GUID_SERVICE); if (null == service) { throw new Exception("GUID_SERVICE_THERMO not avaliable."); } var chars = await service.GetCharacteristicsAsync(); charMeasValue = chars.FirstOrDefault((c) => c.Id == GUID_CHAR_THERMO_VALUE); charMeasType = chars.FirstOrDefault((c) => c.Id == GUID_CHAR_THERMO_TYPE); if ((charMeasValue == null) || (charMeasType == null)) { throw new Exception("some characteristics not avaliable."); } await charMeasValue.ReadAsync(); await charMeasType.ReadAsync(); if ((charMeasValue.Properties & (CharacteristicPropertyType.Notify | CharacteristicPropertyType.Indicate)) > 0) { charMeasValue.ValueUpdated += CharMeasValue_ValueUpdated; await charMeasValue.StartUpdatesAsync(); useNotify = true; } uiRefresh.IsVisible = !useNotify; Title = "Thermometer Service"; uiMeasType.Text = measType[charMeasType.Value[0]]; ShowMeasValue(charMeasValue.Value); }
public async Task Connect() { try { Adapter = CrossBluetoothLE.Current.Adapter; await Adapter.ConnectToDeviceAsync(Device); var service = await Device.GetServiceAsync(serviceGuid).ConfigureAwait(false); writeCharacteristic = await service.GetCharacteristicAsync(writeGuid).ConfigureAwait(false); readCharacteristic = await service.GetCharacteristicAsync(readGuid).ConfigureAwait(false); MainThread.BeginInvokeOnMainThread(async() => { readCharacteristic.ValueUpdated += ReadCharacteristic_ValueUpdated; await readCharacteristic.StartUpdatesAsync(); }); } catch (Exception ex) { Debug.WriteLine($"Sorry an error while sending command - {ex.Message}"); } }
public async Task <IBleResult> StartObservingAsync() { IBleResult result; try { if (_bleCharacteristic == null) { result = BleResult.Failure(BleFailure.DeviceNotInitialized); } else if (!_bleCharacteristic.CanUpdate) { result = BleResult.Failure(BleFailure.UpdateNotSupported); } else { if (!IsObserving) { await _bleCharacteristic.StartUpdatesAsync().ConfigureAwait(false); IsObserving = true; } result = BleResult.Success(); } } catch (TimeoutException) { result = BleResult.Failure(BleFailure.OperationTimeout); } catch (Exception e) { result = BleResult.Failure(e); } return(result); }
private async Task SubscribeToUpdatesAsync(ICharacteristic aCharacteristic) { aCharacteristic.ValueUpdated += BluetoothNotifyReceivedHandler; await aCharacteristic.StartUpdatesAsync(); }
public async Task EnableNotification(ICharacteristic characteristic) { characteristic.ValueUpdated += OnValueAvailable; await characteristic.StartUpdatesAsync(); }
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"; } }
/// <summary> /// Opens the connection interface associated with this Bluetooth device. /// </summary> /// <exception cref="Exception">If there is any problem opening the connection with this bluetooth /// device.</exception> /// <exception cref="XBeeException">If there is any XBee error.</exception> /// <seealso cref="IsOpen"/> /// <seealso cref="Close"/> public void Open() { Debug.WriteLine("----- Open"); // Do nothing if the device is already open. if (IsOpen) { return; } string connectExceptionMessage = null; // Create a task to connect the device. Task task = Task.Run(async() => { try { // Abort the connect operation if the given timeout expires. CancellationTokenSource token = new CancellationTokenSource(); token.CancelAfter(CONNECTION_TIMEOUT); // Connect the device. Try to connect up to 3 times. var retries = BT_CONNECT_RETRIES; while (!IsOpen && retries > 0) { if (device == null) { device = await adapter.ConnectToKnownDeviceAsync(deviceGuid, new ConnectParameters(), token.Token); } else { await adapter.ConnectToDeviceAsync(device, new ConnectParameters(), token.Token); } await Task.Delay(1000); if (device != null && device.State == DeviceState.Connected) { IsOpen = true; } retries--; } // Check if device is connected. if (!IsOpen) { throw new Exception(); } // Request a larger MTU. mtu = await device.RequestMtuAsync(REQUESTED_MTU); Console.WriteLine("----- MTU: " + mtu); // Get the TX and RX characteristics. IService service = await device.GetServiceAsync(Guid.Parse(SERVICE_GUID)); if (service == null) { throw new Exception(ERROR_GET_SERVICE); } txCharacteristic = await service.GetCharacteristicAsync(Guid.Parse(TX_CHAR_GUID)); rxCharacteristic = await service.GetCharacteristicAsync(Guid.Parse(RX_CHAR_GUID)); if (txCharacteristic == null || rxCharacteristic == null) { throw new Exception(ERROR_GET_CHARS); } // Subscribe to the RX characteristic. if (rxCharacteristic.CanUpdate) { rxCharacteristic.ValueUpdated += DataReceived; await rxCharacteristic.StartUpdatesAsync(); } encrypt = false; } catch (Exception e) { connectExceptionMessage = e.Message == null ? ERROR_CONNECTION : ERROR_CONNECTION + " > " + e.Message; } finally { lock (connectLock) { Monitor.Pulse(connectLock); } } }); if (!task.IsCompleted) { // Wait until the task finishes. lock (connectLock) { Monitor.Wait(connectLock); } } // If the task finished with excepction, throw it. if (connectExceptionMessage != null) { if (device != null && device.State != DeviceState.Connected) { IsOpen = false; } Close(); throw new XBeeException(connectExceptionMessage); } // If the task was cancelled, throw an exception. if (task.IsCanceled) { if (device != null && device.State != DeviceState.Connected) { IsOpen = false; } Close(); throw new XBeeException(ERROR_CONNECTION_CANCELED); } // Check again if the device is connected. We've seen that sometimes the // Rx subscribe process could make the device to disconnect. if (device != null && device.State != DeviceState.Connected) { IsOpen = false; Close(); throw new XBeeException(ERROR_CONNECTION); } }
private async Task <byte[]> ReceiveFrame() { const UInt32 waitCommand = 0x00040000; const UInt32 packetCommand = 0x3F3F3F3F; const UInt32 bigFileCommand = 0x3F3F0001; try { if (!_isConnected) { return(await Task.FromResult(new byte[0])); } else { bool isWaitCommand = false; do { await Task.Delay(100); await _analyzerChar.StopUpdatesAsync(); if (_responseFrame == null || _responseFrame.Length == 0) { throw new Exception("dimensione della risposta errata!"); } // Controllo il marker string marker = Encoding.ASCII.GetString(_responseFrame, 0, 4); if (marker != _frameMarker) { string tmp = ""; foreach (byte data in _responseFrame) { tmp += data.ToString("X2"); } throw new Exception("invalid marker, received: " + tmp); } // Controllo il crc UInt32 crcSent = ArrConverter.GetUInt32FromBuffer(_responseFrame, _responseFrame.Length - 4); UInt32 crcCalc = Crc32_STM.CalculateFromBuffer(_responseFrame, _responseFrame.Length - 4); if (crcSent != crcCalc) { throw new Exception("invalid crc"); } // Controllo se ho una risposta con codice di errore UInt32 errorCode = ArrConverter.GetUInt32FromBuffer(_responseFrame, 4); if (errorCode != 0) { throw new Exception(errorCode.ToString()); } if (_responseFrame.Length == 16) { if (ArrConverter.GetUInt32FromBuffer(_responseFrame, 8) == waitCommand) { isWaitCommand = true; } } else if (_responseFrame.Length == 20) { if (ArrConverter.GetUInt32FromBuffer(_responseFrame, 8) == packetCommand) { int totalSize = (int)ArrConverter.GetUInt32FromBuffer(_responseFrame, 12); int packetsNum = ((totalSize % 20) == 0) ? (totalSize / 20) : ((totalSize / 20) + 1); var fullResponse = new byte[totalSize]; // Il device cerca di trasmettere un pacchetto await _analyzerChar.StartUpdatesAsync(); await SendCommand(packetCommand); for (var packetIndex = 0; packetIndex < packetsNum; packetIndex++) { await Task.Delay(100); await _analyzerChar.StopUpdatesAsync(); if (_responseFrame == null || _responseFrame.Length == 0) { throw new Exception("dimensione della risposta errata!"); } _responseFrame.CopyTo(fullResponse, 20 * packetIndex); await _analyzerChar.StartUpdatesAsync(); await SendCommand(packetCommand); } return(await Task.FromResult(fullResponse)); } else if (ArrConverter.GetUInt32FromBuffer(_responseFrame, 8) == bigFileCommand) { int totalSize = (int)ArrConverter.GetUInt32FromBuffer(_responseFrame, 12); int receivedLength = 0; // Alloco un buffer per l'intero file e il preambolo // Per adesso ignoro il preambolo e copio soltanto il buffer contenente il file byte[] fullRespose = new byte[totalSize + 16]; // Il device cerca di trasmettere un pacchetto await _analyzerChar.StartUpdatesAsync(); await SendCommand(packetCommand); while (receivedLength < totalSize) { await Task.Delay(100); await _analyzerChar.StopUpdatesAsync(); if (_responseFrame == null || _responseFrame.Length == 0) { throw new Exception("dimensione della risposta errata!"); } // Copio partendo da 12 e poi in base alla dimensione dei pacchetti ricevuti Buffer.BlockCopy(_responseFrame, 0, fullRespose, receivedLength + 12, _responseFrame.Length); MessagingCenter.Send <IAnalyzerDevice, double>(this, "DownloadFileProgress", (double)receivedLength / totalSize); receivedLength += _responseFrame.Length; await _analyzerChar.StartUpdatesAsync(); await SendCommand(packetCommand); } return(await Task.FromResult(fullRespose)); } } await _analyzerChar.StartUpdatesAsync(); }while (isWaitCommand); } await _analyzerChar.StartUpdatesAsync(); return(await Task.FromResult(_responseFrame)); } catch (Exception ex) { await _analyzerChar.StartUpdatesAsync(); throw ex; } }
public async Task <bool> ConnectToDeviceAsync() { var ble = CrossBluetoothLE.Current; var adapter = CrossBluetoothLE.Current.Adapter; List <IDevice> deviceList = new List <IDevice>(); _isConnecting = true; adapter.DeviceDiscovered += (s, a) => deviceList.Add(a.Device); await adapter.StartScanningForDevicesAsync(); IDevice device = deviceList.Find(x => x.Name == _deviceName); if (device == null) { return(await Task.FromResult(false)); } try { await adapter.ConnectToDeviceAsync(device); _isConnected = true; } catch (Exception e) { // Non ho potuto connettermi al dispositivo _isConnected = false; _isConnecting = false; throw e; } try { List <IService> services = (List <IService>) await device.GetServicesAsync(); List <ICharacteristic> characteristics = (List <ICharacteristic>) await services[1].GetCharacteristicsAsync(); _analyzerChar = characteristics.Find(x => x.Uuid == _analyzerCharacteristic); _analyzerChar.ValueUpdated += OnCharacteristicValueUpdated; await _analyzerChar.StartUpdatesAsync(); await GetDeviceInfo(); } catch (Exception e) { // C'è stato un errore successivamente _isConnected = false; _isConnecting = false; await adapter.DisconnectDeviceAsync(device); throw e; } _isConnecting = false; //ICharacteristic analyzerChar = characteristics.Find(x => x.Uuid == AnalyzerCharacteristic); //analyzerChar.ValueUpdated += CharUpdated; return(await Task.FromResult(true)); }
private async void Adapter_DeviceConnected(object sender, Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs e) { try { Device.BeginInvokeOnMainThread(new Action(() => { BtImage.Source = "bt_on.png"; })); service = await device.GetServiceAsync(Guid.Parse // HM-10 servis UUID si seçldi ("0000FFE0-0000-1000-8000-00805F9B34FB")); characteristic = await service.GetCharacteristicAsync(Guid.Parse // HM-10 RX/TX karakteristigi seçldi ("0000FFE1-0000-1000-8000-00805F9B34FB")); await characteristic.StartUpdatesAsync(); characteristic.ValueUpdated += async(o, args) => // Arduino dan gelen datalar içn bildirim servisi çğrılacak { var bytes = args.Characteristic.Value; if (ReadPages) { if (VerifyRead) { Array.Copy(bytes, 0, combined, shift19, bytes.Length); shift19 += bytes.Length; if (shift19 == 130) { for (int i = 0; i < 128; i++) { ReadPageBytes[VerifyReadPageNumber, i] = combined[i + 1]; } PageCounter++; ReadPagesEnd = true; } } else { Array.Copy(bytes, 0, combined, shift19, bytes.Length); shift19 += bytes.Length; if (shift19 == 130) { for (int i = 0; i < 128; i++) { ReadPageBytes[PageCounter, i] = combined[i + 1]; } PageCounter++; ReadPagesEnd = true; } } //bleReadPage.Insert(jjs,(byte)(bytes.Length)); //jjs++; //if (bytes[0] == 0x14) //{ // if (shift19 == 0) // { // Array.Copy(bytes, 1, combined, shift19, 19); // shift19 += 19; // } //} //if (shift19 > 118 && bytes.Length==10) //{ // Array.Copy(bytes, 0, combined, shift19, 8); // ReadPagesEnd = true; // ReadPages = false; //} //if (shift19 > 0 && shift19 < 119 && bytes.Length==20) //{ // Array.Copy(bytes, 0, combined, shift19, 20); // shift19 += 20; //} } if (bytes[0] == 0x14 && !ReadPages) { if (ReadPages) { } else { if (bytes.Length == 2) { if (bytes[1] == 0x10) { ResponseOk = true; } } } } }; } catch { } }
private async void ConnectToWoundSensorAsync(IDevice device) { try { //await adapter.StopScanningForDevicesAsync(); if (device != null && device.Name == "HET Wound v2.1-001") { string notif = ("You've connected to " + device.Name); await adapter.ConnectToDeviceAsync(device); Service = await device.GetServiceAsync(het); char4 = await Service.GetCharacteristicAsync(char4_uuid); char1 = await Service.GetCharacteristicAsync(char1_uuid); try { await char1.WriteAsync(cmd_string); } catch { } char4.ValueUpdated += CharacteristicsChanged; await char4.StartUpdatesAsync(); //if (SensorDetailsPage.UpdateDeviceName != null) //{ // SensorDetailsPage.UpdateDeviceName(device.Name.ToString()); //} //if (SensorDetailsPage.UpdateConnectionStatus != null) //{ // SensorDetailsPage.UpdateConnectionStatus("Connected"); //} var message = new NotifyMessage { Message = notif }; Device.BeginInvokeOnMainThread( () => MessagingCenter.Send(message, "NotifyMessage") ); } else { var message = new NotifyMessage { Message = "Device not supported !" }; Device.BeginInvokeOnMainThread( () => MessagingCenter.Send(message, "NotifyMessage") ); } } catch (DeviceConnectionException ex) { var message = new NotifyMessage { Message = ex.Message.ToString() }; Device.BeginInvokeOnMainThread( () => MessagingCenter.Send(message, "NotifyMessage") ); } }
public async void CheckMyCharacteristic(ICharacteristic characteristic) { await characteristic.StartUpdatesAsync(); }
private async void InitalizeCommandButton_Clicked(object sender, EventArgs e) { try { var service = await _connectedDevice.GetServiceAsync(GattIdentifiers.UartGattServiceId); if (service != null) { sendCharacteristic = await service.GetCharacteristicAsync(GattIdentifiers.UartGattCharacteristicSendId); receiveCharacteristic = await service.GetCharacteristicAsync(GattIdentifiers.UartGattCharacteristicReceiveId); if (receiveCharacteristic != null) { var descriptors = await receiveCharacteristic.GetDescriptorsAsync(); receiveCharacteristic.ValueUpdated += (o, args) => { var receivedBytes = args.Characteristic.Value; XamarinEssentials.MainThread.BeginInvokeOnMainThread(() => { btdata += Encoding.UTF8.GetString(receivedBytes, 0, receivedBytes.Length); // + Environment.NewLine; if (btdata.Substring(0, 3) != "EEE") { btdata = null; } //----------Uncomment the lines below to display the Datas length-----------\\ //tring btData = receivedBytes.Length.ToString(); // RawData.Text = btdata; //----------Uncomment the lines below to display the RawData----------\\ //RawData.Text = btdata; var dataLength = btdata.Length; if (dataLength >= 39 && (btdata.Substring(37, 2) == "GG")) //Checks to make sure the recived data is the correct length { dataParse(); formatTheData(); InitButton.BackgroundColor = Color.Transparent; btdata = null; //Removes previous string after parsing data\ } else if (dataLength >= 39) { btdata = null; } }); }; await receiveCharacteristic.StartUpdatesAsync(); // InitButton.IsEnabled = !(ScanButton.IsEnabled = true); } } else { // Output1.Text += "UART GATT service not found." + Environment.NewLine; } } catch { // Output1.Text += "Error initializing UART GATT service." + Environment.NewLine; } }
/// <summary> /// Connects to the specified device and completes encryption handshake/key generation. /// </summary> /// <param name="deviceName">Name of the device to connect to.</param> public async Task <bool> ConnectToDevice(string deviceName) //, Func<bool> DisconnectedHanlder { //adapter.DeviceConnectionLost += (s, a) => //{ // DisconnectedHanlder(); //}; try { IDevice device = null; foreach (IDevice i in deviceList) { if (i.Name == deviceName) { device = i; break; } } await adapter.ConnectToDeviceAsync(device); OnPropertyChanged("BluetoothState"); PairedDevice = device; var service = await device.GetServiceAsync(Guid.Parse("913CF3FD-7173-43A5-82F4-DFD6F61BAF5F")); characteristic = await service.GetCharacteristicAsync(Guid.Parse("44B1DF4E-15C8-4F97-9F34-123D33B0C29D")); X9ECParameters x9 = ECNamedCurveTable.GetByName("secp256r1"); ECCurve curve = x9.Curve; ECDomainParameters ecDomain = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); ECKeyPairGenerator generator = (ECKeyPairGenerator)GeneratorUtilities.GetKeyPairGenerator("ECDH"); generator.Init(new ECKeyGenerationParameters(ecDomain, new SecureRandom())); AsymmetricCipherKeyPair appKeyPair = generator.GenerateKeyPair(); ECPublicKeyParameters appPublicKey = (ECPublicKeyParameters)appKeyPair.Public; ECPrivateKeyParameters appPrivateKey = (ECPrivateKeyParameters)appKeyPair.Private; // Wait for Arduino Public Key characteristic.ValueUpdated += GetPubKeyPortion; await characteristic.StartUpdatesAsync(); Task.Run(CheckIfKeyObtainComplete).Wait(); // Once full Key has been obtained, stop reading characteristic and unregister handler await characteristic.StopUpdatesAsync(); characteristic.ValueUpdated -= GetPubKeyPortion; // Cut off 'starting' padding from beginning of arduino's public key & convert to byte array ArdPubKeyStr = ArdPubKeyStr.Substring(8); // Now send the app's public key to arduino via same characteristic string appPublicKeyStr = appPublicKey.Q.ToString(); string appPubKey_x = appPublicKey.Q.XCoord.ToString(); string appPubKey_y = appPublicKey.Q.YCoord.ToString(); for (int i = 0; i < 64 - appPubKey_x.Length; i++) { appPubKey_x = "0" + appPubKey_x; } for (int i = 0; i < 64 - appPubKey_y.Length; i++) { appPubKey_y = "0" + appPubKey_y; } appPublicKeyStr = appPubKey_x + appPubKey_y; char[] pubkey_chars = appPublicKeyStr.ToCharArray(); byte[] pubkey_bytes = new byte[128]; for (int i = 0; i < 128; i++) { pubkey_bytes[i] = Convert.ToByte(pubkey_chars[i]); } byte[][] chunks = pubkey_bytes .Select((c, i) => new { Value = c, Index = i }) .GroupBy(x => x.Index / 16) .Select(grp => grp.Select(x => x.Value).ToArray()) .ToArray(); foreach (byte[] b in chunks) { await characteristic.WriteAsync(b); } BigInteger Q_x = new BigInteger(1, StringToByteArray(ArdPubKeyStr.Substring(0, 64))); BigInteger Q_y = new BigInteger(1, StringToByteArray(ArdPubKeyStr.Substring(64, 64))); ECPoint Q = curve.CreatePoint(Q_x, Q_y); ECPublicKeyParameters ArdPubKey = new ECPublicKeyParameters(Q, ecDomain); // Extract the shared secret for decryption IBasicAgreement agreement = new Org.BouncyCastle.Crypto.Agreement.ECDHBasicAgreement(); agreement.Init(appPrivateKey); sharedKey = agreement.CalculateAgreement(ArdPubKey); Debug.WriteLine("Shared KEY: " + ByteArrayToString(sharedKey.ToByteArrayUnsigned())); characteristic.ValueUpdated += GetEncryptedMessagePortion; await characteristic.StartUpdatesAsync(); return(true); } catch (DeviceConnectionException) { Debug.WriteLine("Could not connect to device"); return(false); } catch (Exception e) { Debug.WriteLine(e.Message); return(false); } }
private async Task ConnectDevice(IDevice deviceConnected, string service) { Debug.WriteLine("Intentando conexion con: " + deviceConnected.Name); try { if (deviceConnected.State == DeviceState.Disconnected) { await adapter.ConnectToDeviceAsync(deviceConnected); lDevicesConnected.Add(deviceConnected); Debug.WriteLine("Dispositivo conectado: " + deviceConnected.Name); //Servicios y caracteristicas y descriptores var services = await deviceConnected.GetServicesAsync(); IService customerService = null; foreach (IService iService in services) { if (iService.Id.Equals(new Guid(service))) { customerService = iService; } } var characteristics = await customerService.GetCharacteristicsAsync(); UnicodeEncoding uniencoding = new UnicodeEncoding(); byte[] one = uniencoding.GetBytes("0"); ICharacteristic characteristicRW = null; //Buscamos la caracteristica que permite escribir, leer y actualizar foreach (ICharacteristic characteristic in characteristics) { if (characteristic.CanRead && characteristic.CanWrite && characteristic.CanUpdate) { characteristicRW = characteristic; } } await characteristicRW.WriteAsync(one); characteristicRW.ValueUpdated += (s, a) => { byte[] valueBytes = a.Characteristic.Value; Debug.WriteLine("BYTE 1:" + valueBytes[0]); Debug.WriteLine("BYTE 1:" + valueBytes[1]); Debug.WriteLine("BYTE 1:" + valueBytes[2]); Debug.WriteLine("BYTE 1:" + valueBytes[3]); Debug.WriteLine("BYTE 1:" + valueBytes[4]); String data = string.Concat(valueBytes.Select(b => b.ToString("X2"))); for (var n = 0; n < valueBytes.Length; n++) { Console.WriteLine(string.Format("BYTES [{0}] = {1}", n, valueBytes[n])); } DeviceData deviceData = new DeviceData(); deviceData.DeviceName = deviceConnected.Name; deviceData.Data = data; lDeviceData.Add(deviceData); Debug.WriteLine(data, "Leyendo datos de " + deviceConnected.Name + ": "); }; await characteristicRW.StartUpdatesAsync(); //var bytes = await characteristics[0].ReadAsync(); } } catch (DeviceConnectionException ex) { await Application.Current.MainPage.DisplayAlert("Atención", "Se ha producido un error al conectar con el dispositivo " + deviceConnected.Name, "Aceptar"); Debug.WriteLine("Error al conectar con el dispositivo: " + deviceConnected.Name + "." + ex); } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert("Atención", "Se ha producido un error al conectar con los dispositivos ", "Aceptar"); Debug.WriteLine("Error al conectar con el dispositivo: " + deviceConnected.Name + "." + ex); } }
async void Button_Clicked(object sender, EventArgs e) { if (device == null) { await DisplayAlert("No Bluetooth", "No Bluetooth connected, " + "please connect BLE first.", "OK"); await Navigation.PopModalAsync(); } await adapter.ConnectToDeviceAsync(device); var services = await device.GetServicesAsync(); foreach (var service in services) { var characteristics = await service.GetCharacteristicsAsync(); foreach (var characteristic in characteristics) { Console.WriteLine(service.Id + " - " + characteristic.Id); if (characteristic.Id == Guid.Parse(dataviewmodel.Characteristic_UUID_1)) { Characteristic1 = characteristic; Console.WriteLine("Find Characteristic 1."); } if (characteristic.Id == Guid.Parse(dataviewmodel.Characteristic_UUID_2)) { Characteristic2 = characteristic; Console.WriteLine("Find Characteristic 2."); } if (characteristic.Id == Guid.Parse(dataviewmodel.Characteristic_UUID_3)) { Characteristic3 = characteristic; Console.WriteLine("Find Characteristic 3."); } if (characteristic.Id == Guid.Parse(dataviewmodel.Characteristic_UUID_4)) { Characteristic4 = characteristic; Console.WriteLine("Find Characteristic 4."); } if (characteristic.Id == Guid.Parse(dataviewmodel.Characteristic_UUID_5)) { Characteristic5 = characteristic; Console.WriteLine("Find Characteristic 5."); } if (characteristic.Id == Guid.Parse(dataviewmodel.Characteristic_UUID_6)) { Characteristic6 = characteristic; Console.WriteLine("Find Characteristic 6."); } if (characteristic.Id == Guid.Parse(dataviewmodel.Characteristic_UUID_7)) { Characteristic7 = characteristic; Console.WriteLine("Find Characteristic 7."); } } } Characteristic1.ValueUpdated += (o, args) => { var bytes = args.Characteristic.Value; string message = System.Text.Encoding.ASCII.GetString(bytes); dataviewmodel.TEMPERATURE = dataviewmodel.messagespliter(message, 0); dataviewmodel.PRESSURE = dataviewmodel.messagespliter(message, 1); }; await Characteristic1.StartUpdatesAsync(); Characteristic2.ValueUpdated += (o, args) => { var bytes = args.Characteristic.Value; string message = System.Text.Encoding.ASCII.GetString(bytes); dataviewmodel.HUMIDITY = dataviewmodel.messagespliter(message, 0); dataviewmodel.VOC = dataviewmodel.messagespliter(message, 1); }; await Characteristic2.StartUpdatesAsync(); Characteristic3.ValueUpdated += (o, args) => { var bytes = args.Characteristic.Value; string message = System.Text.Encoding.ASCII.GetString(bytes); dataviewmodel.ALTITUDE = dataviewmodel.messagespliter(message, 0); dataviewmodel.CO2 = dataviewmodel.messagespliter(message, 1); }; await Characteristic3.StartUpdatesAsync(); Characteristic4.ValueUpdated += (o, args) => { var bytes = args.Characteristic.Value; string message = System.Text.Encoding.ASCII.GetString(bytes); dataviewmodel.LIGHT = dataviewmodel.messagespliter(message, 0); dataviewmodel.ROTATE = dataviewmodel.messagespliter(message, 1); }; await Characteristic4.StartUpdatesAsync(); Characteristic5.ValueUpdated += (o, args) => { var bytes = args.Characteristic.Value; string message = System.Text.Encoding.ASCII.GetString(bytes); dataviewmodel.RED = dataviewmodel.messagespliter(message, 0); dataviewmodel.GREEN = dataviewmodel.messagespliter(message, 1); }; await Characteristic5.StartUpdatesAsync(); Characteristic6.ValueUpdated += (o, args) => { var bytes = args.Characteristic.Value; string message = System.Text.Encoding.ASCII.GetString(bytes); dataviewmodel.BLUE = dataviewmodel.messagespliter(message, 0); dataviewmodel.VIOLET = dataviewmodel.messagespliter(message, 1); }; await Characteristic6.StartUpdatesAsync(); Characteristic7.ValueUpdated += (o, args) => { var bytes = args.Characteristic.Value; string message = System.Text.Encoding.ASCII.GetString(bytes); dataviewmodel.YELLOW = dataviewmodel.messagespliter(message, 1); dataviewmodel.ORANGE = dataviewmodel.messagespliter(message, 0); }; await Characteristic7.StartUpdatesAsync(); }
private async void loop() { bool previousResult = false; try { while (true) { if (GlobalVariables.connection == true) { //Specifieke GuiD van de SERVICE (nodig) service = await GlobalVariables.device.GetServiceAsync(Guid.Parse("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")); //Specifieke GuiD van de characteristic NOTIFY characteristic = await service.GetCharacteristicAsync(Guid.Parse("6E400003-B5A3-F393-E0A9-E50E24DCCA9E")); //De waarden van die characteristic Updaten en vervolgens in een variabele plaatsen genaamd "bytes" characteristic.ValueUpdated += (o, args) => { //var bytes = args.Characteristic.Value; }; await characteristic.StartUpdatesAsync(); //de bytes opvangen in een variabele var bytes = characteristic.Value; //Bytes omzetten naar een string GlobalVariables.result = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length); var date = DateTime.Now; //Boolean voor 1 of 0 Boolean isStanding = false; if (GlobalVariables.result == "1.00") { isStanding = true; } //Als er verandering is in de waarde dan verstuurd hij deze naar de database if (previousResult != isStanding) { Track track = new Track(); track.UserId = GlobalVariables.user.UserId; track.Date = DateTime.Now.AddHours(1); track.isStanding = isStanding; track.MacDevice = GlobalVariables.device.Name; await ImaniManager.AddTrack(track); previousResult = isStanding; } await Task.Delay(5000); } else if (GlobalVariables.connection == false) { await Task.Delay(1000); } } } catch (Exception) { await MainPage.DisplayAlert("Disconnected", "You are no longer connected with your shoe", "Ok"); CrossLocalNotifications.Current.Show("Connection lost", "You are no longer connected with your shoe"); GlobalVariables.connection = false; } }
public async Task <bool> ConnectAsync() { try { await StopDiscover(); await _adapter.ConnectToDeviceAsync(SelectedDevice); var serialIoService = await GetSerialIoService(SelectedDevice); var inBuf = Guid.Parse(Settings.InBufCharacteristicsId); var outBuf = Guid.Parse(Settings.OutBufCharacteristicsId); _inBuf = await serialIoService.GetCharacteristicAsync(inBuf); _outBuf = await serialIoService.GetCharacteristicAsync(outBuf); _inBuf.ValueUpdated += ReadWrite_ValueUpdated; switch (_platform) { case Platform.Undefined: await _inBuf.StartUpdatesAsync(); break; case Platform.iOS: try { await _inBuf.StartUpdatesAsync(); } catch (Exception e) { // This is to be expected on iOS if pair dialog is not dismissed in approx 4 seconds. await _inBuf.StartUpdatesAsync(); } break; case Platform.Android: // The StartUpdatesAsync task hangs forever when we connect the first time and are paired through the OS. var startUpdateTask = _inBuf.StartUpdatesAsync(); if (await Task.WhenAny(startUpdateTask, Task.Delay(2000)) != startUpdateTask) { await _inBuf.StopUpdatesAsync(); await _inBuf.StartUpdatesAsync(); } break; default: throw new ArgumentOutOfRangeException(); } Connected?.Invoke(this, SelectedDevice); return(true); } catch (Exception e) { OnError("Connect to device failed!", e.Message); OnDisconnected(e.Message); } return(false); }