/* * This file is part of sdbclient * Copyright (C) 2022 Jonni Liljamo * * Licensed under GPL-3.0-only. * See LICENSE for licensing information. */ use bevy::{ prelude::*, tasks::{AsyncComputeTaskPool, Task}, }; use bevy_console::PrintConsoleLine; use futures_lite::future; use crate::{api, cfg::CfgHidden}; /// This plugin will check if we can connect to the API pub struct ConnectionCheckPlugin; impl Plugin for ConnectionCheckPlugin { fn build(&self, app: &mut App) { app // Start the check at the start .add_startup_system(start_connection_check) .add_system(handle_connection_check); } } #[derive(Component)] struct ConnectionCheck(Task); fn start_connection_check(mut commands: Commands, cfg_hidden: Res) { let api_address = cfg_hidden.api_server.clone(); let thread_pool = AsyncComputeTaskPool::get(); let task = thread_pool.spawn(async move { let api_info = api::info(api_address); api_info }); commands.spawn(ConnectionCheck(task)); } fn handle_connection_check( mut commands: Commands, mut connection_check_tasks: Query<(Entity, &mut ConnectionCheck)>, mut console: EventWriter, ) { for (entity, mut task) in &mut connection_check_tasks { if let Some(api_info) = future::block_on(future::poll_once(&mut task.0)) { console.send(PrintConsoleLine::new( "API connection check passed".to_string(), )); console.send(PrintConsoleLine::new(format!( "API version: {}", api_info.ver ))); // Remove the task, since it's done now commands.entity(entity).remove::(); commands.entity(entity).despawn_recursive(); } } }