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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use std::convert::TryFrom;
use std::net::SocketAddr;
use std::sync::Arc;

use thiserror::Error;

use super::types::i32_to_duration;

use crate::{
    component::ComponentName,
    global::{
        Global, InputMessage, InputMessageData, InputSourceHandle, InputSourceName, PriorityGuard,
    },
    image::{RawImage, RawImageError},
    models::Color,
};

/// Schema definitions as Serde serializable structures and enums
pub mod message;

#[derive(Debug, Error)]
pub enum FlatApiError {
    #[error("error broadcasting update: {0}")]
    Broadcast(#[from] tokio::sync::broadcast::error::SendError<InputMessage>),
    #[error("source not registered")]
    Unregistered,
    #[error("invalid priority for registration, should be in [100, 200), got {0}")]
    InvalidPriority(i32),
    #[error("unknown command")]
    UnknownCommand,
    #[error("error decoding image: {0}")]
    RawImageError(#[from] RawImageError),
}

async fn handle_register(
    peer_addr: SocketAddr,
    register: message::Register<'_>,
    source: &mut Option<InputSourceHandle<InputMessage>>,
    global: &Global,
    priority_guard: &mut Option<PriorityGuard>,
) -> Result<(), FlatApiError> {
    let priority = register.priority();

    if !(100..200).contains(&priority) {
        return Err(FlatApiError::InvalidPriority(priority));
    } else {
        // unwrap: we checked the priority value before
        let new_source = global
            .register_input_source(
                InputSourceName::FlatBuffers {
                    peer_addr,
                    origin: register.origin().to_owned(),
                },
                Some(priority),
            )
            .await
            .unwrap();

        // Update priority guard
        *priority_guard = Some(PriorityGuard::new_broadcast(&new_source));
        *source = Some(new_source);
    }

    Ok(())
}

#[instrument(skip(request, source, global, priority_guard))]
pub async fn handle_request(
    peer_addr: SocketAddr,
    request: message::Request<'_>,
    source: &mut Option<InputSourceHandle<InputMessage>>,
    global: &Global,
    priority_guard: &mut Option<PriorityGuard>,
) -> Result<(), FlatApiError> {
    if let Some(handle) = source.as_ref() {
        // unwrap: we set a priority when we got the register call
        let priority = handle.priority().unwrap();

        if let Some(clear) = request.command_as_clear() {
            // Update state
            if clear.priority() < 0 {
                handle.send(ComponentName::FlatbufServer, InputMessageData::ClearAll)?;
            } else {
                handle.send(
                    ComponentName::FlatbufServer,
                    InputMessageData::Clear {
                        priority: clear.priority(),
                    },
                )?;
            }
        } else if let Some(color) = request.command_as_color() {
            let rgb = color.data();
            let rgb = (
                (rgb & 0x000_000FF) as u8,
                ((rgb & 0x0000_FF00) >> 8) as u8,
                ((rgb & 0x00FF_0000) >> 16) as u8,
            );

            // Update state
            handle.send(
                ComponentName::FlatbufServer,
                InputMessageData::SolidColor {
                    // TODO
                    priority: 0,
                    duration: i32_to_duration(Some(color.duration())),
                    color: Color::from_components(rgb),
                },
            )?;
        } else if let Some(image) = request.command_as_image() {
            // Get raw image
            let data = image
                .data_as_raw_image()
                .ok_or_else(|| RawImageError::RawImageMissing)?;

            // Extract fields
            let duration = image.duration();
            let width = data.width();
            let height = data.height();
            let data = data.data().ok_or_else(|| RawImageError::RawImageMissing)?;

            // Parse message
            let width = u32::try_from(width).map_err(|_| RawImageError::InvalidWidth)?;
            let height = u32::try_from(height).map_err(|_| RawImageError::InvalidHeight)?;
            let raw_image = RawImage::try_from((data.bytes().to_vec(), width, height))?;

            // Update state
            handle.send(
                ComponentName::FlatbufServer,
                InputMessageData::Image {
                    priority,
                    duration: i32_to_duration(Some(duration)),
                    image: Arc::new(raw_image),
                },
            )?;
        } else if let Some(register) = request.command_as_register() {
            return handle_register(peer_addr, register, source, global, priority_guard).await;
        } else {
            return Err(FlatApiError::UnknownCommand);
        }
    } else if let Some(register) = request.command_as_register() {
        return handle_register(peer_addr, register, source, global, priority_guard).await;
    } else {
        return Err(FlatApiError::Unregistered);
    };

    Ok(())
}