DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 91b9f272c4d67610ecba7dde64dedf81eef504a3 deck-builder/sdbclient/src/plugins/connection_check/mod.rs -rw-r--r-- 1.6 KiB
91b9f272Jonni Liljamo Start of API mod and connection check plugin 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
/*
 * 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 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
            // Load the splash when we enter the Splash state
            .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_hidden: Res<CfgHidden>) {
    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)>,
) {
    for (entity, mut task) in &mut connection_check_tasks {
        if let Some(api_info) = future::block_on(future::poll_once(&mut task.0)) {
            info!("API connection check passed");
            info!("API version: {}", api_info.ver);

            // Remove the task, since it's done now
            commands.entity(entity).remove::<ConnectionCheck>();
            commands.entity(entity).despawn_recursive();
        }
    }
}