private async Task RemoveLoggedInDevice(AuthenticatedWebSocketConnection connection, AnperiDbContext dbContext) { lock (_syncRootActiveConnections) { _activeConnections.Remove(connection.Device.Id); } await OnDeviceLoggedOut(connection, dbContext); }
private async void PartnerCloseConnection() { lock (_syncRootPartner) { _partner = null; } await _socket.SendJson(SharedJsonApiObjectFactory.CreatePartnerDisconnected()); }
private async Task <bool> PartnerConnect(AuthenticatedWebSocketConnection connection) { lock (_syncRootPartner) { _partner?.PartnerCloseConnection(); _partner = connection; } await _socket.SendJson( SharedJsonApiObjectFactory.CreatePartnerConnected(connection.Device.Name), CancellationToken.None); return(true); }
private async Task OnDeviceLoggedIn(AuthenticatedWebSocketConnection connection, AnperiDbContext dbContext) { IEnumerable <int> pairedDeviceIds = await GetPairedDeviceIds(connection.Device, dbContext); lock (_activeConnections) { foreach (int pairedDeviceId in pairedDeviceIds) { _activeConnections.TryGetValue(pairedDeviceId, out var c); c?.OnPairedDeviceLogin(this, new AuthenticatedWebSocketEventArgs(connection)); } } }
public async void OnPairedDeviceLogoff(object sender, AuthenticatedWebSocketEventArgs e) { if (e.Connection.Device.Id == _partner?.Device.Id) { lock (_syncRootPartner) { _partner = null; } await _socket.SendJson(SharedJsonApiObjectFactory.CreatePartnerDisconnected()); } lock (_syncRootLoggedInPairedDevices) { _loggedInPairedDevices.Remove(e.Connection); } await _socket.SendJson( HostJsonApiObjectFactory.CreatePairedPeripheralLoggedOffMessage(e.Connection.Device.Id)); }
private async Task <WebSocketCloseStatus> LoginDevice(HttpContext context, WebSocket socket, byte[] buffer, RegisteredDevice device, AnperiDbContext dbContext) { await socket.SendJson(SharedJsonApiObjectFactory.CreateLoginResponse(true, device.Name)); List <AuthenticatedWebSocketConnection> connectedPairedDevices = await GetOnlinePairedDevices(device, dbContext); var connection = new AuthenticatedWebSocketConnection(context, socket, buffer, device, dbContext, _logger, this, connectedPairedDevices); lock (_syncRootActiveConnections) { _activeConnections.Add(connection.Device.Id, connection); } WebSocketCloseStatus closeStatus; try { await OnDeviceLoggedIn(connection, dbContext); closeStatus = await connection.Run(_options.Value.RequestCancelToken); } catch (WebSocketException se) { if (!(se.InnerException is BadHttpRequestException)) { throw; } closeStatus = WebSocketCloseStatus.Empty; _logger.LogWarning( $"BadHttpRequestException occured while handling a websocket: {se.Message} -> {se.InnerException.Message}"); } finally { if (!connection.IsAborted) { await RemoveLoggedInDevice(connection, dbContext); } } return(closeStatus); }
private async Task HandleHostMessage(JsonApiObject message, CancellationToken token) { HostRequestCode msgCode; try { msgCode = Enum.Parse <HostRequestCode>(message.message_code); } catch (Exception) { await _socket.SendJson(SharedJsonApiObjectFactory.CreateError($"{message.message_code} is not a valid message code (or I forgot it)."), token); return; } switch (msgCode) { case HostRequestCode.pair: if (!message.data.TryGetValue("code", out string code)) { await _socket.SendJson( SharedJsonApiObjectFactory.CreateError("Parameter code not set or null."), token); return; } try { ActivePairingCode pairingCode = _db.ActivePairingCodes.SingleOrDefault(p => p.Code.Equals(code)); if (pairingCode == null) { await _socket.SendJson( SharedJsonApiObjectFactory.CreateError("Pairing code was not valid."), token); return; } Peripheral deviceToPair = _db.Peripherals.Find(pairingCode.PeripheralId); if (deviceToPair != null) { if (deviceToPair.PairedDevices.All(hp => hp.PeripheralId != deviceToPair.Id)) { deviceToPair.PairedDevices.Add(new HostPeripheral { HostId = Device.Id, PeripheralId = deviceToPair.Id }); _db.ActivePairingCodes.Remove(pairingCode); } } else { await _socket.SendJson( SharedJsonApiObjectFactory.CreateError( "The device you want to pair isn't known to me :(")); return; } _db.Remove(pairingCode); _db.SaveChanges(); AuthenticatedWebSocketConnection conn = _anperiManager.GetConnectionForId(deviceToPair.Id); if (conn != null) { OnPairedDeviceLogin(null, new AuthenticatedWebSocketEventArgs(conn)); } await _socket.SendJson(HostJsonApiObjectFactory.CreatePairingResponse(true, deviceToPair.Id)); } catch (Exception e) { await _socket.SendJson( SharedJsonApiObjectFactory.CreateError($"Internal error handling this request: {e.GetType()} - {e.Message}"), token); } break; case HostRequestCode.unpair: if (message.data.TryGetValue("id", out int peripheralId)) { HostPeripheral connection = _db.HostPeripherals.SingleOrDefault(hp => hp.HostId == _device.Id && hp.PeripheralId == peripheralId); if (connection != null) { try { _db.HostPeripherals.Remove(connection); (_device as Host)?.PairedDevices.Remove(connection); _db.SaveChanges(); AuthenticatedWebSocketConnection loggedInPeripheral; lock (_syncRootLoggedInPairedDevices) { loggedInPeripheral = _loggedInPairedDevices.SingleOrDefault(c => c.Device.Id == peripheralId); } if (loggedInPeripheral != null) { OnPairedDeviceLogoff(null, new AuthenticatedWebSocketEventArgs(loggedInPeripheral)); } await _socket.SendJson( HostJsonApiObjectFactory.CreateUnpairFromPeripheralResponse(true)); } catch (Exception ex) { _logger.LogError(ex, "Error unpairing devices."); await _socket.SendJson( HostJsonApiObjectFactory.CreateUnpairFromPeripheralResponse(false)); } } } else { await _socket.SendJson(SharedJsonApiObjectFactory.CreateError("id not defined")); } break; case HostRequestCode.get_available_peripherals: IEnumerable <Peripheral> peripherals = _db.HostPeripherals.Where(hp => hp.HostId == _device.Id).Select(p => p.Peripheral); IEnumerable <HostJsonApiObjectFactory.ApiPeripheral> apiPeris = peripherals.Select( p => new HostJsonApiObjectFactory.ApiPeripheral { id = p.Id, name = p.Name }).ToList(); lock (_syncRootLoggedInPairedDevices) { _loggedInPairedDevices.ForEach(d => { apiPeris.Single(p => p.id == d.Device.Id).online = true; }); } await _socket.SendJson( HostJsonApiObjectFactory.CreateAvailablePeripheralResponse(apiPeris), token); break; case HostRequestCode.connect_to_peripheral: if (message.data.TryGetValue("id", out int id)) { if (!_db.HostPeripherals.Any(hp => hp.HostId == _device.Id && hp.PeripheralId == id)) { await _socket.SendJson( HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(false, -1)); return; } AuthenticatedWebSocketConnection conn = _anperiManager.GetConnectionForId(id); if (conn != null) { if (await conn.PartnerConnect(this)) { lock (_syncRootPartner) { _partner = conn; } await _socket.SendJson( HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(true, id)); } else { await _socket.SendJson(HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(false, -1)); } } else { await _socket.SendJson(HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(false, -1)); } } else { await _socket.SendJson(HostJsonApiObjectFactory.CreateConnectToPeripheralResponse(false, -1)); } break; case HostRequestCode.disconnect_from_peripheral: lock (_syncRootPartner) { _partner?.PartnerCloseConnection(); _partner = null; } await _socket.SendJson(HostJsonApiObjectFactory.CreateDisconnectFromPeripheralResponse(true), token); break; case HostRequestCode.change_peripheral_name: if (message.data.TryGetValue("name", out string newName) && message.data.TryGetValue("id", out int periId)) { HostPeripheral hp = _db.HostPeripherals.SingleOrDefault(e => e.HostId == _device.Id && e.PeripheralId == periId); if (hp == null) { await _socket.SendJson( HostJsonApiObjectFactory.CreateChangeNameResponse(false, null, periId)); return; } if (string.IsNullOrWhiteSpace(newName)) { await _socket.SendJson( HostJsonApiObjectFactory.CreateChangeNameResponse(false, hp.Peripheral.Name, periId)); return; } Peripheral p = hp.Peripheral; p.Name = newName; _db.SaveChanges(); await _socket.SendJson( HostJsonApiObjectFactory.CreateChangeNameResponse(true, newName, periId)); } else { await _socket.SendJson(SharedJsonApiObjectFactory.CreateError("name or id not defined")); } break; default: await _socket.SendJson(SharedJsonApiObjectFactory.CreateError($"Function {msgCode.ToString()} not implemented yet."), token); _logger.LogWarning($"HostRequestCode.{msgCode.ToString()} not implemented."); break; } }
public AuthenticatedWebSocketEventArgs(AuthenticatedWebSocketConnection connection) { Connection = connection; }