DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 1e00855d67f5580c8d446a0d24621986e4dae0b5 deck-builder/sdbclient/src/plugins/connection_check/mod.rs -rw-r--r-- 1.8 KiB
1e00855dJonni Liljamo Create a constants file 1 year, 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * This file is part of sdbclient
 * Copyright (C) 2022 Jonni Liljamo <jonni@liljamo.com>
 *
 * 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<api::APIInfo>);

fn start_connection_check(mut commands: Commands, cfg_dev: Res<CfgDev>) {
    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<PrintConsoleLine>,
) {
    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::<ConnectionCheck>();
            commands.entity(entity).despawn_recursive();
        }
    }
}