internal void OnDeviceHubConnected(string workstationId, IRemoteCommands caller) { Task.Run(async() => { RemoteDeviceDescription descr = null; try { _appConnections.TryGetValue(workstationId, out descr); if (descr != null) { var connectionContainer = _connectionContainers.GetOrAdd(workstationId, (c) => new DeviceConnectionContainer(caller, _deviceId)); var deviceConnection = new SignalRRemoteDeviceConnection(connectionContainer); var commandQueue = new CommandQueue(deviceConnection, null); var deviceCommands = new HesDeviceCommands(connectionContainer); var remoteDevice = new Device(commandQueue, channelNo, deviceCommands, null); descr.Device = remoteDevice; await remoteDevice.VerifyAndInitialize(); // Inform clients about connection ready descr.Tcs.TrySetResult(remoteDevice); } } catch (Exception ex) { descr.Device = null; // inform clients about connection fail descr.Tcs?.TrySetException(ex); } }); }
public async Task <Device> ConnectDevice(string workstationId) { RemoteDeviceDescription descr = null; if (workstationId == null) { // trying to connect to any workstation, first, look for that where Device is not empty descr = _appConnections.Values.Where(x => x.Device != null).FirstOrDefault(); if (descr == null) { descr = _appConnections.Values.FirstOrDefault(); } } else { _appConnections.TryGetValue(workstationId, out descr); } if (descr == null) { throw new HideezException(HideezErrorCode.DeviceNotConnectedToAnyHost); } TaskCompletionSource <Device> tcs = null; lock (descr) { if (descr.Device != null) { return(descr.Device); } tcs = descr.Tcs; if (tcs == null) { descr.Tcs = new TaskCompletionSource <Device>(); } } if (tcs != null) { return(await tcs.Task); } try { // call Hideez Client to make remote channel await descr.AppConnection.EstablishRemoteHwVaultConnection(_deviceId, channelNo); await descr.Tcs.Task.TimeoutAfter(20_000); return(descr.Device); } catch (TimeoutException) { var ex = new HideezException(HideezErrorCode.RemoteConnectionTimedOut); descr.Tcs.TrySetException(ex); throw ex; } catch (Exception ex) { descr.Tcs.TrySetException(ex); throw; } finally { lock (descr) { descr.Tcs = null; } } }