public static void Main(string[] args) { IConfiguration config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json").Build(); IWebHost webHost = BuildWebHost(args, config); using (var scope = webHost.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <AnperiDbContext>(); var logger = services.GetRequiredService <ILogger <Program> >(); try { context.Database.EnsureCreated(); } catch (Exception ex) { logger.LogCritical(ex, "Error reading or creating database! Shutting down ...\nYou might want to enable InMemoryDatabase in appsettings.json."); Console.WriteLine("Error testing database ... press enter to shutdown."); return; } try { logger.LogInformation("Testing database structure ..."); Host h = new Host { Name = "SomeHost", Token = "DEBUGTOKENHOST" }; Peripheral p = new Peripheral { Name = "SomePeripheral", Token = "SOMEPERIPHERALDEBUGTOKEN" }; context.Hosts.Add(h); context.Peripherals.Add(p); context.SaveChanges(); HostPeripheral hp = new HostPeripheral { Host = h, Peripheral = p }; h.PairedDevices.Add(hp); context.SaveChanges(); var code = new ActivePairingCode { Code = "123456", PeripheralId = p.Id }; context.ActivePairingCodes.Add(code); context.SaveChanges(); context.RemoveRange(code, hp, p, h); context.SaveChanges(); logger.LogInformation("Testing database structure: SUCCESS"); } catch (Exception ex) { logger.LogCritical("Testing database structure: ERROR"); logger.LogCritical(ex, "Error testing DB structure! Shutting down ...\nYou might need to wipe the database."); Console.WriteLine("Error testing database ... press enter to shutdown."); return; } } webHost.Run(); }
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; } }