| 279 | } |
| 280 | |
| 281 | pub async fn connect<ConnectorType>( |
| 282 | &self, |
| 283 | mut connector: ConnectorType, |
| 284 | ) -> Result<(), ButtplugClientError> |
| 285 | where |
| 286 | ConnectorType: ButtplugConnector<ButtplugClientMessageV4, ButtplugServerMessageV4> + 'static, |
| 287 | { |
| 288 | if self.connected() { |
| 289 | return Err(ButtplugClientError::ButtplugConnectorError( |
| 290 | ButtplugConnectorError::ConnectorAlreadyConnected, |
| 291 | )); |
| 292 | } |
| 293 | |
| 294 | // If connect is being called again, clear out the device map and start over. |
| 295 | self.device_map.clear(); |
| 296 | |
| 297 | // Take the request receiver - if None, a previous connection consumed it and we can't reconnect |
| 298 | // without creating a new client (the sender is tied to this receiver) |
| 299 | let request_receiver = self.request_receiver.lock().await.take().ok_or( |
| 300 | ButtplugConnectorError::ConnectorGenericError( |
| 301 | "Cannot reconnect - request channel already consumed. Create a new client.".to_string(), |
| 302 | ), |
| 303 | )?; |
| 304 | |
| 305 | info!("Connecting to server."); |
| 306 | let (connector_sender, connector_receiver) = mpsc::channel(256); |
| 307 | connector.connect(connector_sender).await.map_err(|e| { |
| 308 | error!("Connection to server failed: {:?}", e); |
| 309 | ButtplugClientError::from(e) |
| 310 | })?; |
| 311 | info!("Connection to server succeeded."); |
| 312 | let mut client_event_loop = ButtplugClientEventLoop::new( |
| 313 | self.connected.clone(), |
| 314 | connector, |
| 315 | connector_receiver, |
| 316 | self.event_stream.clone(), |
| 317 | self.message_sender.clone(), |
| 318 | request_receiver, |
| 319 | self.device_map.clone(), |
| 320 | ); |
| 321 | |
| 322 | // Start the event loop before we run the handshake. |
| 323 | buttplug_core::spawn!("ButtplugClient event loop", async move { |
| 324 | client_event_loop.run().await; |
| 325 | }); |
| 326 | self.run_handshake().await |
| 327 | } |
| 328 | |
| 329 | /// Creates the ButtplugClient instance and tries to establish a connection. |
| 330 | /// |