DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 0ad660668e80040bdd2b7cf9f5d5f35da4f14b6a deck-builder/sdbclient/src/plugins/connection_check/mod.rs -rw-r--r-- 2.3 KiB
0ad66066Jonni Liljamo chore(sdbapi): add nhyoor.io/websocket dep 1 year, 10 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
66
67
68
69
70
71
72
73
74
75
76
/*
 * 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<Result<api::APIInfo, String>>);

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(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::<ConnectionCheck>();
            commands.entity(entity).despawn_recursive();
        }
    }
}