| 101 | } |
| 102 | |
| 103 | pub async fn subscribe(&mut self, on_value_changed: NotifiyEventHandler) -> Result<()> { |
| 104 | { |
| 105 | let value_handler = TypedEventHandler::new( |
| 106 | move |_: Ref<GattCharacteristic>, args: Ref<GattValueChangedEventArgs>| { |
| 107 | if let Ok(args) = args.ok() { |
| 108 | let value = args.CharacteristicValue()?; |
| 109 | let reader = DataReader::FromBuffer(&value)?; |
| 110 | let len = reader.UnconsumedBufferLength()? as usize; |
| 111 | let mut input: Vec<u8> = vec![0u8; len]; |
| 112 | reader.ReadBytes(&mut input[0..len])?; |
| 113 | trace!("changed {:?}", input); |
| 114 | on_value_changed(input); |
| 115 | } |
| 116 | Ok(()) |
| 117 | }, |
| 118 | ); |
| 119 | let token = self.characteristic.ValueChanged(&value_handler)?; |
| 120 | self.notify_token = Some(token); |
| 121 | } |
| 122 | let config = to_descriptor_value(self.characteristic.CharacteristicProperties()?); |
| 123 | if config == GattClientCharacteristicConfigurationDescriptorValue::None { |
| 124 | return Err(Error::NotSupported("Can not subscribe to attribute".into())); |
| 125 | } |
| 126 | |
| 127 | let status = self |
| 128 | .characteristic |
| 129 | .WriteClientCharacteristicConfigurationDescriptorAsync(config)? |
| 130 | .into_future() |
| 131 | .await?; |
| 132 | trace!("subscribe {:?}", status); |
| 133 | if status == GattCommunicationStatus::Success { |
| 134 | Ok(()) |
| 135 | } else { |
| 136 | Err(Error::Other( |
| 137 | format!("Windows UWP threw error on subscribe: {:?}", status).into(), |
| 138 | )) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | pub async fn unsubscribe(&mut self) -> Result<()> { |
| 143 | if let Some(token) = &self.notify_token { |