/* * 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::CfgDev}; /// 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_dev: Res) { let api_address = cfg_dev.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(res) = future::block_on(future::poll_once(&mut task.0)) { match res { Ok(api_info) => { console.send(PrintConsoleLine::new( "API connection check passed".to_string().into(), )); console.send(PrintConsoleLine::new( format!("API version: {}", api_info.ver).into(), )); } Err(err) => { console.send(PrintConsoleLine::new( "API connection check FAILED with following error:" .to_string() .into(), )); console.send(PrintConsoleLine::new(err.into())); } } // Remove the task, since it's done now commands.entity(entity).remove::(); commands.entity(entity).despawn_recursive(); } } }